Zhan
(Mr Zhan)
#1
code from
m = {0: 1, 1: 1}
var fib = function(n) {
if (n in m) return m[n];
return m[n] = fib(n - 1) + fib(n - 2);
};
console.log(fib(46));
I try to conver to this use Map<Int64,but failed
import haxe.Int64;
class TestUV {
static var map:Map<Int64, Int64> = [];
public static function fib(n:Int64):Int64 {
if (map.exists(n)) {
return map[n];
}
return map[n] = fib(n - 1) + fib(n - 2);
}
static function main() {
map[0] = 1;
map[1] = 1;
var t1 = Date.now().getTime();
trace(fib(46));
var t2 = Date.now().getTime();
trace(t2 - t1);
}
}
alex_dja
(Alexander Djafarov)
#2
You should replace everywhere Int64
with Int
.
cedx
(Cédric Belin)
#3
@alex_dja … but you will get an overflow (i.e. instead of having 2971215073
for fib(46)
, you will get -1323752223
).
cedx
(Cédric Belin)
#4
Not optimal: you can try to use a string map to store the Int64
values.
using haxe.Int64;
class TestUV {
static final map: Map<String, String> = [
"0" => "1",
"1" => "1"
];
public static function fib(n: Int64): Int64 {
final value = n.toStr();
if (!map.exists(value)) map[value] = (fib(n - 1) + fib(n - 2)).toStr();
return map[value].parseString();
}
static function main() {
trace(fib(46));
}
}
alex_dja
(Alexander Djafarov)
#5
In js target case you would’t Try Haxe !.
cedx
(Cédric Belin)
#6
Of course
!
Haxe’s Int
maps to Number
when targeting JS… and the Number
type is a double-precision 64-bit binary format IEEE 754 value.
@Zhan What is your target? If you encountered an error, I guess it’s not JS…
Zhan
(Mr Zhan)
#7
I want to test js target and hl target .and I found there is a bug about Map<Int64,Int64>
alex_dja
(Alexander Djafarov)
#8
As a workaround you can try this:
typedef MyInt64 =
#if js
Int;
#elseif hl
hl.I64;
// and so on
#end
...
static var map:Map<MyInt64, MyInt64> = [];
2 Likes
Zhan
(Mr Zhan)
#9
I don’t think it’s best way to use that .because orgin code is target to js
fib(46)
AdrianV
(Adrian V)
#10
how about this Try Haxe ! ?
1 Like