diff --git a/.gitignore b/.gitignore index d63cd90..371bd91 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /.gtm/ +.vimspector.json diff --git a/pow-x-n/nodejs/index.js b/pow-x-n/nodejs/index.js new file mode 100644 index 0000000..f5bde80 --- /dev/null +++ b/pow-x-n/nodejs/index.js @@ -0,0 +1,96 @@ +/* +Implement pow(x, n), which calculates x raised to the power n (xn). + +Example 1: + +Input: 2.00000, 10 +Output: 1024.00000 +Example 2: + +Input: 2.10000, 3 +Output: 9.26100 +Example 3: + +Input: 2.00000, -2 +Output: 0.25000 +Explanation: 2-2 = 1/22 = 1/4 = 0.25 +Note: + +-100.0 < x < 100.0 +n is a 32-bit signed integer, within the range [−231, 231 − 1] +*/ +const { assert } = require('../../util/js'); +/** + * @param {number} x + * @param {number} n + * @return {number} + */ +var myPow = function(x, n) { + + const isNeg = n < 0 ? true: false; + if (n === 0) { + return 1; + } + if (n === 1) { + return x; + } + if (n === -1) { + return 1/x; + } + + const storedCalcs = {}; + + const recursivePow = (x, n) => { + + + if (n === 2) { + return isNeg ? (1/x * 1/x) : x * x; + } + if (n === 1) { + return isNeg ? 1/x : x; + } + if (n === 0) { + return 1; + } + + const firstHalf = Math.floor(parseInt(Math.abs(n) / 2)); + const secondHalf = Math.abs(n) - firstHalf; + + if(storedCalcs[n]) { + return storedCalcs[n]; + } + const result = recursivePow(x, firstHalf) * recursivePow(x, secondHalf); + storedCalcs[n] = result; + return result; + + }; + + return recursivePow(x, n); +} + +/* Test Case 1 + * Input: 2.00000, 10 + * Output: 1024.00000 + */ +x = 2.00000; +n = 10; +sol = 1024.00000; +assert(myPow(x, n) == sol, 'Output: 1024.00000'); + +/* Test Case 2 + * Input: 2.10000, 3 + * Output: 9.261 + */ +x = 2.10000; +n = 3; +sol = 9.261; +assert(myPow(x, n).toFixed(3) == sol, 'Output: 9.261'); + +/* Test Case 3 + * Input: 2.00000, -2 + * Output: 0.25 + */ +x = 2.00000; +n = -2; +sol = 0.25; +assert(myPow(x, n) == sol, 'Output: 0.25000'); diff --git a/rec-permute/nodejs/index.js b/rec-permute/nodejs/index.js new file mode 100644 index 0000000..ee638bb --- /dev/null +++ b/rec-permute/nodejs/index.js @@ -0,0 +1,18 @@ +const RecPermute = (soFar, rest) => { + if (rest.length === 0) { + console.log('result', soFar); + console.log('\n\n'); + } else { + for (let i = 0; i < rest.length; i++) { + const remaining = rest.substring(0,i) + rest.substring(i+1); + console.log('r', remaining) + console.log('R', rest); + console.log('SF', soFar); + console.log('------'); + RecPermute(soFar + rest[i], remaining); + } + } +}; + +x = 'abc'; +RecPermute('', x);