Created
September 22, 2021 21:28
-
-
Save marclerodrigues/587993eafc34987a6bdd3758f7ec0ae4 to your computer and use it in GitHub Desktop.
migratory birds hackerrank problem
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
| // 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