I'm trying to solve this kata:
You are given a list of unique integers arr, and two integers a and b. Your task is to find out whether or not a and b appear consecutively in arr, and return a boolean value (True if a and b are consecutive, False otherwise).
It is guaranteed that a and b are both present in arr.
Test examples:
consecutive([1, 3, 5, 7], 3, 7), false
consecutive([1, 3, 5, 7], 3, 1), true
consecutive([1, 6, 9, -3, 4, -78, 0], -3, 4), true
This is what I have so far:
for (let i = 0; i < arr.length; i ) {
let index2 = arr.indexOf(b)
let index1 = arr.indexOf(a)
let diff = (index2) - (index1)
if (diff > 1) {
console.log(diff, 'false');
return false
} else {
console.log(diff, 'true');
return true
}
}
The test examples are passing but then when I submit the solution, some other tests are not passing. I don't get to see the tests that are not passing so I'm stuck on this. Also, I thought that, in case a and b are the same number, so in case I had
cons([4, 6, 4, 5, 6], 4, 4)
my solution wouldn't pass this test, so how could I improve it?
CodePudding user response:
To answer your question, the reason your code isn't passing all the tests is because you are not taking into account that when a
comes after b
, diff will be negative.
So you should be doing
let diff = Math.abs(index2 - index1)
Also the for loop doesn't seem to do anything so you can just delete it.
CodePudding user response:
steps:
- Find index of given values
- check if index of any one value or - 1 is same as other.
code:
function consecutive(number_list, value1,value2){
var index_value_one = number_list.indexOf(value1);
var index_value_two = number_list.indexOf(value2);
if(index_value_one == (index_value_two 1) || index_value_one == (index_value_two - 1)){
return true;
}
return false;
}
console.log(consecutive([1, 3, 5, 7], 3, 7));
console.log(consecutive([1, 3, 5, 7], 3, 1));
console.log(consecutive([1, 6, 9, -3, 4, -78, 0], -3, 4));