Javascript - sum of string decimals - javascript

i have and array of string that are decimals. I need to iterate the array and get the sum of them. For example
function check() {
let arr = ["1,50", "1,50"];
let sum1 = 0;
let sum2 = "0";
let sum3 = 0
for (let i = 0, length = arr.length; i < length; i++) {
sum1 += +arr[i];
sum2 += +arr[i];
sum3 += arr[i];
}
console.log(sum1, sum2, sum3)
//sum1 = NaN
//sum2 = '0NaNNaN'
//sum3 = 01,501,50
}
sum should be 3 or 3,00.

You can use reduce() for sum and replace() to replace , with ..
let arr = ["1,50", "1,50"];
const result = arr.reduce((r, e) => r + +e.replace(',', '.'), 0)
console.log(result)

Related

How to iterate to 100 using a for or while loop and show the sum of each iteration with javascript?

Just doing a small homework. I need to iterate to 100, but also console.log the result of each previous example.
Example of the series: (1)+(1+2)+(1+2+3)+…+(1+2+3+…+n)<=100
Iteracion1=1
Iteracion2= 1+2 = 3
iteracion 3: 1+2+3 = 6
iteracion 4: 1+2+3+4 = 10
I have this:
for (i = 0; i <= 100; i++) {
if(i < 100) {
console.log(`${i}+${1}`);
}};
But I don't know how to add the sum of it on each iteration. I you have any references for this it would be great! thank you.
You can efficiently achieve the result using a single loop.
For demo purposes, I've printed up to 20. You can add any number of your choice.
let lastTotal = 0;
let lastStr = "";
for (let i = 1; i <= 10; ++i) {
const total = (lastTotal ?? 0) + i;
const str = lastStr ? lastStr + " + " + i : i;
console.log(`Iteration ${i}: ${str}${total === 1 ? "" : " = " + total}`);
lastTotal = total;
lastStr = str;
}
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use variables outside of for to achieve this
let sum = 0;
const previousSums = [];
for (i = 0; i < 100; i++) {
previousSums.push(sum);
sum += i;
console.log(`${previousSums}`);
}
Create an array you can add indexes to.
Create a function that calculates the sum of the numbers in the array. I've used reduce here.
Create a string, and then log it.
const arr = [];
function sum(arr) {
return arr.reduce((acc, c) => acc + c, 0);
}
// On each iteration push the index in to the
// array. Create a string that joins up the array
// elements and logs the result of the sum
for (let i = 1; i <= 10; i++) {
arr.push(i);
const str = `Iteration ${i}: ${arr.join('+')} = ${sum(arr)}`;
console.log(str);
};
This should do fine.
I created a new Array for the length of iteration of i and use Array#reduce to sum it all up to a number.
const max = 10;
for (let i = 1; i <= max; i++) {
const arr = new Array(i).fill().map((_, i) => i + 1);
console.log(`Iteration ${i}: ${arr.join('+')} = ${arr.reduce((acc, b) => acc + b, 0)}`);
}
var total = 0;
var res = 0;
var upto = 6;
for(i=1;i<=upto;i++){
total = total+i;
res = res+total;
}
console.log(res);

how to get maximum sub array in javascript

