Created
January 8, 2018 18:44
-
-
Save matheushf/d1237d8d78865b328d63a96f6c632c36 to your computer and use it in GitHub Desktop.
Javascript solution for the Codility Frog River One
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
function solution(X, A) { | |
// write your code in JavaScript (Node.js 6.4.0) | |
let sequence = [0]; | |
let position = -1; | |
let counter = 0; | |
if (X === 1 && A[0] === 1) | |
return 0; | |
for (let i = 0; i <= A.length - 1; i++) { | |
if (A[i] <= X) { | |
if (!sequence[A[i]]) { | |
counter++; | |
} | |
sequence[A[i]] = A[i]; | |
if (counter === X) { | |
position = i; | |
break; | |
} | |
} | |
} | |
return position; | |
} |
@macroramesh6 solution with set makes a lot of sense and pretty easy. Thank you for sharing.
let moves = [];
let leaf = 0;
for(let i = 0; i < A.length; i++) {
if(!moves[A[i]]) {
leaf++;
moves[A[i]] = true;
}
if(leaf == X) return i;
}
return -1;
I need a bit of help here if any. I have a similar solution to @KamilZajac but mine doesn't pass all cases, i'm not sure where I am missing it
const arr = Array.from(new Set([...A]))
if(!A.includes(X)) return -1;
if(arr.length === X) {
return A.indexOf(X)
}
return -1
function solution(X, A) {
let myNum = 0;
A.sort().map(it =>(it+1) === X+1 ? myNum=it+1 : null)
return myNum;
}
I got 9% : )))) such poor score.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great solution!
Just to be precise, would add one if, to check if A[i] is smaller or equal than X - we need to cover steps from 1 to X, while now, steps like [2,3,4,5,6] will be as valid as [1,2,3,4,5], so maybe like:
Anyway, it will get 100% even without this check 🥇