Created
May 23, 2021 02:28
-
-
Save GiuseppeMP/e7ccd53beda536b514f43ea20b745f87 to your computer and use it in GitHub Desktop.
Data Structures > Stacks > Poisonous Plants (Javascript)
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
'use strict'; | |
const fs = require('fs'); | |
process.stdin.resume(); | |
process.stdin.setEncoding('utf-8'); | |
let inputString = ''; | |
let currentLine = 0; | |
process.stdin.on('data', function(inputStdin) { | |
inputString += inputStdin; | |
}); | |
process.stdin.on('end', function() { | |
inputString = inputString.split('\n'); | |
main(); | |
}); | |
function readLine() { | |
return inputString[currentLine++]; | |
} | |
/* | |
* Complete the 'poisonousPlants' function below. | |
* | |
* The function is expected to return an INTEGER. | |
* The function accepts INTEGER_ARRAY p as parameter. | |
*/ | |
function poisonousPlants(p) { | |
// Write your code here | |
let stacksIndex = 0 | |
let stacks = p.reduce((pv, cv, ci)=> { | |
pv[stacksIndex].push(cv) | |
if(cv > p[ci-1]){ | |
pv.push([]) | |
stacksIndex++ | |
} | |
return pv | |
}, [[]]) | |
if(stacksIndex === 0) return 0 | |
//console.log(`The plants rearranged to stacks: ${JSON.stringify(stacks)}`) | |
let days = 0 | |
while(true){ | |
// keep last tail ref | |
let tailAux = undefined | |
// if none have removed, than dies stopped | |
let stopped = undefined | |
for (let i =0; i < stacks.length; i++){ | |
let tail = stacks[i][stacks[i].length -1] | |
// if the last element have more pesticide, pop it. | |
if(stacks[i][stacks[i].length -1] > stacks[i][stacks[i].length -2]){ | |
stopped = stacks[i].pop() | |
// if have just an element in the stack | |
}else if(stacks[i].length === 1 ){ | |
// and its bigger than the previous stack tail, pop it | |
if(stacks[i] > tailAux){ | |
stopped = stacks[i].pop() | |
} | |
// if the last stack tail ref exists, and the actual stack head have more pesticide, shift the current stack head | |
}else if(tailAux && stacks[i][0] > tailAux){ | |
stopped = stacks[i].shift() | |
} | |
// save the last stack tail for ref. | |
tailAux = tail | |
} | |
// remove the empty stacks. maybe have some tweak here, filter o(n) | |
stacks = stacks.filter( s => s.length > 0) | |
if(!stopped){ break } else { days ++} | |
//console.log(`The plants end of the day ${days} : ${JSON.stringify(stacks)}`) | |
} | |
return days | |
} | |
function main() { | |
const ws = fs.createWriteStream(process.env.OUTPUT_PATH); | |
const n = parseInt(readLine().trim(), 10); | |
const p = readLine().replace(/\s+$/g, '').split(' ').map(pTemp => parseInt(pTemp, 10)); | |
const result = poisonousPlants(p); | |
ws.write(result + '\n'); | |
ws.end(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment