Dimitri
BAN USERFirst i++ and ++i are the same since they do the same operation. But the results are not in the same time. With i++, we return the value contained in the variable i before increment it. And ++i, we increment i and we return the value of i. What would happen if in for loop in java we would do something like
for(int i = 0; i < size; ++i) { .... }
Here is my solution in C
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int sum(int array[], int start, int end){
int sum = 0, i;
for(i = start; i < end; i++){
sum += array[i];
}
return sum;
}
int splitArray(int array[], int start, int end, int ind){
if( ind == end){
return 0;
} else {
int left = sum(array, start, ind);
int right = sum(array, ind+1, end);
return (left == right) || splitArray(array, start, end, ind+1);
}
}
int main(int argc, char* argv[]){
int array[] = { 7,3,4,0,1,2};
int res = splitArray(array, 0, 5, 0);
if( res == 1)
printf("TRUE\n");
else
printf("FALSE\n");
return 0;
}
Here is my solution in C
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int sum(int array[], int start, int end){
int sum = 0, i;
for(i = start; i < end; i++){
sum += array[i];
}
return sum;
}
int splitArray(int array[], int start, int end, int ind){
if( ind == end){
return 0;
} else {
int left = sum(array, start, ind);
int right = sum(array, ind+1, end);
return (left == right) || splitArray(array, start, end, ind+1);
}
}
int main(int argc, char* argv[]){
int array[] = { 7,3,4,0,1,2};
int res = splitArray(array, 0, 5, 0);
if( res == 1)
printf("TRUE\n");
else
printf("FALSE\n");
return 0;
}
I also have an solution but in a recursive manner :
public class StringReduction {
public char getChar(char l, char r) {
if (l == 'a') {
if (r == 'b')
return 'c';
if (r == 'c')
return 'b';
}
if (l == 'b') {
if (r == 'a')
return 'c';
if (r == 'c')
return 'a';
}
if (l == 'c') {
if (r == 'a')
return 'b';
if (r == 'b')
return 'a';
}
return 'l';
}
public int redux(String input, int pos) {
if (pos > input.length() - 1) {
return input.length();
}
char l = input.charAt(pos);
char r = input.charAt(pos + 1);
if (l != r) {
StringBuffer sb = new StringBuffer(getChar(l, r));
sb.append(input.substring(pos + 1));
System.out.println(sb.toString());
return redux(sb.toString(), pos + 1);
}
return redux(input, pos + 1);
}
/**
* @param args
*/
public static void main(String[] args) {
StringReduction sr = new StringReduction();
System.out.println(sr.redux("aacbca", 0));
}
}
I think there is a easier way to do that. It says that the tree stores character data. So we can do a in/pre/post-order traversal for T1 and T2. Then, we will check the length of T2 and sees if it matches the same character and the same length of T1 depending of the traversal. For instance, if we have the tree :
.
- Dimitri March 21, 2012