I saw this codegolf challenge and I set out to try and write a solution for it. I'm nowhere near an expert codegolfer (or programmer), but it was an interesting exercise.
Now I'm wondering how to improve my code, as it feels really bulky (especially compared to some of the answers to the challenge). Note that I'm not looking for ways to golf this code, I'm merely looking for general improvements and optimizations, hints and tips.
I hope the title is clear as to what the program does, it was pretty hard to describe!
Anyway, what my program does is pretty simple:
- It accepts a string as input
- It then fetches the index of each char in the string from the array
- It checks if that char is within a certain range
- Each range corresponds with a classic mobile phone button (0,1,2 = A,B,C)
- The current button is compared to the previously used button
- If the buttons match, the string does not pass and it returns false
My code:
int previousButton = -1;
char[] letters =
{
'a', 'b', 'c', // 2
'd', 'e', 'f', // 3
'g', 'h', 'i', // 4
'j', 'k', 'l', // 5
'm', 'n', 'o', // 6
'p', 'q', 'r', 's', // 7
't', 'u', 'v', // 8
'w', 'x', 'y', 'z', // 9
' ' // 0
};
for (int i = 0; i < line.Length; i++) {
char currentLetter = line[i];
int index = Array.IndexOf(letters, currentLetter);
int currentButton = 1;
if (index >= 0 && index <= 2) {
currentButton = 2;
} else if (index >= 3 && index <= 5) {
currentButton = 3;
} else if (index >= 6 && index <= 8) {
currentButton = 4;
} else if (index >= 9 && index <= 11) {
currentButton = 5;
} else if (index >= 12 && index <= 14) {
currentButton = 6;
} else if (index >= 15 && index <= 18) {
currentButton = 7;
} else if (index >= 19 && index <= 21) {
currentButton = 8;
} else if (index >= 22 && index <= 25) {
currentButton = 9;
} else if (index == 26) {
currentButton = 0;
}
if (previousButton == currentButton) {
return false;
}
previousButton = currentButton;
}
return true;