Created
June 29, 2020 22:45
-
-
Save da411d/0e59f79dcf4603cdabf0024a10eeb6fe to your computer and use it in GitHub Desktop.
7 => 1 + 4*2 - 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const rand = (mi, ma) => { | |
return Math.floor(Math.random() * (ma - mi + 1) + mi); | |
}; | |
// IN: 7 | |
// OUT: [1, 8, -2] | |
const generateAdditionsArray = n => { | |
const additions = []; | |
const from = Math.min(-10000, -Math.abs(n * 2)); | |
const to = Math.max(10000, Math.abs(n * 2)); | |
let tempSum = 0; | |
for(let i = 0; i<5; i++){ | |
const addition = rand(from, to); | |
additions.push(addition); | |
tempSum += addition; | |
} | |
additions.push(n - tempSum); | |
return additions; | |
}; | |
// IN: 6 | |
// OUT: [2, 3] | |
const getDividers = n => { | |
const dividers = []; | |
n = Math.abs(n); | |
for(var i = 2; i < n; i++){ | |
if(n % i === 0){ | |
dividers.push(i); | |
} | |
} | |
return dividers; | |
}; | |
// IN: 8 | |
// OUT: [2, 4] | |
// IN: 3 | |
// OUT: [3] | |
const toMultiplyArray = n => { | |
const dividers = getDividers(n); | |
if(dividers.length == 0){ | |
return [n]; | |
} | |
const divider = dividers[ rand(0, dividers.length - 1) ]; | |
return [divider, n / divider]; | |
}; | |
// IN: [1, [2, 3], 4] | |
// OUT: 1 + 2 * 3 + 4 | |
const toString = arr => arr.map(n => Array.isArray(n) ? n.join("*") : n).join("+").replace(/\+-/g, "-"); | |
const testNumbers = [ | |
0, | |
1, | |
100, | |
125793, | |
-15232103, | |
]; | |
for(const test of testNumbers){ | |
const additions = generateAdditionsArray(test); | |
const withMultiply = additions.map(toMultiplyArray); | |
const additionsString = toString(additions); | |
const multiplyString = toString(withMultiply); | |
// eval just for test | |
const addSuccess = eval(additionsString) == test; | |
const multiplySuccess = eval(multiplyString) == test; | |
console.log([ | |
`TEST: ${test}`, | |
`ADD CODE: ${additionsString} ${addSuccess ? "✔" : "❗"}`, | |
`MULTIPLY CODE: ${multiplyString} ${multiplySuccess ? "✔" : "❗"}`, | |
].join("\n")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment