https://app.codility.com/demo/results/trainingAQH33G-WVS/
Array.prototype.peek = function() {
return this[this.length-1]
}
export const fish = (A = [4, 3, 2, 1, 5], B = [0, 1, 0, 0, 0]) => {
console.log(` A ${A}, B ${B} `)
let c = B[0]
let s = []
s.push(A[0])
console.log(`init c ${c}, n , s ${s}, A[0] ${A[0]}, `)
console.log(`starting with ${s.peek()}`)
for (let i = 1; i < A.length; i++) {
let n = B[i]
console.log(` c ${c}, n ${n}, s ${s}, A[i] ${A[i]}, `)
if ( c === n ) {
s.push(A[i])
console.log(`same direction ${n}, so append ${A[i]}`)
}
else if (c !== n) {
if (s.peek() > A[i]) {
console.log(`I am fish size ${A[i]} eaten by ${s.peek()}`)
}
while (s.peek() < A[i]) {
console.log(`${A[i]} eating ${s.peek()}, so pop ${s.peek()} `)
s.pop()
}
if (s.length === 0) {
s.push(A[i])
c = n
console.log(`last big fish ${A[i]} on direction ${n} `)
}
}
}
console.log('result : ', s)
return s.length
}
Логически большие fi sh должны съедать маленькие fi sh, когда они встречаются в противоположном направлении. Если они пойдут в одном направлении, они выживут. Где я ошибся?
fish([ 4, 3, 2, 1, 5], [ 1, 0, 1, 0, 1] ) // 3
fish([ 4, 3, 2, 0, 5], [ 0, 1, 0, 0, 0] ) // expected 2, but getting 4
fish([ 4, 3, 2, 1, 5], [ 0, 1, 0, 0, 0] ) // expected 2, but getting 4
fish([ 4, 3, 2, 1, 5], [ 0, 1, 1, 0, 0] ) // expected 2, but getting 3
fish([ 4, 3, 2, 5, 6], [ 1, 0, 1, 0, 1] ) // expected 2, but getting 1
fish([ 7, 4, 3, 2, 5, 6 ], [ 0, 1, 1, 1, 0, 1 ] ) // expected 3, but getting 7
fish([ 3, 4, 2, 1, 5 ], [ 1, 0, 0, 0, 0 ] ) // expected 4
fish([ 3 ], [ 1 ] ) // 1
fish([ 3 ], [ 0 ] ) // 1