var maxSubArray = function(nums) {
let sum = 0,
result = 0;
for (let i = 0; i < nums.length; i++) {
sum = Math.max(0, sum + nums[i]);
result = Math.max(sum, result);
}
return result ;
};
let nums = [-2,1,-3,4,-1,2,1,-5,4];
console.log(maxSubArray(nums));
Question
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
But my test case fail
Input
[-1]
Output
0
Expected
-1
and one more test case fails
Input
[-2,-1]
Output
0
Expected
-1
Answer
var maxSubArray = function(nums) {
let sum = 0,
result = 0,
max=nums[0];
for (let i = 0; i < nums.length; i++) {
sum = Math.max(0, sum + nums[i]);
result = Math.max(sum, result);
if(nums[i] > max){
max = nums[i];
}
}
return result <=0 ? max :result ;
};
Your result should start at -Infinity (or at the value of the first item of the array), otherwise an array containing all negative numbers won't give a proper result. The calculation of sum inside the loop should also use Math.max(nums[i], sum + nums[i]);, otherwise if you pass 0 to Math.max, the current running total will always be at least 0, resulting in an incorrect answer when the passed array contains all negative values.
var maxSubArray = function(nums) {
let sum = 0,
result = -Infinity;
for (let i = 0; i < nums.length; i++) {
sum = Math.max(nums[i], sum + nums[i]);
result = Math.max(sum, result);
}
return result ;
};
console.log(
maxSubArray([-2,1,-3,4,-1,2,1,-5,4]),
maxSubArray([-1]),
maxSubArray([-2,-1]),
);
var maxSubArray = function(nums) {
let sum = 0,
result = -Infinity;
for (let i = 0; i < nums.length; i++) {
sum = Math.max(nums[i], sum + nums[i]);
result = Math.max(sum, result);
}
return result ;
};
console.log(
maxSubArray([-2,1,-3,4,-1,2,1,-5,4]),
maxSubArray([-1]),
maxSubArray([-2,-1]),
);
<!-- begin snippet: js hide: false console: true babel: false -->

JavaScript Mini-Max Sum - Challenge from HackerRank website

