JavaScript - reverse an array in a specific way - javascript

I'm doing an algorithm course and here is the instructor's answer about how to reverse an array without using reverse js method:
function solution(arr) {
for(var i=0; i < arr.length/2; i++) {
var tempVar = arr[i]
arr[i] = arr[arr.length - 1 - i]
arr[arr.length - 1 - i] = tempVar
}
return arr
}
I did understand everything, EXCEPT this detail:
arr.length/2
In this line below:
for(var i=0; i < arr.length/2; i++) {
what does it mean? What its purpose?

To reverse a string, you have to swap characters of first half of the string with the last half.
let str = 'abcde';
You have to swap a with e, b with d.
ab is the first half of the string. So simply run loop over the first half of the string and swap ith character with arr.length - 1 - ith character as below
var tempVar = arr[i]
arr[i] = arr[arr.length - 1 - i]
arr[arr.length - 1 - i] = tempVar

Algorithm start with first and last element and swap them. Next it take the second element from the begin and from the end and swap them. And etc it swap all the elements with same distance from center.
So algorithm go to the center of array from both sides. And it need only half of length of array from both side to proceed. So that statement arr.length/2 actually the expression which is a half of length.
Which is used as limit of the loop.

The algorithm swaps two elements that are on equal distance from both ends of the array. The number of operations needed is number_of_operations = number_of_elements / number_elements_operated_on and since it's doing two elements at once, that's number_of_elements / 2. And hence the reason to use arr.length / 2 as the limit of the for loop. Here is a representation of what happens.
Given an array [1, 2, 3, 4, 5, 6] then array.length is 6 and the following operations are performed:
//loop i = 0, 0 < 3 == true, execute
[1, 2, 3, 4, 5, 6] -> [6, 2, 3, 4, 5, 1]
^--------------^ ^--------------^
//loop i = 1, 1 < 3 == true, execute
[6, 2, 3, 4, 5, 1] -> [6, 5, 3, 4, 2, 1]
^--------^ ^--------^
//loop i = 2, 2 < 3 == true, execute
[6, 5, 3, 4, 2, 1] -> [6, 5, 4, 3, 2, 1]
^--^ ^--^
//i = 3, 3 < 3 == false, loop stops
This works perfectly fine with odd number of elements, since there is going to just be one element in middle when you get to it.
Given an array [1, 2, 3, 4, 5] then array.length is 5 and the following operations are performed:
//loop i = 0, 0 < 2.5 == true, execute
[1, 2, 3, 4, 5] -> [5, 2, 3, 4, 1]
^-----------^ ^-----------^
//loop i = 1, 1 < 2.5 == true, execute
[5, 2, 3, 4, 1] -> [5, 4, 3, 2, 1]
^-----^ ^-----^
//loop i = 2, 2 < 2.5 == true, execute
[5, 2, 3, 4, 1] -> [5, 4, 3, 2, 1]
^ ^
//i = 3, 3 < 2.5 == false, loop stops

Related

JavaScript. Filtering an array with the Splice() method [duplicate]

This question already has answers here:
Looping through array and removing items, without breaking for loop
(17 answers)
Closed last year.
I need to write a function
filterRangeInPlace(arr, a, b)
that takes an array and two numbers and deletes all elements from the array that are not within the range a to b. So the check looks like
a ≤ arr[i] ≤ b
I want to do it with the for loop and splice method. But can't figure out why the function keeps some elements outside of the range, in my case below it's number 3. This is not a home task or whatever, I'm just practicing array methods. Here's my code:
let myArr = [1, 3, 8, 3, 9, 5, 3, 4, 10, 7, 6, 1]
function filterRangeInPlace( arr, a, b ) {
for ( i = 0; i < arr.length; i++ ) {
if ( arr[i] < a || arr[i] > b ) {
arr.splice(i, 1)
}
}
}
filterRangeInPlace(myArr, 4, 9)
console.log(myArr) // [3, 8, 9, 5, 4, 7, 6]
I understand I messed with the index somewhere, but can't figure out where and how, as the rest works fine. Thanks!
You should start iterating from the end of the array if you are using splice here and go upto the first element as:
for (i = arr.length - 1; i >= 0; i--) {
Let say, you are removing the first element i.e. 1 at position 0 then after removing the array will be
[3, 8, 3, 9, 5, 3, 4, 10, 7, 6, 1]
and at that time the i increments and becomes 1, so now it will point to 8 as 1 index.
So using splice will skip some of the steps
let myArr = [1, 3, 8, 3, 9, 5, 3, 4, 10, 7, 6, 1];
function filterRangeInPlace(arr, a, b) {
for (i = arr.length - 1; i >= 0; i--) {
if (arr[i] < a || arr[i] > b) {
arr.splice(i, 1);
}
}
}
filterRangeInPlace(myArr, 4, 9);
console.log(myArr);
When you use splice, and you're still in the same loop, you skip some indexes (because splice deletes number of items, so the indexes are changed).
In your example, the 1, which is first, is deleted, so 3 becomes the first one, but then you skip to the second (i++ in the loop). You don't double check the same index.
I'd recommend using filter method to do that, or just putting i-- on the line after splice.

Group numbers from array that are right after each other

I have an array with some numbers like the following:
[1, 2, 3, 4, 6, 7, 8, 10, 15, 16, 17]
I'd like to show all numbers that are direct after each other (n+1) in one line and if there is a gap, this should be separated. This will either be done in javascript/jquery.
The user would see it like this:
1 - 4, 6 - 8, 10, 15 - 17
I'm guessing the only solution to this would be to loop through the array and see if the next number is n+1 and if it is, lump it together, else start on a new series?
I think I know how I would do it that way but interested to know if there is some other way to do it either in javascript/jquery?
You can loop once while keeping track of the current starting number.
let arr = [1, 2, 3, 4, 6, 7, 8, 10, 15, 16, 17];
let start = arr[0],
res = [];
for (let i = 1; i < arr.length; i++) {
if (arr[i + 1] - arr[i] != 1 || i == arr.length - 1) {
res.push(start + " - " + arr[i]);
start = arr[i + 1];
}
}
console.log(res);

Find the longest sub array of consecutive numbers with a while loop

I want to write a function with a while-statement that determines the length of the largest consecutive subarray in an array of positive integers. (There is at least one consecutive array.) For instance:
Input: [6, 7, 8, 6, 12, 1, 2, 3, 4] --> [1,2,3,4]
Output: 4
Input: [5, 6, 1, 8, 9, 7] --> [1,8,9]
Output: 3
Normally I would try to use for-loops and the array.push method later on, however, to get more practice I wanted to use a while-loop and another 'array-lengthening' method, not sure how it's called, see below.
My try:
function longestSub (input) {
let i=0;
let idx=0;
let counterArr=[1]; //init. to 1 because input [4,5,3] equals sub-length 2
while(i<input.length) {
if (input[i]+1 > input[i]) {
counterArr[0+idx] += 1
}
else {
i=input.indexOf(input[i]); //should start loop at this i-value again
idx +=1;
counterArr[0+idx] = 1; //should init new array index
}
i++
}
return Math.max(...counterArr)
}
My idea was that the else-statement would reset the if-statement when it fails and start again from the position it failed at with updated variables. It would also initialize another array index with value 1 that gets subsequently updated afterwards with the if-statement.
Finally I have a counterArr like [1,2,3] where 3 stands for the largest consecutive subarray. Thanks everyone reading this or helping a beginner like me to get a deeper understanding of Javascript.
Here is a simple solution using while loop:
let arr =[6, 7, 8, 6, 12, 1, 2, 3, 4]
let endIndx = 0, maxLength = 0, indx = 1,tempMax = 0;
while (indx < arr.length) {
if (arr[indx] > arr[indx - 1])
tempMax++;
else {
if (maxLength <= tempMax) {
maxLength = tempMax+1
endIndx = indx
tempMax=0;
}
}
++indx
}
if (maxLength < tempMax) {
maxLength = tempMax
endIndx = indx
}
console.log("Sub array of consecutive numbers: ", arr.slice(endIndx-maxLength,endIndx))
console.log("Output :",maxLength)
You could take an approach which just counts the length and checks with the max found length if the continuous items.
function longestSub(input) {
let i = 1, // omit first element and use later element before this index
max = 0,
tempLength = 1; // initialize with one
if (!input.length) return 0;
while (i < input.length) {
if (input[i - 1] < input[i]) {
tempLength++;
} else {
if (max < tempLength) max = tempLength;
tempLength = 1;
}
i++;
}
if (max < tempLength) max = tempLength;
return max;
}
console.log(longestSub([])); // 0
console.log(longestSub([6, 7, 8, 6, 12])); // 3
console.log(longestSub([5, 6, 1, 2, 8, 9, 7])); // 4
console.log(longestSub([6, 7, 8, 6, 12, 1, 2, 3, 4, 5])); // 5
Unless this really is a learning exercise, I'd rather focus on the approach than on the implementation.
Create a function that slices an array of numbers into arrays of consecutive numbers:
The first two conditions deal with the simplest cases:
If input is empty, output is empty [] -> []
If input is exactly one element, the output is known already [42] -> [[42]]
Then comes the "meat" of it. The output is an array of array. Let's start by creating the first sub array with the first element of the initial array. Let's use [6, 7, 8, 6, 12, 1 ,2 ,3, 4, 5] as the input.
Start with [[6]] then iterate over [7, 8, 6, 12, 1 ,2 ,3, 4, 5]. Here are the result at each iteration:
7 > 6 true -> [[6,7]]
8 > 7 true -> [[6,7,8]]
6 > 8 false -> [[6],[6,7,8]]
12 > 6 true -> [[6,12],[6,7,8]]
1 > 12 false -> [[1],[6,12],[6,7,8]]
2 > 1 true -> [[1,2],[6,12],[6,7,8]]
3 > 2 true -> [[1,2,3],[6,12],[6,7,8]]
4 > 3 true -> [[1,2,3,4],[6,12],[6,7,8]]
5 > 4 true -> [[1,2,3,4,5],[6,12],[6,7,8]]
const slices =
xs =>
xs.length === 0 ? []
: xs.length === 1 ? [[xs[0]]]
: xs.slice(1).reduce
( ([h, ...t], x) =>
x >= h[h.length - 1]
? [h.concat(x), ...t]
: [[x], h, ...t]
, [[xs[0]]]
);
slices([6, 7, 8, 6, 12, 1 ,2 ,3, 4, 5]);
//=> [ [1, 2, 3, 4, 5]
//=> , [6, 12]
//=> , [6, 7, 8]
//=> ]
Then you create a function that takes an array of slices and return the biggest one:
const max_slices =
xs =>
xs.reduce
( (a, b) =>
a.length > b.length
? a
: b
);
max_slices(slices([6, 7, 8, 6, 12, 1 ,2 ,3, 4, 5]));
//=> [1, 2, 3, 4, 5]

How to sort an array starting from the middle?

Considering, I have an array like this [..., n-2, n-1, n, n+1, n+2, ...]. I would like to sort it in this way [n, n+1, n-1, n+2, n-2,...] with n equals to the middle of my array.
For example:
Input:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Output:
[5, 6, 4, 7, 3, 8, 2, 9, 1, 0]
let arrayNotSorted = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let positionMiddleArray = Math.trunc(arrayNotSorted.length / 2);
let arraySorted = [arrayNotSorted[positionMiddleArray]];
for(let i=1; i <= positionMiddleArray; i++){
if(arrayNotSorted[positionMiddleArray + i] !== undefined){
arraySorted.push(arrayNotSorted[positionMiddleArray + i]);
}
if(arrayNotSorted[positionMiddleArray - i] !== undefined){
arraySorted.push(arrayNotSorted[positionMiddleArray - i]);
}
}
console.log('Not_Sorted', arrayNotSorted);
console.log('Sorted', arraySorted);
What I have done works properly, but I would like to know if there is a better way or a more efficient way to do so ?
You could take a pivot value 5 and sort by the absolute delta of the value and the pivot values an sort descending for same deltas.
var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
pivot = 5;
array.sort((a, b) => Math.abs(a - pivot) - Math.abs(b - pivot) || b - a);
console.log(...array); // 5 6 4 7 3 8 2 9 1 0
You can do that in following steps:
Create an empty array for result.
Start the loop. Initialize i to the half of the length.
Loop backwards means decrease i by 1 each loop.
push() the element at current index to the result array first and the other corresponding value to the array.
function sortFromMid(arr){
let res = [];
for(let i = Math.ceil(arr.length/2);i>=0;i--){
res.push(arr[i]);
res.push(arr[arr.length - i + 1])
}
return res.filter(x => x !== undefined);
}
console.log(sortFromMid([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
[5, 6, 4, 7, 3, 8, 2, 9, 1, 0]

Shift the position of an element in an array

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const output = move(numbers, 3, -5);
console.log(output);
function move(array, index, offset) {
const output = [...array];
const element = output.splice(index, 1)[0];
output.splice(index + offset, 0, element)
return output;
}
The first line is an array of numbers.
At the second line, when calling the move function, we pass three arguments.
First, is the array itself called numbers.
Secondly, the index of the number we are trying to move (in the example, we have index 3 so we are passing the number 4).
Finally, we have the offset set to -5. The negative sign means we are moving the number to the left. The 5 means 5 positions.
But as you can see, we only have 3 positions to the left of the number 4 before reaching the beginning of the array. In this case, we have to go to the end of the array and count backwards. So, we are looking for a function which will turn the original array to [1, 2, 3, 5, 6, 7, 8, 4, 9].
As you can see, number 4 has shifted 3 positions to the left to reach the beginning of the array, then, 2 further positions from the end of the array.
A further example to clarify.
Let's say we write:
const output = move(numbers, 1, -4);
In this example, we want the number 2 from the array (index 1) to move 4 positions to the left. So, we should get [1, 3, 4, 5, 6, 7, 2, 8, 9].
You need to cover the edge cases when the updated index is less than 0 OR greater than the array length. You can try following
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function move(array, index, offset) {
const output = [...array];
const element = output.splice(index, 1)[0];
let updatedIndex = index + offset;
if(updatedIndex < 0) updatedIndex++;
else if (updatedIndex >= array.length) updatedIndex -= array.length;
output.splice(updatedIndex, 0, element);
return output;
}
console.log(move(numbers, 3, -5));
You could do this using while loop and iterating for the Math.abs() of the position you want to move to and then move in direction depending if parameter is positive or negative.
function move(arr, i, p) {
let left = p < 0,
counter = Math.abs(p),
newPos = i;
while (--counter > -1) {
newPos = (left ? (newPos - 1) : (newPos + 1));
if (newPos == -1) newPos = arr.length - 1;
if (newPos == arr.length) newPos = 0;
if (counter == 0) arr.splice(newPos, 0, arr.splice(i, 1)[0])
}
return arr;
}
console.log(move([1, 2, 3, 4, 5, 6, 7, 8, 9], 3, -5));
console.log(move([1, 2, 3, 4, 5, 6, 7, 8, 9], 5, 5));
console.log(move([1, 2, 3, 4, 5, 6, 7, 8, 9], 1, -25));

Categories