Merhabalar.
Sorunun linki burada:
Ben çözüm için şöyle bir şey yaptım:
function perimeter(n) {
const squareCount = n + 1;
let perimeters = [1, 1];
let i1 = 0;
let i2 = 1;
while (squareCount !== perimeters.length) {
perimeters.push(perimeters[i1] + perimeters[i2]);
i1++;
i2++;
}
return perimeters.reduce((a, b) => a + b) * 4; // sum(perimeters) * 4
}
Çok büyük sayılar argüman olarak girildiğinde sonucu science notation’la göstermesi ve çok çok çok çok büyük sayılar girildinde sonucu Infinity göstermesi dışında her şey yolunda. Ancak görünen o ki iyi bir optimizasyona ihtiyaç var çünkü Codewars:
<--- Last few GCs --->
[1:0x55d412b60000] 41 ms: Scavenge 3.6 (7.3) -> 3.5 (8.3) MB, 1.1 / 0.0 ms allocation failure
[1:0x55d412b60000] 75 ms: Scavenge 7.2 (10.9) -> 6.9 (13.4) MB, 0.8 / 0.0 ms allocation failure
[1:0x55d412b60000] 107 ms: Scavenge 8.7 (13.4) -> 7.8 (14.4) MB, 1.2 / 0.0 ms allocation failure
[1:0x55d412b60000] 132 ms: Scavenge 9.5 (14.4) -> 8.6 (15.4) MB, 0.9 / 0.0 ms allocation failure
<--- JS stacktrace --->
==== JS stack trace =========================================
Security context: 0x37bd4be257c1 <JSObject>
1: perimeter [/home/codewarrior/index.js:~5] [pc=0x31bbc4c0b2bf](this=0x3e31cff0c211 <JSGlobal Object>,n=0)
2: /* anonymous */ [/home/codewarrior/index.js:23] [bytecode=0xbe76afe3429 offset=20](this=0x3e31cff0c211 <JSGlobal Object>)
3: arguments adaptor frame: 1->0
4: begin [/runner/frameworks/javascript/cw-2.js:203] [bytecode=0xbe76afe2a49 offset=141](this=0x3e31cff0c211 <JSGlob...
FATAL ERROR: invalid array length Allocation failed - JavaScript heap out of memory
diyor.
Açıkçası optimizasyon sorunlarıyla ilk kez Codewars’ta yüzleşmeye başladığım için bu konuda henüz beceriksizim. Optimizasyon için ne yapılabilir ? Ya da en hızlı ve doğru çözüm yolu ne olabilirdi ?