Skip to content

Instantly share code, notes, and snippets.

@marclerodrigues
Created September 22, 2021 21:28
Show Gist options
  • Select an option

  • Save marclerodrigues/587993eafc34987a6bdd3758f7ec0ae4 to your computer and use it in GitHub Desktop.

Select an option

Save marclerodrigues/587993eafc34987a6bdd3758f7ec0ae4 to your computer and use it in GitHub Desktop.
migratory birds hackerrank problem
// Problem: https://www.hackerrank.com/challenges/migratory-birds/problem
function migratoryBirds(arr) {
// Write your code here
// Contar os tipos e armazenar o valor deles em uma variavel
// Salvar em uma variavel do tipo objeto
const birdsTypes = {
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
};
// Contar quais sao os tipos no array de entrada e atualizar o valor de cada tipo em birdsTypes
// Percorrer o array
// Para cada elemento
// verificar o tipo
// e incrementar o valor no objeto de birdTypes daquele em +1
// [1, 4, 4, 4, 5, 3]
// 1 = 1
// 4 = 1
// 4 = 2
// 4 = 3
// 5 = 1
// 3 = 1
for(let element of arr) {
birdsTypes[element] += 1;
}
// Verificar qual elemento tem a maior ocorrencia e retornar o primeiro.
// Transformar o nosso objeto em um array
// Ordernar o nosso array pelo valor total do elemento
// Pegar o primeiro elemento e retornar ele
const elements = Object.entries(birdsTypes);
console.log(elements)
}
// Final Solution
function migratoryBirds(arr) {
const birdsTypes = {
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
};
for(let element of arr) {
birdsTypes[element] += 1;
}
const elements = Object.entries(birdsTypes);
const sorted = elements.sort((a, b) => b[1] - a[1]);
return sorted[0][0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment