Javascript - Sum two specific array numbers [duplicate] - javascript

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 1 year ago.
I have an array that I need to the following with:
arranged from lowest to highest.
Select the middle two numbers.
Sum the middle two scores.
Am I on the right track?
var numArray = [2, 1, 3, 1, 4, 2];
numArray.sort((a, b) => a - b);
var sum = numArray[2] + numArray[3];
I think Array.reduce can be used somehow?
var sum = numArray[2] + numArray[3]; gives me two numebrs together and not their sum.
How do I do math function sum rather than combined two variables into one?
Edit: DrafsApp for Mac was adding two values "2" and "2" into "22"
I had to change the code to this and it works:
var sum = Number(numArray[2]) + Number(numArray[3]);

The code is returning the sum as expected.
var numArray = [2, 1, 3, 1, 4, 2];
numArray.sort((a, b) => a - b);
//Sorted array - [1, 1, 2, 2, 3, 4]
var sum = numArray[2] + numArray[3];
//sum = 2 + 2
console.log(sum);

Related

Find the sum of the elements from the beginning of an array to the first negative number

I need to find the sum of elements from the beginning of the array to the first negative number, using loops, like "for". I want loop to summarize all the elements of array before the first negative number and return the sum.
Like for example if I have:
arr = [1, 2, 3, -4, 5]
I need to summarize all elements before "-4" , output would be
6
to print in the console.
Simply iterate over the numbers and break the loop at the first negative one.
let arr = [1, 2, 3, -4, 5];
let res = 0;
for (const num of arr) {
if (num < 0) break;
res += num;
}
console.log(res);

Mini-Max Sum - Wrong output

Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
For example, if the array is [1, 3, 5, 7, 9]. Our minimum sum is 1 + 3 + 5 + 7 = 16 and our maximum sum is 3 + 5 + 7 + 9 = 24.
function miniMaxSum(arr) {
let max = arr.reduce((a, b) => a + b, 1);
let min = arr.reduce((a, b) => a + b, 0, arr.length - 1);
console.log(min, max);
}
Right now, the output should be 10, 14 if the array is just [1, 2, 3, 4, 5].
The output I am getting is 15, 16.
The max variable should just add everything starting from index 1 no?
And the min variable I'm not sure if you're able to do this, but my thinking was initialize the starting at index 0 and go up to the end of the array but minus 1 index.
How can I correct this?
You need to identify which 4 of the 5 elements are the largest, and which 4 of the 5 elements are the smallest - or, equivalently, identify which one element is the smallest, and which one element is the largest, and subtract those from the sum of all 5 elements:
function miniMaxSum(arr) {
// fullSum: sum of all items in the array
const fullSum = arr.reduce((a, b) => a + b, 0);
// Find smallest value in array
const min = Math.min(...arr);
// Find largest value in array
const max = Math.max(...arr);
console.log(fullSum - max, fullSum - min);
}
miniMaxSum([1, 3, 5, 7, 9]);
miniMaxSum([1, 2, 3, 4, 5]);
Another approach is to use slice and sum the small and and the large end of the array.
function miniMax(arr) {
const sum = a => a.reduce((a, b) => a + b, 0);
// we can skip the sort if we know the input is sorted, but just in case
const sorted = arr.sort((a,b) => a-b)
const min = sum(sorted.slice(0, sorted.length-1)) // sum the small end of the array
const max = sum(sorted.slice(1)) // sum the large end of the array
return { min, max }
}
console.log(miniMax([1, 3, 5, 7, 9]));
console.log(miniMax([1, 2, 3, 4, 5]));
This only works if the numbers are listed in ascending order in the array
function miniMaxSum(arr)
{
let max = arr.reduce((a,c,i)=>i?a+c:0, 0);
let min = arr.reduce((a,c,i,t)=>i?a+t[i-1]:0, 0);
document.write(`${JSON.stringify(arr)} -> min: ${min}, max: ${max} <br>`);
}
miniMaxSum([1, 3, 5, 7, 9]);
miniMaxSum([1, 2, 3, 4, 5]);
It was fun to do ;)

Sorting an array of numbers based on start and end values [duplicate]

