Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Below is a piece of code, which uses only frustratingly poor naming. Can you dec

ID: 3812513 • Letter: B

Question

Below is a piece of code, which uses only frustratingly poor naming. Can you decipher what it does? Can you rename the variables and functions to make their purpose obvious? Hint: It should not be necessary to change control flow or any aspect of the code, other than replacing the opaque names with descriptive ones.

public boolean foo(string a, string b)

{

int[] d = bar(a);

int[] e = bar(b);

for (int c = 0; c < 26; c++)

{

if (d[c] != e[c])

{

return false;

}

}

return true;

}

private int[] bar (string s)

{

int[] b = new int[26];

for (int i = 0; i < b.len; i++)

{

b[i] = 0;

}

for each c in s

{

char d = Character.toLowerCase(c);

b[d - ‘a’] = b[d - ‘a’] + 1;

}

return b;

}

Explanation / Answer

The below checks for equality of two strings by ignoring the case.

PROGRAM CODE:

   public static boolean equalsIgnoreCase(String str1, String str2)
{
int[] string1Letters = getLetterMatrix(str1);
int[] string2Letters = getLetterMatrix(str2);

for (int c = 0; c < 26; c++)
{
if (string1Letters[c] != string2Letters[c])
{
return false;
}
}
return true;
}

private static int[] getLetterMatrix(String string)
{
int[] letters = new int[26];

for (int i = 0; i < letters.length; i++)
{
letters[i] = 0;
}

for each c in string
{
char letter = Character.toLowerCase(c);
letters[letter - 'a'] = letters[letter - 'a'] + 1;
}
return letters;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote