Greetings, I hope you can help me, I can't find my error, what happens is that I am making a function that solves the following problem: Make the function ArrayChallenge( arr ) read the array of integers stored in arr that will have the following format: [K , r1, r2, r3, ...] where K represents the number of desks in a classroom and the rest of the integers in the array will be ordered and represent the desks that are already occupied. All desks will be arranged in 2 columns, where desk #1 is top left, desk #2 is top right, desk #3 is below desk #1, desk #4 is below #2, etc. should return the number of ways 2 students can sit next to each other.
For example: if arr [12, 2, 6, 7, 11], there are a total of 6 ways to seat 2 new students next to each other. The combinations are: [1, 3], [3, 4], [3, 5], [8, 10], [9, 10], [10, 12]. So for this input, your program should return 6 .
function ArrayChallenge(arr) {
let highest = arr[0];
let lowest = arr[0];
let numberBetween = [];
for(let i = 0;i<arr.lenght;i++){
if(arr[i]>highest){
highest=arr[i];
}
else {
if(arr[i]<lowest){
lowest=arr[i];
}
}
}
console.log('highest', highest);
console.log('lowest', lowest);
for(let j = lowest;j<=highest;j++){
if(arr.indexOf(j)==-1){
numberBetween.push(j);
}
}
console.log('numberBetween', numberBetween);
console.log('arr', arr);
return numberBetween.length;
}
this is the function i try to solve but i get 0; Thanks for the help.
interesting exercise... I'll tell you how I would do it:
The first thing you should do is get the first value of the array, because it contains the number of seats, so we isolate it from the list of occupied seats. For this we use the method
array.shift()
that eliminates the first value of an array and returns it to us.Now we have the array with only the seats occupied.
Next, we are going to create a loop with all the possible seats and we are going to add the possible combinations.
If the seat appears on the list, we move on to the next one, because as it is already occupied, it will not add any possibility, the rest we will check seat by seat, if it is odd if the seat + 1 is free (the one on the right) and if it is for the seat - 1 (the one on the left). We must bear in mind that since they are contiguous pairs, the total number of possibilities will be doubled because, for example, if it detects that the pair (1 - 2) is free, it will also detect the pair (2 - 1).
We must also check if the seat + 2 (the one in the back) is free. For all this, we will use the method
array.include()
that returns true or false depending on whether the value we pass to it exists in the array.The code of your function would look like this:
And here I leave it commented and in a snippet so you can try it.
All the best.