Created
July 5, 2022 21:15
-
-
Save anushshukla/2187bcd80aa0b750144665cb2b30acac to your computer and use it in GitHub Desktop.
Get planet to destroy to make even and odd sums of planet mass same
This file contains hidden or 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 'getPlanetToDestroy' function below. | |
| * | |
| * The function is expected to return an INTEGER. | |
| * The function accepts INTEGER_ARRAY planets as parameter. | |
| */ | |
| function getPlanetToDestroy(planets) { | |
| const numberIndexHashmap = {}; | |
| const planetsMassSum = { | |
| even: 0, | |
| odd: 0 | |
| }; | |
| const oddNumbersSet = []; | |
| planets.forEach((planetMass, index) => { | |
| if (!numberIndexHashmap[planetMass]) { | |
| numberIndexHashmap[planetMass] = index; | |
| } | |
| planetsMassSum[index % 2 === 0 ? 'even' : 'odd'] += planetMass; | |
| if (planetMass % 2 !== 0) { | |
| oddNumbersSet.push(planetMass); | |
| } | |
| }); | |
| let planetsMassSumTotal = planetsMassSum.even + planetsMassSum.odd; | |
| console.log({ | |
| planets, | |
| planetsMassSum, | |
| planetsMassSum, | |
| numberIndexHashmap, | |
| oddNumbersSet | |
| }); | |
| for (let index = 0; index < oddNumbersSet.length; index++) { | |
| const oddNumber = oddNumbersSet[index]; | |
| const planetsMassSumAfterOddNumDeds = planetsMassSumTotal - oddNumber; | |
| const isPlanetsMassSumEven = planetsMassSumAfterOddNumDeds % 2 === 0; | |
| console.log({ | |
| oddNumber, | |
| planetsMassSumAfterOddNumDeds, | |
| isPlanetsMassSumEven | |
| }); | |
| if (isPlanetsMassSumEven && numberIndexHashmap[oddNumber]) { | |
| return numberIndexHashmap[oddNumber] + 1; | |
| } | |
| } | |
| return -1; | |
| } | |
| function main() { | |
| const ws = fs.createWriteStream(process.env.OUTPUT_PATH); | |
| const planetsCount = parseInt(readLine().trim(), 10); | |
| let planets = []; | |
| for (let i = 0; i < planetsCount; i++) { | |
| const planetsItem = parseInt(readLine().trim(), 10); | |
| planets.push(planetsItem); | |
| } | |
| const result = getPlanetToDestroy(planets); | |
| ws.write(result + '\n'); | |
| ws.end(); | |
| } | |
| // [2, 5, 6, 7, 8, 4]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment