Title
Find the first non-consecutive number
Description
Your task is to find the first element of an array that is not consecutive.
By not consecutive we mean not exactly 1 larger than the previous element of the array.
E.g. If we have an array [1,2,3,4,6,7,8] then 1 then 2 then 3 then 4 are all consecutive but 6 is not, so that's the first non-consecutive number.
If the whole array is consecutive then return null2.
The array will always have at least 2 elements1 and all elements will be numbers. The numbers will also all be unique and in ascending order. The numbers could be positive or negative and the first non-consecutive could be either too!
If you like this Kata, maybe try this one next: https://www.codewars.com/kata/represent-array-of-numbers-as-ranges
1 Can you write a solution that will return null2 for both [] and [ x ] though? (This is an empty array and one with a single number and is not tested for, but you can write your own example test. )
How Can I Solved
문제 요구사항 정의
배열안 요소들의 증가값이 1씩 순차적으로 증가하는지 여부를 판단한다.
문제 접근
배열안의 요소들이 1씩 순차적으로 증가하는 경우 에는 null을 return 한다.
1씩 순차적으로 증가하지 않는 경우, 해당 인덱스의 원소값을 return 한다.
Solution
function firstNonConsecutive (arr) {
for(var i=0;i<arr.length;i++){
if(arr[i]+1 !== arr[i+1]){
return arr[i+1]
}
}
return null;
}
'알고리즘 > CodeWars' 카테고리의 다른 글
[CodeWars] javascript - 7kyu - Largest 5 digit number in a series 문제풀이 (0) | 2020.04.24 |
---|---|
[CodeWars] javascript - 6kyu - IQ Test 문제풀이 (0) | 2020.04.21 |
[CodeWars] javascript - 7kyu - Growth Of Population 문제풀이 (0) | 2020.04.14 |
[CodeWars] javascript - 6kyu - Sum of Digits / Digital Root 문제풀이 (0) | 2020.04.12 |
[CodeWars] javascript - 5kyu - Math Issue 문제 풀이 (0) | 2020.04.07 |
댓글