Last active
August 10, 2022 03:13
-
-
Save CarlaTeo/9797f8ceeec33967d71a44c4abb647d6 to your computer and use it in GitHub Desktop.
[JS] Descobrir verdade com base em pitacos
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
// People representing each index: | |
// 0 - Carla, 1- Star, 2- Gabriel, 3- Ikeda, 4-Matt | |
// Each food will be represented by its initial: | |
// Banana, Goiabinha, Hersheys, Pacoquinha, Suflair | |
// The solution is a string (eg: 'BGHPS') assigning each food to a person | |
const day = [['S', 'P', 'H', 'B', 'G'], 2]; | |
const max = [['S', 'B', 'G', 'P', 'H'], 2]; | |
const sab = [['S', 'G', 'P', 'B', 'H'], 2]; | |
const gab = [['S', 'H', 'B', 'G', 'P'], 3]; | |
const coringa = [['H', 'G', 'B','P', 'S'], 1]; | |
const pitacos = [day, max, sab, gab, coringa]; | |
function findTruth(pitacos) { | |
const scenarios = getAllScenarios(['B', 'G', 'H', 'P', 'S']); | |
const solutions = []; | |
for(const scenario of scenarios) { | |
if(arePossible(pitacos, scenario)) solutions.push(scenario); | |
} | |
return solutions; | |
} | |
function arePossible(pitacos, scenario) { | |
for(const [pitaco, nOfHits] of pitacos) { | |
if(!isPossible(pitaco, nOfHits, scenario)) return false; | |
} | |
return true; | |
} | |
function isPossible(pitaco, desiredHits, scenario) { | |
let realHits = 0; | |
for(const [idx, food] of pitaco.entries()) { | |
if(scenario[idx] === food) { | |
realHits++; | |
if(realHits > desiredHits) return false; | |
} | |
} | |
return realHits === desiredHits; | |
} | |
function getAllScenarios(foods) { | |
if(foods.length <= 1) return [foods]; | |
const scenarios = [] | |
for(const [idx, food] of foods.entries()) { | |
const foodsCopy = [...foods]; | |
foodsCopy.splice(idx, 1); | |
const rest = getAllScenarios(foodsCopy); | |
for(const r of rest) scenarios.push([...r, food]); | |
} | |
return scenarios; | |
} | |
console.log(findTruth(pitacos)); // ['S', 'P', 'B', 'G', 'H'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment