Word Square Actionscript 3.0 - loops

Using the letters of the word the user inputs, I want to print a square by shifting the letters of the word to the left one position on each line.For example, since COMPUTERS has nine letters, its square will be nine characters across by nine characters down. In each row, each character will be shifted to the end. However, the following program only does one iteration. Please advise. Thanks!
btnDetermine.addEventListener(MouseEvent.CLICK, displayVowels);
function displayVowels(e: MouseEvent): void {
var str1:String;
var str2:String = "";
var i:Number;
str1 = String(txtinString.text);
i=0;
for (i=0; i<str1.length;i++){
str2 = str2 + str1.charAt(i);
}
str2 = str2 + str1.charAt();
lblString.text += str1.charAt(i) + "\r" + str2 ;
}

function displayVowels(e:MouseEvent):void {
//defines your original string
var myString:String = String(txtinString.text);
//the total character length of the original text, determine how many lines to print
var tLength:int = myString.length;
//clears out the textfield in case theres already something on it
lblString.text = "";
//print the first line
lblString.appendText(myString);
//this loops through every line except line1, we printed line1 above
//thus tLength - 1
for (var line:uint = 0; line < tLength - 1; line++) {
//line break
lblString.appendText("\n");
//shift the characters
myString = shiftChar(myString);
//print the result into the textfield
//use appendText instead of textfield += "new text'
lblString.appendText(myString);
}
}
function shiftChar(_myString:String):String {
//save the char at the front, add it to the back later
var offset:String = _myString.charAt(0);
//slice the original string so that the first char is now removed
_myString = _myString.slice(1, _myString.length);
//add the first char of the original string to the back
_myString = _myString + offset;
//return the final results
return _myString;
}

Related

Optimizing a do while loop/for loop in C

I was doing an exercise from LeetCode in which consisted in deleting any adjacent elements from a string, until there are only unique characters adjacent to each other. With some help I could make a code that can solve most testcases, but the string length can be up to 10^5, and in a testcase it exceeds the time limit, so I'm in need in some tips on how can I optimize it.
My code:
char res[100000]; //up to 10^5
char * removeDuplicates(char * s){
//int that verifies if any char from the string can be deleted
int ver = 0;
//do while loop that reiterates to eliminate the duplicates
do {
int lenght = strlen(s);
int j = 0;
ver = 0;
//for loop that if there are duplicates adds one to ver and deletes the duplicate
for (int i = 0; i < lenght ; i++){
if (s[i] == s[i + 1]){
i++;
j--;
ver++;
}
else {
res[j] = s[i];
}
j++;
}
//copying the res string into the s to redo the loop if necessary
strcpy(s,res);
//clar the res string
memset(res, '\0', sizeof res);
} while (ver > 0);
return s;
}
The code can't pass a speed test that has a string that has around the limit (10^5) length, I won't put it here because it's a really big text, but if you want to check it, it is the 104 testcase from the LeetCode Daily Problem
If it was me doing something like that, I would basically do it like a simple naive string copy, but keep track of the last character copied and if the next character to copy is the same as the last then skip it.
Perhaps something like this:
char result[1000]; // Assumes no input string will be longer than this
unsigned source_index; // Index into the source string
unsigned dest_index; // Index into the destination (result) string
// Always copy the first character
result[0] = source_string[0];
// Start with 1 for source index, since we already copies the first character
for (source_index = 1, dest_index = 0; source_string[source_index] != '\0'; ++source_index)
{
if (source_string[source_index] != result[dest_index])
{
// Next character is not equal to last character copied
// That means we can copy this character
result[++dest_index] = source_string[source_index];
}
// Else: Current source character was equal to last copied character
}
// Terminate the destination string
result[dest_index + 1] = '\0';

Why will my function not loop as expected?

Below is a code sample for a function that removes similar adjacent characters in a string. For a given arguement like remove_adjacent("azyyzb"), the expected output should be ab, since it should first remove adjacent characters yy to get substring azzb. It should then remove adjacent characters zz in the substring, to finally get substring ab. However, my function only handles the first adjacent characters, and fails to handle the second part. It could be an indication that it is not looping as expected. Could someone point out what the problem might be?
public static void remove_adjacent(String str1)
{
int i = 0;
do
{
int j = i + 1;
if (str1.charAt(i) == str1.charAt(j))
str1 = str1.substring(0, i) + str1.substring(j + 1, str1.length());
i++;
}
while (i < str1.length() - 1);
System.out.println(str1);
}
Because your i is already pointing at index 2 when you remove yy. But your first z is at index 1, which won't be checked anymore.
When you remove a part of the string, you will need to go one position backwards in your string to check, if a new pair of equal characters was created. And you must only step forward, if nothing was removed in the current iteration.
public static void remove_adjacent(String str1)
{
int i = 0;
do
{
int j = i + 1;
if (str1.charAt(i) == str1.charAt(j)) {
str1 = str1.substring(0, i) + str1.substring(j + 1, str1.length());
if (i > 0) i--;
} else {
i++;
}
}
while (i < str1.length() - 1);
System.out.println(str1);
}

char array printing 1 char short of what I assigned

I am trying to create a character array with X number of characters.
I need the first X-1 characters to be spaces and I need the Xth character to be an *.
I have written the following:
int i = 0;
int X = 5;
char spaces[X]; //In this case X is 5 so the array should have indexes 0 - 4
for(i = 0; i < X; i++) {
spaces[i] = '*'; //I start by setting all 5 char's equal to '*'
printf("spaces = '%s'\n", spaces); //This was to make sure it ran the correct # of times
}
The output of this segment is the following, the 'gh' is different every time:
spaces = '*gh'
spaces = '**h'
spaces = '***'
spaces = '****'
spaces = '****'
why does spaces only grow to 4 instead of 5 characters?
Shouldn't spaces[4] = '*'; have been called?
After setting the whole string equal to '*' I run a second for loop:
for(i = 0; i < X-1; i++) {
spaces[i] = ' ';
}
which should then set everything but the Xth character equal to ' ', but since the string is acting like its only X-1 characters long, the whole thing is set to spaces and it comes out like this
spaces = ' ';
4 spaces, when I need 4 spaces followed by an *.
You are missing the string termination character \0, which is needed once you want to print your array as a string using printf("%s",...).
So make your array one item larger than the items you want to print, and initialize it with 0, such that everything you write into the array will at the end be a valid string. Otherwise you yield undefined behaviour:
int main (void)
{
#define X 5
int i = 0;
char spaces[X+1] = { 0 };
for(i = 0; i < X; i++) {
spaces[i] = '*';
printf("spaces = '%s'\n", spaces);
}
}
In order to set first X-1 characters to be spaces and the Xth character to be an .
This will always have the last character a ''
for(i = 0; i < X-1; i++) {
spaces[i] = ' ';
spaces[i+1] = '*';
printf("spaces = '%s'\n", spaces);
}

C# Problems importing a file to an array and put each character in it's own index

I have a problem importing a text file to an array and put each character in it's own index?
Here is my code:
class Program
{
static void Main(string[] args)
{
string content = File.ReadAllText("Labyrint.txt", Encoding.UTF8);
// Use ToCharArray to convert string to array.
char[] array = content.ToCharArray();
Console.WriteLine(content);
// Loop through array.
for (int i = 0; i < array.Length; i++)
{
// Get character from array.
char letter = array[i];
// Display each letter.
Console.Write("Letter: " + letter);
// Console.WriteLine(letter);
}
}
}
The problem is it only display some of the characters? Now if I change the code a little to this:
class Program
{
static void Main(string[] args)
{
string content = File.ReadAllText("Labyrint.txt", Encoding.UTF8);
// Use ToCharArray to convert string to array.
char[] array = content.ToCharArray();
Console.WriteLine(content);
// Loop through array.
for (int i = 0; i < array.Length; i++)
{
// Get character from array.
char letter = array[i];
// Display each letter.
Console.Write("Letter: " + letter);
//Console.WriteLine(letter);
}
}
}
Then it display all the charaters in the array, but when I try to find out what index each character are in and add the 'i' to this code Console.Write("Letter: " + letter); so the code looks like this:
class Program
{
static void Main(string[] args)
{
string content = File.ReadAllText("Labyrint.txt", Encoding.UTF8);
// Use ToCharArray to convert string to array.
char[] array = content.ToCharArray();
Console.WriteLine(content);
// Loop through array.
for (int i = 0; i < array.Length; i++)
{
// Get character from array.
char letter = array[i];
// Display each letter.
Console.Write(" Letter: " + letter + " " + i);
//Console.WriteLine(letter);
}
}
}
The result go crazy and look like this:
Output Vindue
The text file is the one below, and I placed it in the debug folder in my project so I didn't had to provide a path.
TextFile
I tried the following code and it seems to work, if this still doesn't work it's likely you're using the wrong encoding type and the file has a different encoding than UTF-8.
If that is the case then open the file in an editor like Notepad++ and see what the encoding for the file is
EDIT
The reason it looks like it was starting at line 191 instead of 0 was you were exceeding the buffer height of the console, so below I've added code to set the buffer height to it's maximum. depending on the application you might want to use a smaller value.
class Program{
static void Main(string[] args){
//Increase Console Buffer Height
Console.BufferHeight = Int16.MaxValue - 1;
string content = File.ReadAllText(#"Labyrint.txt", Encoding.UTF8);
// Use ToCharArray to convert string to array.
char[] array = content.ToCharArray();
// Loop through array
for (int i =0; i<array.Length; i++) {
string letter = arrray[i].ToString()
.Replace("\r","\\r").Replace("\n", "\\n")
.Replace("\t","\\t").Replace(" ","<space>");
// Display each letter
Console.WriteLine("Letter {0}: {1}", i, letter);
}
Console.ReadLine();
}
}

Spelling a word backwords

For all of the following words, if you move the first letter to the end of the
word, and then spell the result backwards, you will get the original word:
banana dresser grammar potato revive uneven assess
I got the first part down, moving the first letter to the end, but I am not able to spell the word in reverse. I have to use a for loop for this, but I have no idea how to use it so it will spell the rest of the word backwards.
Normally the for-loop does not care in which way you modify the index, so you should be able to use something like
string firstAtLast = "otatop";
string reverse = "";
for(int i=string.length-1; i => 0; i--)
{
reverse += firstAtLast.At(i)
}
Details for i and the string manipulation methods depend on your language of course.
This should do the trick (C#)
public void ReverseWord()
{
var word = "banana dresser grammar potato revive uneven assess";
var length = word.Length;
string reverse = "";
for (int i = 0; i < length; i++)
{
reverse = word.Substring(0, 1) + reverse;
word = word.Remove(0, 1);
}
}
The result I'm getting is : ssessa nevenu eviver otatop rammarg resserd ananab
Why would you move the first letter to the end?
string word = "hello";
string neword = string.Empty;
Array a = word.ToCharArray();
foreach (char c in a)
{
neword = neword + c;
}
I wrote that in C#, but its the same for mainly anything.
Actually, you might be able to do it this way if the language you are writing in is a bit smart:
string word = "hello";
string neword = string.Empty;
foreach (char c in word)
{
neword = neword + c;
}

Resources