CoDEVIANT #16 (10/2/20) — When arrays are like Tetris

function threeNumberSum(array, targetSum) {
let arr = []
for(let i = 0; i < array.length - 1; i++) {
for(let c = i + 1; c < array.length; c++) {
for(let p = c + 1; p < array.length; p++) {
if(array[i] + array[c] + array[p] == targetSum) {
arr.push([array[i], array[c], array[p]])
}
}
}
}
return arr
}
a visual representation of my attempt at solving this problem: I got some of them correct (see the far right blocks).
function threeNumberSum(array, targetSum) {
array.sort((a,b) => {
return a - b
})

let triplets = []

for(let i = 0; i < array.length - 2; i++) {
let left = i + 1
let right = array.length - 1

while(left < right ) {
let currentSum = array[i] + array[left] + array[right]
if(currentSum === targetSum) {
triplets.push([ array[i], array[left], array[right] ])
left++
right--
} else if(currentSum < targetSum) {
left++
} else if(currentSum > targetSum) {
right--
}
}
}
return triplets
}
array.sort((a, b) => {
return a - b
})
let triplets = []
for(let i = 0; i < array.length - 2; i++ {
...
}
for(let i = 0; i < array.length - 2; i++ {
let left = i + 1
let right = array.length - 1
...
}
while(left < right ) {
let currentSum = array[i] + array[left] + array[right]
if(currentSum === targetSum) {
triplets.push([ array[i], array[left], array[right] ])
left++
right--
}
}
Hey, good question!
Basically, here’s what’s going on.
while(left < right ) {
let currentSum = array[i] + array[left] + array[right]
if(currentSum === targetSum) {
triplets.push([ array[i], array[left], array[right] ])
left++
right--
} else if(currentSum < targetSum) {
left++
} else if(currentSum > targetSum) {
right--
}
}
function threeNumberSum(array, targetSum) {
array.sort((a,b) => {
return a - b
})

let triplets = []

for(let i = 0; i < array.length - 2; i++) {
let left = i + 1
let right = array.length - 1

while(left < right ) {
let currentSum = array[i] + array[left] + array[right]
if(currentSum === targetSum) {
triplets.push([ array[i], array[left], array[right] ])
left++
right--
} else if(currentSum < targetSum) {
left++
} else if(currentSum > targetSum) {
right--
}
}
}
return triplets
}
I have no idea….how this makes sense to me. But I’m pleased that it does and hope you had fun!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store