Created
February 10, 2022 20:39
-
-
Save RhydianJenkins/8190b701621a59070e57fbbf1607333f to your computer and use it in GitHub Desktop.
Find the two indexes of an array where their values equal a given target (O(n^2) solution)
This file contains 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
// function to check answer | |
function checkAnswer(arr, target, index1, index2) { | |
return arr[index1] + arr[index2] === target; | |
} | |
// generate array with random numbers | |
const length = 100 | |
const target = 90 | |
const a = Array.from({ length }, () => Math.floor(Math.random() * 100)).sort() | |
// exhaustively search all possible values (O(n^2)) | |
for (let i = 0; i < a.length; i++) { | |
for (let j = i + 1; j < a.length - 1; j++) { | |
if (checkAnswer(a, target, i, j)) { | |
console.log(`First number = a[${i}] =`, a[i]); | |
console.log(`Second number = a[${j}] =`, a[j]); | |
process.exit(0) | |
} | |
} | |
} | |
// no solution found | |
console.log('No solution found') | |
process.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To run:
curl -sL https://gist.githubusercontent.com/RhydianJenkins/8190b701621a59070e57fbbf1607333f/raw/2b9accf4ad4d79ea7d6ac87088f2e1bc9c83953c/sumArray.js | node