Why do these two snippets produce different results?
These two blocks of code theoretically should do the same thing just
implemented in two different languages. But they produce completely
different outputs. The C++ produces the expected results while the ruby
output is not even close.
C++
unsigned long MEMO[10][10][21];
long generate(int a, int b, int l){
if(MEMO[a][b][l] != 0){
return MEMO[a][b][l];
}
if(l==0){
return 1;
}
for(int i =0; i<=9-a-b; i++){
MEMO[a][b][l] += generate(b, i, l-1);
}
return MEMO[a][b][l];
}
int main(){
unsigned long sum = 0L;
for(int i=1; i<10; i++){
sum += generate(0,i,19);
}
printf ("Answer: %lu\n",sum);
return 0;
}
Ruby
MEMO = Array.new(10, Array.new(10, Array.new(21, 0)))
def generate a, b, l
if MEMO[a][b][l] != 0
return MEMO[a][b][l]
end
if (l==0)
return 1
end
0.upto(9-a-b).each do |i|
MEMO[a][b][l] += generate(b, i, l-1)
end
MEMO[a][b][l]
end
sum = 0
1.upto(9).each do |i|
sum+= generate(0, i, 19)
end
puts sum
Ruby output: 72900000000000000000
C++ output: 378158756814587
Does anyone know why this might be?
No comments:
Post a Comment