Last week I posted my first contest with a coding problem to solve.
Now it's time to acknowledge and reward the winners!
Contest #1
- Write a function that take as argument a char array and modify it so that the order of the letters is reversed.
- For instance: 'abc def' ---> 'fed cba'
- Write a function that take as argument a char array and modify it so that the order of the letters in the words are reversed.
- For instance: 'abc def' ---> 'cba fed'
You can assume the separator between words is always the space (no comma, dot, ...)
The preferred language to use is Java, but you can also use other languages as well. You will need to translate the starting code to the language of your choice. Don't use languages where you can solve the problem natively in one line ;)
Winners
There were 3 participants and all of them solved the problems well!
The first place goes to : he did a very good job and the code is very well written.
The second and third prizes will be divided equally between and
because I couldn't choose a winner between them.
did a great job, in javascript, but his code was not working in a special case where there were words separated by two spaces.
solved the problem in C, it works, but his solution was a bit overcomplicated.
have a look at the Best solution here to see how it could have been done.
Anyway, great job guys! Hope to see your solutions to my future contests too!
Best solution
class Main {
/*
* Example: 'abc def' --> 'fed cba'
*/
public static void reverseAll(char[] text) {
reversePartial(text, 0, text.length - 1);
}
/*
* Example: 'abc def' --> 'cba fed'
*/
public static void reverseWords(char[] text) {
int i = 0, j = 0;
while (j < text.length) {
while (j < text.length && text[j] != ' ') {
j++;
}
reversePartial(text, i, j - 1);
i = ++j;
}
}
private static void reversePartial(char[] text, int start, int end) {
int i = start, j = end;
while (i < j) {
swap(text, i++, j--);
}
}
private static void swap(char[] text, int i, int j) {
char temp = text[i];
text[i] = text[j];
text[j] = temp;
}
/***************************/
/***************************/
/* DO NOT CHANGE DOWN HERE */
/***************************/
/***************************/
public static void solve(String text) {
System.out.println("Reversing string: " + text);
char [] reversedAll = text.toCharArray();
reverseAll(reversedAll);
System.out.println(String.format("Result after reversing all: %s", new String(reversedAll)));
char [] reversedWords = text.toCharArray();
reverseWords(reversedWords);
System.out.println(String.format("Result after reversing the words: %s", new String(reversedWords)));
System.out.println();
}
public static void main(String[] args) {
solve("abc def");
solve("This is a sentence I want to reverse");
}
}
Rewards
The contest post total liquid reward is: 7.210 SBD
- 1st price: 50% ---> 3.605 SBD
- 2nd-3rd prize: 25% + 12.5% = 37.5% ---> 2.703 SBD
Thanks for taking part of the challenge!
Armando 🐾