This question already has answers here:
Sort an integer array, keeping first in place
(6 answers)
Closed 3 years ago.
I have an array which contains numeric values, these values range from 0 to 6. I would like to sort them in an "ascending" order, by specifying the starting number and ending number.
So let's say I want to start from 2, and end on 1..
These values would have to be sorted as such:
2, 3, 4, 5, 6, 0, 1
Or if I want them to start from 4, and end on 3..
These values would have to be sorted as such:
4, 5, 6, 0, 1, 2, 3
I may be overthinking this, but I'm not sure how to use the .sort() functionality for that, how and what would I have to compare against which values exactly?
const startFrom = 4;
const endAt = 3;
const arr = [0, 1, 2, 3, 4, 5, 6];
arr.sort((a, b) => {
// What should I compare to what here?
// .. and what do I return in which case?
});
Using sort,splice,push and unshift
const startFrom = 4;
const endAt = 3;
const arr = [0, 1, 2, 3, 4, 5, 6];
arr.sort(function(a,b){return a-b});
arr.splice(arr.indexOf(startFrom),1)
arr.splice(arr.indexOf(endAt),1)
arr.unshift(startFrom)
arr.push(endAt)
console.log(arr)

Given an array and positive integer d, left shift the array by d efficiently

This is the HackerRank problem description:
A left rotation operation on an array of size n shifts each of the array's elements d unit to the left. For example, if left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].
Here is my function :
function leftRotation(arr, d) {
let newArr = [];
while (d > 0) {
let first = arr.shift();
newArr.push(first);
d--;
}
return [...arr,...newArr];
}
console.log(leftRotation([1,2,3,4,5], 2))
but it doesn't pass large test cases. For example, for n=73000 and d=60000.
Thanks in advance for any idea .
I'm not entirely sure the performance of this method, but it can be done in a single line.
function leftRotation(arr, d) {
return [ ...arr.slice(d), ...arr.slice(0, d) ];
}
console.log(leftRotation([1, 2, 3, 4, 5], 2));
Don't rotate N number of times. Shift N % (length of array) times, because Let's say you have an array of 5 items and you are asked to shift it 5 times then you essentially do not have to shift even once.
Start : [1, 2, 3, 4, 5]
1: [2, 3, 4, 5, 1]
2: [3, 4, 5, 1, 2]
3: [4, 5, 1, 2, 3]
4: [5, 1, 2, 3, 4]
5: [1, 2, 3, 4, 5]
EDIT:
You could use similar logic to optimize the code instead of actually shifting elements in the array. For example: In case of N = 73000, D = 60000, you could splice the array by 73000 % 60000 and then just append the returned spliced array to the existing array and return it.
For an array arr a method shift() can have a time complexity of O(arr.length).
If d is larger than n then you still perform shift() d times.
In total, your time complexity can rise to O(d * arr.length) that is definitely too long.
However, this problem can be solved in O(arr.length) time and space. If you know d then you can shift each item by d positions to the left easily. For instance, arr.length = 5 and d = 2
position: 0 1 2 3 4
arr: 4 3 5 1 6
position in arr: 2 3 4 0 1
shifted_arr: 5 1 6 4 3
So actually, each item at position i in the shifted array corresponds to an item at position (i + d) % arr.length in the original array arr. Hence, the code can look as follows:
function leftShift(arr, d) {
let newArr = [];
let size = arr.length;
for (var i = 0; i < size; i++) {
newArr.push(arr[(i + d) % size]);
}
return newArr;
}
console.log(leftShift([4, 3, 5, 1, 6], 2))

trying to get a quantity of absent elements in the array [duplicate]

This question already has answers here:
Why is math.max() returning NaN on an array of integers?
(5 answers)
Closed 5 years ago.
i am trying to handle with an array with non-consecutive numbers . Here is my example var myArray = [2, 4, 6, 8] . absent numbers are 3, 5, 7 and the quantity = 3 . I tried to get it with this function `
function makeArrayConsecutive(myArray) {
return Math.max(myArray) - Math.min(myArray) + 1 - myArray.length;
}
var myArray = [2, 4, 6, 8];
console.log(makeArrayConsecutive(myArray));
this must return 3 ... but it returns NaN... whats the issue ?
Here's one solution that I think would work for you:
function makeArrayConsecutive(arr) {
//get the min and max using reduce
var max = arr.reduce(function(a, b) {
return Math.max(a, b);
});
var min = arr.reduce(function(a, b) {
return Math.min(a, b);
});
//amount of numbers b/t min/max if array had no "gaps"
var deltaDesired = ((max - min) - 1);
//actual amount of numbers b/t min/max in our array
var deltaActual = (arr.length - 2);
return (deltaDesired - deltaActual);
}
var myArray = [2, 4, 6, 8];
console.log(makeArrayConsecutive(myArray));

Categories