Created
July 16, 2017 14:21
-
-
Save takayukii/761c863ac23ab6e390de207ec2b3b38b to your computer and use it in GitHub Desktop.
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 patterns = []; | |
| function preparePermutationRecursively({ values, arr, depth = 0, maxDepth }) { | |
| if (depth >= maxDepth) { | |
| patterns.push(arr); | |
| return; | |
| } | |
| for (let i = 0; i < values.length; i ++) { | |
| preparePermutationRecursively({ | |
| values, | |
| arr: arr.concat(values[i]), | |
| depth: depth + 1, | |
| maxDepth | |
| }); | |
| } | |
| } | |
| function val(A, S) { | |
| let sum = 0; | |
| for (let i = 0; i < A.length; i ++) { | |
| sum += A[i] * S[i]; | |
| } | |
| // console.log(A, S, sum); | |
| return Math.abs(sum); | |
| } | |
| function solution(A) { | |
| // write your code in JavaScript (Node.js 6.4.0) | |
| preparePermutationRecursively({ | |
| values: [-1, 1], | |
| arr: [], | |
| depth: 0, | |
| maxDepth: A.length | |
| }); | |
| let lowest = -1; | |
| for (let pattern of patterns) { | |
| const sum = val(A, pattern); | |
| if (lowest < 0 || sum < lowest) { | |
| lowest = sum; | |
| } | |
| } | |
| return lowest; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment