In an array take alternate numbers and swap them. Put it again in the place of array again
e.g., arr = [8,7,4,6,9,3,2,1]
newarr= [8,1,4,3,9,6,2,7]
The Code which I tried is below one
let arr = [8, 7, 4, 6, 9, 3, 2, 1];
let data = arr.map((val, index, curr) => {
if (index == 0) {
return curr[index];
} else if (index == 1) {
return curr[7];
} else if (index == 2) {
return curr[index];
} else if (index == 3) {
return curr[5];
} else if (index == 4) {
return curr[index];
} else if (index == 5) {
return curr[3];
} else if (index == 6) {
return curr[index];
} else if (index == 7) {
return curr[1];
}
});
console.log(data);
This is not the correct way to proceed.
When you consider every odd indexed element to be alternate -
let arr = [8, 7, 4, 6, 9, 3, 2, 1];
let lastAlternate = arr.length % 2 == 0 ? arr.length : arr.length - 1;
let data = arr.map((val, index, curr) => {
if (index % 2 == 0) {
return curr[index];
} else {
return curr[lastAlternate - index];
}
});
console.log(data);
Related
Given an array of length n, consolidate the sum created by adding index pairs until there's only a single index.
EXAMPLES:
[1, 2, 3, 4, 5] => 48
Explanation:
The next array would be [3, 5, 7, 9] because [1+2, 2+3, 3+4, 4+5]
The next array would be [8, 12, 16] because [3+5, 5+7, 7+9]
The next array would be [20, 28] because [8+12, 12+16]
The final answer would be [48] because [20+28] and there are not enough operands to add
This is the solution I came up with but I feel like there's a simpler way to achieve the same solution. I'm trying to understand recursion but I need some explanation on why when we call our stacks, we do it from the (n - 1) or from the (n + 1) to reach our base cases and how do we know which one to use? I don't understand why we're using those passing arguments when we are returning our helper function.
function reduceSum(input) {
function simplify(input, index) {
if (index === 1) {
return input[0];
}
if (index === 0) {
return 0;
}
for (let i = 0; i < input.length; i++) {
input[i] += input[i + 1];
}
return simplify(input, index - 1);
}
return simplify(input, input.length);
}
console.log(reduceSum([1, 2, 3, 4]) == 20)
console.log(reduceSum([5]) == 5)
console.log(reduceSum([]) == 0)
console.log(reduceSum([1, 3, 5]) == 12)
console.log(reduceSum([-5, 5]) == 0)
console.log(reduceSum([-5, 5, -5, 5]) == 0)
console.log(reduceSum([-5, 5, 5, -5]) == 20)
I'm not sure the following is a genuinely simpler way to achieve the solution as it does basically the same thing (although it does not modify the original array), but perhaps there's something useful here:
function reduceSum(input) {
if(input.length <= 1)
return input[0] || 0;
return reduceSum(
input.reduce(
(acc, val, i, { [i + 1]: next }) =>
typeof next !== 'undefined' ? [ ...acc, val + next ] : acc,
[]
)
);
}
console.log(reduceSum([1, 2, 3, 4]) == 20)
console.log(reduceSum([5]) == 5)
console.log(reduceSum([]) == 0)
console.log(reduceSum([1, 3, 5]) == 12)
console.log(reduceSum([-5, 5]) == 0)
console.log(reduceSum([-5, 5, -5, 5]) == 0)
console.log(reduceSum([-5, 5, 5, -5]) == 20)
The next variable is populated using object destructuring on the array argument passed to the reduce callback function. It will be undefined when the reduce method processes the last element of the array, this last element gets skipped; this means that each time we run reduceSum the array gets shorter by one element (as per your original).
Each loop updates values in the array. And with each loop the index needs to be reduced, otherwise it will be infinite loop. Just add console.log("" + input) right after the for loop and you'll see how input progresses with each call of simplify() function.
There are a few optimizations can be done to your code:
you don't need simplify() at all, simply check if index variable is undefined:
function reduceSum(input, index) {
if (index === undefined)
index = input.length;
if (index === 1) {
return input[0];
}
if (index === 0) {
return 0;
}
for (let i = 0; i < input.length; i++) {
input[i] += input[i + 1];
}
console.log("input: " + input);
return reduceSum(input, index - 1);
}
console.log("result:", reduceSum([1, 2, 3, 4, 5]) == 48)
console.log("result:", reduceSum([1, 2, 3, 4]) == 20)
console.log("result:", reduceSum([5]) == 5)
console.log("result:", reduceSum([]) == 0)
console.log("result:", reduceSum([1, 3, 5]) == 12)
console.log("result:", reduceSum([-5, 5]) == 0)
console.log("result:", reduceSum([-5, 5, -5, 5]) == 0)
console.log("result:", reduceSum([-5, 5, 5, -5]) == 20)
You can also optimize a little by only looping through 0 to index - 1 instead of entire array:
function reduceSum(input, index) {
if (index === undefined)
index = input.length;
if (index === 1) {
return input[0];
}
if (index === 0) {
return 0;
}
for (let i = 0; i < index - 1; i++) {
input[i] += input[i + 1];
}
console.log("input: " + input);
return reduceSum(input, index - 1);
}
console.log("result:", reduceSum([1, 2, 3, 4, 5]) == 48)
console.log("result:", reduceSum([1, 2, 3, 4]) == 20)
console.log("result:", reduceSum([5]) == 5)
console.log("result:", reduceSum([]) == 0)
console.log("result:", reduceSum([1, 3, 5]) == 12)
console.log("result:", reduceSum([-5, 5]) == 0)
console.log("result:", reduceSum([-5, 5, -5, 5]) == 0)
console.log("result:", reduceSum([-5, 5, 5, -5]) == 20)
Further you can optimize the code by adding default value to the index variable and moving conditions to the end the function, this way it won't need an extra call of the function to get final result:
function reduceSum(input, index = input.length - 1) {
for (let i = 0; i < index; i++) {
input[i] += input[i + 1];
}
console.log("input: " + input);
if (index > 1)
return reduceSum(input, --index);
//return final result or 0 if array is empty
return input[0] || 0;
}
console.log("result:", reduceSum([1, 2, 3, 4, 5]) == 48)
console.log("result:", reduceSum([1, 2, 3, 4]) == 20)
console.log("result:", reduceSum([5]) == 5)
console.log("result:", reduceSum([]) == 0)
console.log("result:", reduceSum([1, 3, 5]) == 12)
console.log("result:", reduceSum([-5, 5]) == 0)
console.log("result:", reduceSum([-5, 5, -5, 5]) == 0)
console.log("result:", reduceSum([-5, 5, 5, -5]) == 20)
Finally, you can get rid of index all together, by removing last item from the input array instead, this method is slower than the above though:
function reduceSum(input) {
for (let i = 0; i < input.length - 1; i++) {
input[i] += input[i + 1];
}
console.log("input: " + input);
if (input.length > 1)
{
//remove last item by reducing length of the array
input.length--;
return reduceSum(input);
}
//return final result or 0 if array is empty
return input[0] || 0;
}
console.log("result:", reduceSum([1, 2, 3, 4, 5]) == 48)
console.log("result:", reduceSum([1, 2, 3, 4]) == 20)
console.log("result:", reduceSum([5]) == 5)
console.log("result:", reduceSum([]) == 0)
console.log("result:", reduceSum([1, 3, 5]) == 12)
console.log("result:", reduceSum([-5, 5]) == 0)
console.log("result:", reduceSum([-5, 5, -5, 5]) == 0)
console.log("result:", reduceSum([-5, 5, 5, -5]) == 20)
You can use a for loop as follows:
function reduceSum(input) {
if( input.length < 2 ) {
return input[0] || 0;
}
const arr = [];
for(let i = 0; i < input.length - 1; i++) {
arr.push(input[i] + input[i+1]);
}
return reduceSum( arr );
}
console.log(reduceSum([1, 2, 3, 4]) == 20)
console.log(reduceSum([5]) == 5)
console.log(reduceSum([]) == 0)
console.log(reduceSum([1, 3, 5]) == 12)
console.log(reduceSum([-5, 5]) == 0)
console.log(reduceSum([-5, 5, -5, 5]) == 0)
console.log(reduceSum([-5, 5, 5, -5]) == 20)
I want to create a function that will return the number with highest frequency(mode). For example: if array contains [10, 4, 5, 2, 4] the output should be 4. If there is more than one mode, I want to return the one that appeared in the array first (ie. [10,2,5, 4, 5, 2, 4] should return 2 because it appeared first. If there is no mode, I want to return -1. The array will not be empty. Below is my attempt
function Mode(arr){
if(arr == undefined || arr.length == 0){
return
}
const number_to_frequency = {};
let number_with_overall_highest_frequency = 0;
let overall_highest_frequency = 0;
for(index in arr) {
const number = arr[index];
if(number_to_frequency[number]) {
number_to_frequency[number] += 1;
} else {
number_to_frequency[number] = 1;
}
let updated_frequency = number_to_frequency[number]
if(overall_highest_frequency < updated_frequency) {
number_with_overall_highest_frequency = number;
overall_highest_frequency = updated_frequency;
}
}
if(overall_highest_frequency == 1){
return -1
}
return number_with_overall_highest_frequency;
};
console.log(Mode([10,2,5, 4, 5, 2, 4])) //5
If you only need the first one that its repeated you can try this approach
const checkMode = (array = []) => {
const duplicated = array.find(value => array.filter(_value => value === _value).length > 1)
return duplicated >= 0 ? duplicated: -1
}
checkMode([10,2,5, 4, 5, 2, 4])
This is the quicksort algorithm I wrote:
var arr = [0, 2, 5, 10, 3, 22, 12, 8, 20];
let quickSort = (arr) => {
let len = arr.length;
if (len === 1) {
return arr;
};
let pivot = arr.length - 1;
const rightArr = [];
const leftArr = [];
for (let i = 0; i < len - 1; i++) {
let j = i + 1;
if (arr[j] > arr[pivot]) {
rightArr.push(arr[j]);
} else {
leftArr.push(arr[j]);
};
};
if (leftArr.length > 0 && rightArr.length > 0) {
return [...quickSort(leftArr), pivot, ...quickSort(rightArr)];
} else if (leftArr.length > 0 && rightArr.length <= 0) {
return [...quickSort(leftArr), pivot];
} else {
return [pivot, ...quickSort(rightArr)];
};
};
console.log(quickSort(arr));
The output is: [20, 1, 2, 3, 4, 5, 6, 8, 22]
My question is: why do I get the wrong output and how do I fix this ?
There is much wrong with this code, but the problem arises from adding pivot to the list instead of arr[pivot], pivot being the index
I'm to create a function that returns the index of a target within a sorted numbers array if the target is found and return the index where it would be if it were inserted in order (if the target is not found).
So far, in my code, I can only return the index of a target if found but couldn't add the target to its position and return the index. My code below.
function searchIndex(numbers, target) {
let index = numbers.findIndex(x => x === target)
if(index !== -1){
console.log(index)
}
}
searchIndex([1,2,3,4,5], 4)
searchIndex([3,4], 1) // to return 0
searchIndex([[8, 10, 14, 26], 25]) // to return 3
If the array is sorted, then for larger arrays a binary search is the more efficient way to search the target (or its future insertion index):
function searchIndex(numbers, target) {
let low = 0, high = numbers.length;
while (low < high) {
let mid = (low + high) >> 1; // integer division by 2
if (target < numbers[mid]) high = mid;
else if (target > numbers[mid]) low = mid + 1;
else return mid; // found
}
return low; // not found
}
console.log(searchIndex([1,2,3,4,5], 4)); // 3
console.log(searchIndex([3,4], 1)); // 0
console.log(searchIndex([8, 10, 14, 26], 25)); // 3
console.log(searchIndex([1,2,3,4,5], 6)); // 5
function searchIndex(numbers, target) {
if(numbers.includes(target)){
return numbers.indexOf(target)
}else{
numbers.push(target)
numbers.sort((a,b)=> Number(a)-Number(b))
return numbers.indexOf(target)
}
}
console.log(searchIndex([1,2,3,4,5], 4))
console.log(searchIndex([3,4], 1)) // to return 0
console.log(searchIndex([8, 10, 14, 26], 25)) // to return 3
Search for the first element that's >= target. If the target is in the array it will return its index. If not, it will return the index of the element that it should be before.
If it returns -1, it should be added at the end of the array, so return the array length.
function searchIndex(numbers, target) {
let index = numbers.findIndex(x => x >= target)
if (index !== -1) {
console.log(index);
} else {
console.log(numbers.length);
}
}
searchIndex([1, 2, 3, 4, 5], 4)
searchIndex([3, 4], 1) // to return 0
searchIndex([8, 10, 14, 26], 25) // to return 3
searchIndex([1, 2, 3, 4], 5) // to return 4
function searchIndex(numbers, target) {
let index = numbers.findIndex(x => x === target)
if(index === -1){
index = numbers.indexOf(numbers.filter(item => item > target)[0]);
}
console.log(index)
}
searchIndex([1,2,3,4,5], 4);
searchIndex([3,4], 1);// to return 0
searchIndex([8, 10, 14, 26], 25); // to return 3
I am writing a program to find duplictate number in array. The following program is working when number are single digits but for double digit number it is not working
var containsDuplicate = function(nums) {
num = nums.sort()
if (num.length === 0) {
return false
} else {
for (let i = 0; i < num.length; i++) {
if (num[i] == num[i + 1]) {
return true;
} else {
return false
}
}
}
}
First update your condition to num.length-1 to not run out of boundaries. Second return true if there is a duplicate but don't return false inside the else block.
When no duplicate was found then return false at the end of the function.
function containsDuplicate(nums) {
num = nums.sort()
if (num.length === 0) {
return false
} else {
for (let i = 0; i < num.length-1; i++) {
if (num[i] === num[i + 1]) {
return true;
}
}
}
return false;
}
console.log(containsDuplicate([2,3,4,4,5]))
If you want to remove duplicates, you can proceed in the following way:
let a = (x) => {return Array.from(new Set(x))};
a([1,2,3,4,5,6,7,8,9,10,11,12,11,11,9,8,10,11,12]);
Expected output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Hope that it is what you wanted.