Here is the Challenge:
https://www.hackerrank.com/challenges/mini-max-sum/problem
Despite my answer is returning the same number that matches the expected result, I have done something wrong because my answer has been rejected.
How can I solve it?
Here is the solution I had tried:
function miniMaxSum(arr) {
var arrClone1 = arr.slice()
var arrClone2 = arr.slice()
var arrMinor = arrClone1.sort(function(a, b){return a - b;})
arrMinor.pop()
var arrMajor = arrClone2.sort(function(a, b){return b - a;})
arrMajor.pop()
function getSum(a, b) {
return a + b;
}
var result1 = arrMinor.reduce(getSum)
var result2 = arrMajor.reduce(getSum)
console.log(`${result1} ${result2}`) // it is returning: 10 14
I think the solution should be easier:
function miniMaxSum(arr) {
let sum = arr.reduce((a, b) => a + b);
let maxVal = Math.max(...arr);
let minVal = Math.min(...arr);
console.log((sum - maxVal) + ' ' + (sum - minVal));
}
function miniMaxSum(arr) {
// Write your code here
let sum=arr.reduce((a,b)=>{
return a+b;
});
const min=sum-Math.max(...arr);
const max=sum-Math.min(...arr);
console.log(min+" "+max);
}
I found the answer. I noticed that it was mandatory to name the function argument as 'input' instead of 'arr'. That's why the answer was rejected by the HackerRank platform despite the code returned the right result in my editor, NOT in the HackerRank platform. If you do this simply adjustment, it works in the HackerRank platform too.
Just like that:
function miniMaxSum(input) { //'input' NOT 'arr'
var arrClone1 = input.slice() //'input' NOT 'arr'
var arrClone2 = input.slice() //'input' NOT 'arr'
//... rest of the code omitted
my solution:
let sumValue = arr.reduce((a, b) => {
return a + b;
});
const min = sumValue - Math.max(...arr);
const max = sumValue - Math.min(...arr);
const result = `${min} ${max}`
console.log(result);
Here's a more procedural solution to the problem.
function miniMaxSum(arr) {
let sum_min = 0
let sum_max = 0
let min_val = arr[0]
let max_val = arr[0]
let sum = 0
for(let index = 0; index < arr.length; index += 1){
if(arr[index] > max_val) {
max_val = arr[index]
}
if(arr[index] < min_val){
min_val = arr[index]
}
sum = sum + arr[index]
}
sum_min = sum - max_val
sum_max = sum - min_val
console.log(sum_min, sum_max)
}
This is my solution, I hope it works for you
function miniMaxSum(arr) {
// Write your code here
const max = arr.sort((a,b) => b-a).slice(0,4).reduce((a,b)=> a+b,0)
const min = arr.sort((a,b) => b-a).reverse().slice(0,4).reduce((a,b)=> a+b,0)
console.log(min,max)
}
You've got it right. The only "problem" is, that you're doing a Java or C++ coding challenge. (That's why they're mentioning the 32 bit integer).
The input shouldn't be an array but "A single line of five space-separated integers."
Here is another solution...
function miniMaxSum(arr) {
let minValue = 0, maxValue = 0, minIndex = 0, maxIndex = 0, minSum = 0, maxSum = 0;
minValue = Math.min(...arr);
maxValue = Math.max(...arr);
minIndex = arr.indexOf(minValue);
maxIndex = arr.indexOf(maxValue);
for (let i = 0; i < arr.length; i++){
if (minIndex != i) {
maxSum += arr[i];
}
if (maxIndex != i) {
minSum += arr[i];
}
}
console.log(minSum, maxSum);
}
miniMaxSum([1,2,3,4,5]);
Click Here to RUN
Using .reduce:
const arr = [1, 2, 3, 4, 5];
function miniMaxSum(arr) {
const res = arr.sort((a,b) => a-b).reduce((prev, cur, i) => {
if(i!=0) ( prev.max=prev.max+cur || cur);
if(i!=arr.length-1) ( prev.min=prev.min+cur || cur);
return prev;
}, [{max:0},{min:0}]);
console.log(res.min || 0, res.max || 0);
}
miniMaxSum(arr) // 10 14
Try this, it works for all cases:
function miniMaxSum(arr) {
let c = arr.sort();
let a = c.slice(0,4)
let b = c.slice(1,5)
console.log(a.reduce((p,n)=>p+n,0),b.reduce((p,n)=>p+n,0))
}
Another solution !
const numbers = arr.slice('').sort();
let min = 0;
let max = 0;
for (let i = 0; i < numbers.length; i++) {
if (i < 4) {
min = min + numbers[i];
}
if (i > 0 && i < 5) {
max += numbers[i];
}
}
console.log(`${min} ${max}`);
let numbers = arr.slice('').sort();
let maxScore = 0;
let minScore = 0;
for(let i = 0; i < numbers.length - 1; i++) {
minScore += numbers[i];
};
for(let j = 1; j < numbers.length; j++) {
maxScore += numbers[j];
};
console.log(`${minScore} ${maxScore}`);
function miniMaxSum(input) {
let minElem = 0, maxElem = 0, sum = 0;
minElem = input[0];
maxElem = minElem;
sum = minElem;
for (let i = 1; i < input.length; i++) {
sum += input[i];
if (input[i] < minElem) {
minElem = input[i];
}
if (input[i] > maxElem) {
maxElem = input[i];
}
}
let minresult = sum - maxElem;
let maxresult = sum - minElem;
console.log(minresult + " " + maxresult);
}
function miniMaxSum(arr) {
let sortarr = arr.sort();
let maxSum = 0;
let minSum = 0;
for (let i=0 ; i < arr.length - 1; i++ ){
minSum += sortarr[i];
}
for (let j=arr.length - 1; j > 0; j-- ){
maxSum += sortarr[j];
}
console.log(minSum + ' ' + maxSum);
}
guys. Just sharing my solution!
function miniMaxSum(input) {
input.sort((a,b) => a-b)
let min = 0, max = 0;
for(let i=0; i < input.length; i++)
{
min += input[i]
max += input[i]
}
console.log((min - input[input.length -1]) + ' ' + (max - input[0]))
}
Here is my solution --> This will handle duplicate and float values as well
Check the live demo below:
function miniMaxSum(arr) {
let tempArr=[];
var sum = arr.reduce((acc,cur)=>acc+cur);
arr.map((val)=>{
tempArr.push(Number(sum-val));
});
// unique values only
tempArr = [...new Set(tempArr)];
console.log(`${Math.min.apply(null,tempArr)} ${Math.max.apply(null,tempArr)}`);
}
miniMaxSum([7,69,2,203,894]);
this is my solution
function miniMaxSum(arr) {
// Write your code here
var sums = [];
for (var i=0; i<arr.length; i++) {
var num = arr.shift();
var sum = arr.reduce(function(acc, val) { return acc + val; }, 0);
sums.push(sum);
arr.push(num)
}
console.log(Math.min(...sums) + " " + Math.max(...sums));
}
function miniMaxSum(arr) {
let arrayMin = arr.slice() //new array for minimum
let arrayMax = arr.slice() //new array for maximum
let small = arrayMin.sort((a,b) => {return a - b}) //sort number small to big
let big = arrayMax.sort((a,b) => {return a - b}) //sort number small to big
function maxsum (a,b){return a + b} // that's function for calculate all numbers
let min = small.pop() //remove last element
let max = big.shift() //remove first element
let mins = arrayMin.reduce(maxsum) //apply maxsum function to array
let maxs = arrayMax.reduce(maxsum) //apply maxsum function to array
console.log(`${mins} ${maxs}`)
}
code worked for me is as below:
function miniMaxSum(arr) {
// Write your code here
let min = Math.min(...arr);
let max = Math.max(...arr);
let arrExceptMin, arrExceptMax;
let allEqual = arr.every(val => val === arr[0]);
if(allEqual) {
return console.log(sum(arr.slice(1)) + ' ' + sum(arr.slice(1)));
}
if(min) {
arrExceptMin = arr.filter(val => val !== min);
}
if(max) {
arrExceptMax = arr.filter(val => val !== max);
}
return console.log(sum(arrExceptMax) + ' ' + sum(arrExceptMin));
}
Simple Solution (I hope), there was not any problem with 'arr' argument with me.
function miniMaxSum(arr) {
// Write your code here
let a=0, b=0;
arr.sort();
for(let i=0; i<4; i++) {
a+=arr[i];
b+=arr[i+1];
}
console.log(a,b)
}
you can shorten the code
function miniMaxSum(arr) {
// Write your code here
arr.sort((a,b) => a-b)
let min= 0, max = 0;
for(let i = 0; i < arr.length-1 ; i++){
min += arr[i];
}
for(let j = 1; j < arr.length; j++){
max += arr[j];
}
console.log(min,max);
}
Here's a single loop variant.
function miniMaxSum(arr) {
let min = 0
let max = 0
let sum = 0
for (const n of arr) {
sum += n
if (!min || min > n) {
min = n
continue
}
if (max < n) {
max = n
}
}
console.log(sum - max, sum - min)
}
function miniMaxSum(arr) {
let arrMin = [].concat(arr).sort()
let arrMax = [].concat(arr).sort()
arrMin.pop();
arrMax.shift();
let arrMinReduced = arrMin.reduce((prev, curr) => prev + curr)
let arrMaxReduced = arrMax.reduce((prev, curr) => prev + curr)
console.log(arrMinReduced, arrMaxReduced)
}
miniMaxSum([1,2,3,4,5])
This solution uses only single loop and also no utility functions.
code is pretty much self-explanatory.
function miniMaxSum(arr) {
// Write your code here
const total = arr[0] + arr[1] + arr[2] + arr[3] + arr[4];
let max, min;
for (let i = 0; i < arr.length; i++) {
// Add all elements and subtract one element so that we sum of 4 items only
let sum = total - arr[i];
// Sets min & max both equal to sum on first iteration
if (max === undefined && min === undefined) {
max = sum;
min = sum; `enter code here`
} else if (max < sum) {
max = sum
} else if (min > sum) {
min = sum
}
}
console.log(min, max)
}
const arr = [1, 2, 3, 4, 5];
let len = arr.length;
let smallest = arr[0];
let largest = arr[0];
let minSum = 0;
let maxSum = 0;
function minMax(arr, len){
for(let i = 0; i<len; i++){
if(arr[i] >= largest){
largest = arr[i];
}
if(arr[i] <= smallest){
smallest = arr[i];
}
}
for(let i = 0; i < len; i++){
if(arr[i] > smallest){
maxSum += arr[i];
}
if(arr[i] < largest){
minSum += arr[i];
}
}
return console.log(minSum, maxSum)
}
minMax(arr, len)
solution in fewest possible lines, i think
'function miniMaxSum(arr) {
arr.sort((a,b)=>a-b);
let fSum=0, lSum=0;
for(let x=0; x<arr.length-1; x++){
fSum+=arr[x]
}
for(let x=1; x<arr.length; x++){
lSum+=arr[x]
}
console.log(fSum+" "+lSum);
}'

Javascript sum of arrays and average

I have an issue with getting the sum of two arrays and combining their averages while rounding off.
I don't want to hardcode but rather pass two random arrays. so here is the code but it keeps returning NaN
function sumAverage(arr) {
var result = 0;
// Your code here
// set an array
arr = [];
a = [];
b = [];
arr[0] = a;
arr[1] = b;
var sum = 0;
// compute sum of elements in the array
for (var j = 0; j < a.length; j++) {
sum += a[j];
}
// get the average of elements in the array
var total = 0;
total += sum / a.length;
var add = 0;
for (var i = 0; i < b.length; i++)
add += b[i];
var math = 0;
math += add / b.length;
result += math + total;
Math.round(result);
return result;
}
console.log(sumAverage([
[2, 3, 4, 5],
[6, 7, 8, 9]
]));
If you wanted to do it a bit more functionally, you could do something like this:
function sumAverage(arrays) {
const average = arrays.reduce((acc, arr) => {
const total = arr.reduce((total, num) => total += num, 0);
return acc += total / arr.length;
}, 0);
return Math.round(average);
}
console.log('sum average:', sumAverage([[1,2,3], [4,5,6]]));
Just try this method..this kind of issues sometimes occured for me.
For example
var total = 0;
total = total + sum / a.length;
And every concat use this method..
Because you are assigning the value [] with the same name as the argument? This works, see jFiddle
function sumAverage(arr) {
var result = 0;
//arr = [];
//a = [];
//b = [];
a = arr[0];
b = arr[1];
var sum = 0;
// compute sum of elements in the array
for(var j = 0; j < a.length; j++ ){
sum += a[j] ;
}
// get the average of elements in the array
var total = 0;
total += sum / a.length;
var add = 0;
for(var i = 0; i < b.length; i++)
add += b[i];
var math = 0;
math += add / b.length;
result += math + total;
Math.round(result);
return result;
}
document.write(sumAverage([[2,3,4,5], [6,7,8,9]]));
As said in comments, you reset your arguments...
Use the variable "arguments" for dynamic function parameters.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
I suggest to use two nested loops, one for the outer array and one for the inner arrays. Then sum values, calculate the average and add averages.
function sumAverage(array) {
var result = 0,
sum,
i, j;
for (i = 0; i < array.length; i++) {
sum = 0;
for (j = 0; j < array[i].length; j++) {
sum += array[i][j];
}
result += Math.round(sum / array[i].length);
}
return result;
}
console.log(sumAverage([[2, 3, 4, 5], [6, 7, 8, 9]])); // 12
The problem is that you are emptying arr by saying arr = [].
Later, you are iterating over a which is empty too.
Again when you say total += sum / a.length;, sum is 0 and a.length is 0 so 0/0 becomes NaN. Similarly for math. Adding Nan to NaN is again NaN and that's what you get.
Solution is to not empty passed arr and modify your code like below:
function sumAverage(arr) {
var result = 0;
// Your code here
// set an array
//arr = [];
//a = [];
//b = [];
a = arr[0];
b = arr[1];
var sum = 0;
// compute sum of elements in the array
for (var j = 0; j < a.length; j++) {
sum += a[j];
}
// get the average of elements in the array
var total = 0;
total = sum / a.length;
var add = 0;
for (var i = 0; i < b.length; i++)
add += b[i];
var math = 0;
math = add / b.length;
result = math + total;
result = Math.round(result);
return result;
}
console.log(sumAverage([
[2, 3, 4, 5],
[6, 7, 8, 9]
]));
Basically I see a mistake here:
arr[0] = a; arr[1] = b;
That should be
a= arr[0]; b= arr[1];
and then remove:
arr = [];
I suggest you write your function like this:
function sum(arr) {
var arr1 = arr[0]
var sum1 = 0;
arr1.map(function(e){sum1+=e});
var arr2 = arr[1]
var sum2 = 0;
arr2.map(function(e){sum2+=e});
return Math.round(sum1/arr1.length + sum2/arr2.length);
}

Array Processing logic correction

I have an array [1,2,4,5,1,7,8,9,2,3]
and i would like it to generate all subset which sum of values are less than 10
current result [[1,2,4],[5,1],[7],[8],[9],[2,3]]
expected result [[4,5,1],[9,1],[8,2],[3,7],[1,2]]
that is what i did
var a = [1,2,4,5,1,7,8,9,2,3], tempArr = []; tempSum = 0, result = [];
for (var i = 0;i< a.length; i += 1 ) {
tempSum+=a[i];
tempArr.push(a[i]);
if((tempSum+a[i+1])>10) {
result.push(tempArr);
tempSum = 0;
tempArr = [];
} else if (i == a.length-1 && tempArr.length > 0) { // if array is [1,2,3]
result.push(tempArr);
}
}
but it gives me [[1,2,4],[5,1],[7],[8],[9],[2,3]] and it has 6 subset, but i expect to get [[4,5,1],[9,1],[8,2],[3,7],[1,2]] which has 5 subset.
Below logic is in JavaScript :-
var limit = 10;
var arr = [1,2,4,5,1,7,8,9,2,3];
arr.sort();
var ans = new Array ( );
while(arr.length >0){
var ts = arr[arr.length-1];
arr.splice(arr.length-1 , 1);
var ta= new Array ( );
ta.push(ts);
var x = arr.length-1;
while(x>=0){
if(ts + arr[x] <= limit){
ts = ts + arr[x];
ta.push(arr[x]);
arr.splice(x , 1);
}
x= x-1;
}
ans.push(JSON.stringify(ta));
}
alert(ans);
It is Giving Output as required .
[9,1],[8,2],[7,3],[5,4,1],[2]
I have removed duplicates then added maxSum parameter to combine function to generate all subset which have those conditions and then sorted subsets by sum of the values and sliced them.
You could change parameters to fit it for your problem.
var arr = [1,2,4,5,1,7,8,9,2,3]
MAX_SUM = 10,
MIN_SUBSET_LEN = 2,
RESULT_LEN = 5;
//remove duplicates
var uniqeSet = arr.filter(function(value, index){
return this.indexOf(value) == index
},arr);
// a function to get all subset which
// their length are greater than minLength and
// sum of values are little than maxSum
var combine = function(sourceArr, minLength, maxSum) {
var fn = function(n, src, got, all, sum) {
if(sum <= maxSum){
if (n == 0) {
if (got.length > 0) {
all.push({arr:got,sum:sum});
}
return;
}
for (var j = 0; j < src.length; j++) {
var tempSum = sum
fn(n - 1, src.slice(j + 1), got.concat([src[j]]), all, sum + src[j]);
}
}
return;
}
var all = [];
for (var i = minLength; i < sourceArr.length; i++) {
fn(i, sourceArr, [], all, 0);
}
return all;
}
var result = combine(uniqeSet, MIN_SUBSET_LEN, MAX_SUM);
var sortedSliced = result.sort(function(a1, a2){
return a2.sum - a1.sum;
}).slice(0, RESULT_LEN).map(function(m){return m.arr;});
console.log(JSON.stringify(sortedSliced));

Categories