I recently took a coding test for a promotion at work. This was one of the tasks I really struggled with and was wondering what is the best way to do this. I used a load of
This is what I came up with. Hardly elegant, I might try to tidy it make it a bit more efficient. I have a feeling a brute force approach would be the cleanest and most efficient way to do it. This is a mess.
// w: highest value 2 or less
// UNLESS: 1 of b, c, or d are less than 3 while the other two are greater than 7
// x: highest value
// UNLESS: last was 2 then highest value less than 2
// y: highest value less than 5
// z: highest remaining value
function findhighestwhere(array, condition) {
let res = null
let val = -1
let i = 0
for (let x of array) {
if (x !== null && condition(x) && x > val) {
res = i
val = x
}
i++
}
// console.log(`Test index: ${res} \n Test value: ${val}`)
return res
}
function generate(a,b,c,d) {
// console.log(`Testing: ${a}${b}${c}${d}`)
let array = [a,b,c,d]
let wi = findhighestwhere(array, x => x <= 2)
// That one pain in the conditional edge-case
if ( array[wi] == 2 ) {
// console.log(`Encountered First Position 2 Checking for Edge Case`)
let i = 0
let lowcount = 0
let highcount = 0
for (let x of array) {
if ( i != wi && x <= 3 ) lowcount++
if ( i != wi && x >= 6 ) highcount++
i++
}
if ( lowcount == 1 && highcount == 2 ) {
// console.log(`Edge Case Encountered`)
wi = findhighestwhere(array, x => x <= 1)
}
}
if ( wi === null ) return false
let w = array[wi]
// console.log(`W: ${w}`)
array[wi] = null
if ( w == 2 ) {
var xi = findhighestwhere(array, x => x <= 3)
} else {
var xi = findhighestwhere(array, x => true)
}
if ( xi === null ) return false
let x = array[xi]
// console.log(`X: ${x}`)
array[xi] = null
let yi = findhighestwhere(array, x => x <= 5)
if ( yi === null ) return false
let y = array[yi]
// console.log(`Y: ${y}`)
array[yi] = null
let zi = findhighestwhere(array, x => true)
if ( zi === null ) return false
let z = array[zi]
// console.log(`Z: ${z}`)
array[zi] = null
return `${w}${x}:${y}${z}`
}
console.log(`6520: ${generate(6,5,2,0)}`) // 6520: 20:56
console.log(`3950: ${generate(3,9,5,0)}`) // 3950: 09:53
console.log(`7638: ${generate(7,6,3,8)}`) // 7638: false
console.log(`1727: ${generate(1,7,2,7)}`) // 1727: 17:27