Sum in 2-dimensional array - javascript

I have a matrix :
matrix = [[0, 1, 1, 2],
[0, 5, 0, 0],
[2, 0, 3, 3]]
I need to calculate Sum of all array elements which are not under 0
So, in this example Sum should be = 9
I have this function:
function matrixElementsSum(matrix) {
// Write your code here
var Summa =0
for (i = 0; i<4; i++){
var sum =0;
// console.log(matrix[i].length); //4
for(j=0; j<matrix.length; j++){
console.log("Matrix JI "+ matrix[j][i])
sum = sum +matrix[j][i];
if (matrix[j][i-1]!=0){
console.log(matrix[j][i-1])
Summa =Summa+ sum;
}
}
console.log('-----------' +Summa)
console.log("Sum "+sum);
}
return Summa;
}
i think i need to change if (matrix[j-1][i]!=0) but it doesn't work

You can use reduce() and inside forEach() loop for this. If the current element in foreach loop is zero then you can store index of that element in one other object zero and you can use that object to check if there was zero with same index.
var matrix = [
[0, 1, 1, 2],
[0, 5, 0, 0],
[2, 0, 3, 3]
]
var zero = {}
var sum = matrix.reduce(function(r, e, i) {
e.forEach(function(n, j) {
if (n == 0) zero[j] = true;
if (!zero[j]) r += n;
})
return r;
}, 0)
console.log(sum)

You can sum 2 arrays and ignore numbers from the bottom array, which items from the same index on the top array are 0.
Now you can iterate the matrix from the end, and sum the resulting array.
const matrix = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]];
const sumNotUnderZero = (bottom, top) =>
top.map((v, i) => v ? v + bottom[i] : v);
const result = matrix.reduceRight(sumNotUnderZero)
.reduce((s, n) => s + n);
console.log(result);

You could use Array#reduceRight for building another array with valued column sums and then use Array#reduce for a single number.
var matrix = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]],
result = matrix.reduceRight(function (a, b) {
return b.map(function (c, i) {
return c && c + a[i];
});
}).reduce(function (a, b) {
return a + b;
});
console.log(result);

Should be able to simplify it and use this:
function matrixElementsSum(matrix) {
var Summa =0
for (i = 0; i < matrix.length; i++)
for(j = 0; j < matrix[i].length; j++)
if (matrix[i-1][j] != 0)
Summa = Summa + matrix[i][j];
return Summa;
}
You need to access first the array above your current one, hence the matrix[i-1] and then the same column, hence the [j] in (matrix[i-1])[j] ~ matrix[i-1][j]

Related

How do i return new array with removing one of the elements based on condition [duplicate]

I have a number array [2, 1, 3, 4, 5, 1] and want to remove the smallest number in the list. But somehow my IF statement gets skipped.
I checked and by itself "numbers[i + 1]" and "numbers[i]" do work, but "numbers[i + 1] < numbers[i]" doesn't...
function removeSmallest(numbers) {
var smallestNumberKEY = 0;
for (i = 0; i <= numbers.lenths; i++) {
if (numbers[i + 1] < numbers[i]) {
smallestNumberKEY = i + 1;
}
}
numbers.splice(smallestNumberKEY, 1);
return numbers;
}
document.write(removeSmallest([2, 1, 3, 4, 5, 1]));
You have a typo in your code, array doesn't have lenths property
function removeSmallest(numbers) {
var smallestNumberKEY = 0;
for (var i = 0; i < numbers.length - 1; i++) {
if (numbers[i + 1] < numbers[i]) {
smallestNumberKEY = i + 1;
numbers.splice(smallestNumberKEY, 1);
}
}
return numbers;
}
document.write(removeSmallest([2, 1, 3, 4, 5, 1]));
But your algorithm wont work for another array, e.g [5, 3, 1, 4, 1], it will remove a value 3 too.
You can find the min value with Math.min function and then filter an array
function removeSmallest(arr) {
var min = Math.min(...arr);
return arr.filter(e => e != min);
}
You can use Array#filter instead
function removeSmallest(arr) {
var min = Math.min.apply(null, arr);
return arr.filter((e) => {return e != min});
}
console.log(removeSmallest([2, 1, 3, 4, 5, 1]))
Short one liner. If the smallest value exist multiple times it will only remove ONE. This may or may not be what you want.
const result = [6,1,3,1].sort().filter((_,i) => i) // result = [1,3,6]
It works by sorting and then creating a new array from the items where indeces are truthy(anything but 0)
another solution with splice and indexOf:
array = [2, 1, 3, 4, 5, 1];
function replace(arr){
arr = arr.slice(); //copy the array
arr.splice( arr.indexOf(Math.min.apply(null, arr)),1)
return arr;
}
document.write( replace(array) ,'<br> original array : ', array)
edit : making a copy of the array will avoid the original array from being modified
"Short" solution using Array.forEach and Array.splice methods:
function removeSmallest(numbers) {
var min = Math.min.apply(null, numbers);
numbers.forEach((v, k, arr) => v !== min || arr.splice(k,1));
return numbers;
}
console.log(removeSmallest([2, 1, 3, 4, 5, 1])); // [2, 3, 4, 5]
This is a proposal with a single loop of Array#reduce and without Math.min.
The algorithm sets in the first loop min with the value of the element and returns an empty array, because the actual element is the smallest value and the result set should not contain the smallest value.
The next loop can have
a value smaller than min, then assign a to min and return a copy of the original array until the previous element, because a new minimum is found and all other previous elements are greater than the actual value and belongs to the result array.
a value greater then min, then the actual value is pushed to the result set.
a value equal to min, then the vaue is skipped.
'use strict';
var removeSmallest = function () {
var min;
return function (r, a, i, aa) {
if (!i || a < min) {
min = a;
return aa.slice(0, i);
}
if (a > min) {
r.push(a);
}
return r;
}
}();
document.write('<pre>' + JSON.stringify([2, 1, 3, 2, 4, 5, 1].reduce(removeSmallest, []), 0, 4) + '</pre>');
I like this oneliner: list.filter(function(n) { return n != Math.min.apply( Math, list ) })
check it out here: https://jsfiddle.net/rz2n4rsd/1/
function remove_smallest(list) {
return list.filter(function(n) { return n != Math.min.apply( Math, list ) })
}
var list = [2, 1, 0, 4, 5, 1]
console.log(list) // [2, 1, 0, 4, 5, 1]
list = remove_smallest(list)
console.log(list) // [2, 1, 4, 5, 1]
list = remove_smallest(list)
console.log(list) // [2, 4, 5]
I had to do this but I needed a solution that did not mutate the input array numbers and ran in O(n) time. If that's what you're looking for, try this one:
const removeSmallest = (numbers) => {
const minValIndex = numbers.reduce((finalIndex, currentVal, currentIndex, array) => {
return array[currentIndex] <= array[finalIndex] ? currentIndex : finalIndex
}, 0)
return numbers.slice(0, minValIndex).concat(numbers.slice(minValIndex + 1))
}
function sumOfPaiars(ints){
var array = [];
var min = Math.min(...ints)
console.log(min)
for(var i=0;i<ints.length;i++){
if(ints[i]>min){
array.push(ints[i])
}
}
return array
}
If you only wish to remove a single instance of the smallest value (which was my use-case, not clear from the op).
arr.sort().shift()
Here is a piece of code that is work properly but is not accepted from codewars:
let numbers = [5, 3, 2, 1, 4];
numbers.sort(function numbers(a, b) {
return a - b;
});
const firstElement = numbers.shift();

How to get the position of element index of an array in an ascending order?

let a=[4, 3, 2, 2, 0, 1]
let b=[0, 1, 2, 2, 3, 4]; //My code demo below help to sort a into ascending order.
Output=[4, 5, 2, 3, 1, 0];
// Get the position of element index in a ascending order. For example, 0 is in index 4, 1 is in index 5, 2 is in index 2,2 is in index 3, and 4 is in index 0. Please Provide a demo. Thank you
var Arr = [4, 3, 2, 2, 0, 1];
for (var i = 1; i < Arr.length; i++) {
for (var j = 0; j < i; j++) {
if (Arr[i] < Arr[j]) {
var x = Arr[i];
Arr[i] = Arr[j];
Arr[j] = x;
}
}
}
console.log(Arr);
You could get the indices of the unsorted array and sort the indices by the values of the array.
const
array = [4, 3, 2, 2, 0, 1],
indices = [...array.keys()];
indices.sort((a, b) => array[a] - array[b]);
console.log(...indices);
you can use Object.entries :
let a=[4, 3, 2, 2, 0, 1]
let result = Object.entries(a).sort((a,b) => a[1]-b[1]).map(e => +e[0])
console.log(result)
i guess this is what you want
and also i change some other thing in code to be cleaner and readable
you can ask me anything if you want
function sortWithIndex (self) {
let Arr = [4, 3, 2, 2, 0, 1];
let result = [];
let ArrLength = Arr.length;
for (let i = 0; i < ArrLength; i++) {
number = Arr[i];
indexOfNumber = i;
result.push ('index ' + indexOfNumber + ' is ' + number);
};
return result
};
console.log(sortWithIndex());
Mostafa.T 🐍

Sum specific array values depends on list of index value on other array

I have two arrays:
a = [12, 50, 2, 5, 6];
and
b = [0, 1, 3];
I want to sum those arrays value in array A with exact index value as array B so that would be 12+50+5 = 67. Kindly help me to do this in native javascript. I already tried searching but I can't find any luck. I found related article below, but I can't get the logic
indexOf method in an object array?
You can simply do as follows;
var arr = [12, 50, 2, 5, 6],
idx = [0, 1, 3],
sum = idx.map(i => arr[i])
.reduce((p,c) => p + c);
console.log(sum);
sumAIndiciesOfB = function (a, b) {
var runningSum = 0;
for(var i = 0; b.length; i++) {
runningSum += a[b[i]];
}
return runningSum;
};
logic explained:
loop through array b. For each value in b, look it up in array a (a[b[i]]) and then add it to runningSum. After looping through b you will have summed each index of a and the total will be in runningSum.
b contains the indices of a to sum, so loop over b, referencing a:
var sum=0, i;
for (i=0;i<b.length;i++)
{
sum = sum + a[b[i]];
}
// sum now equals your result
You could simply reduce array a and only add values if their index exists in array b.
a.reduce((prev, curr, index) => b.indexOf(index) >= 0 ? prev+curr : prev, 0)
The result is 12+50+5=67.
Like this:
function addByIndexes(numberArray, indexArray){
var n = 0;
for(var i=0,l=indexArray.length; i<l; i++){
n += numberArray[indexArray[i]];
}
return n;
}
console.log(addByIndexes([12, 50, 2, 5, 6], [0, 1, 3]));

How to convert an array in an complex array

I have this array [2, 1, 2, 1, 1, 1, 1, 1]
I want if the sum of the values exceed four, it's make a new array in array.
I want a result like that: [[2,1],[2,1,1],[1,1,1]]
You could use Array#reduce and use it for adding the values of the last inserted array and for the whole result array.
The main part of the algorithm is this line
!i || r[r.length - 1].reduce(add, 0) + a > 4 ?
r.push([a]) :
r[r.length - 1].push(a);
In it, a check takes place, if i is zero (at start) or if the sum of the last array of the result is in sum with the actual item greater than 4, then a new array with the actual value is added. If not, then the element is pushed to the last array.
var data = [2, 1, 2, 1, 1, 1, 1, 1],
add = function (a, b) { return a + b; },
result = data.reduce(function (r, a, i) {
!i || r[r.length - 1].reduce(add, 0) + a > 4 ? r.push([a]) : r[r.length - 1].push(a);
return r;
}, []);
console.log(result);
You can loop through the array and build a new one, if the sum exceed 4 push the previous array into the result like:
var myArr = [2, 1, 2, 1, 1, 1, 1, 1];
var newArr = [];
var newInner = [];
for (var i = 0; i < myArr.length; i++) {
if (summArr(newInner) + myArr[i] > 4) {
newArr.push(newInner);
newInner = [];
}
newInner.push(myArr[i]);
if (i==myArr.length-1) newArr.push(newInner);
}
function summArr(arr) {
return arr.reduce(add, 0);
function add(a, b) {
return a + b;
}
}
Demo: https://jsfiddle.net/q0ps7960/
for simple way...
var array1 = [2, 1, 2, 1, 1, 1, 1, 1];
var tmp=[];
var output=[];
var sum=0;
for(var i=0; i<array1.length; i++){
sum +=array1[i];
if(sum<=4){
tmp.push(array1[i]);
}else{
output.push(tmp);
sum =array1[i];
tmp=[array1[i]];
}
}
output.push(tmp);
console.log(output);

How to subtract elements of two arrays and store the result as positive array in javascript?

Assume i have 2 arrays,
A=[1,2,3,4,5,6]
B=[9,8,7,5,8,3]
When I subtract the elements of the array,
C=[-8,-6,-4,-1,-3,3]
How can I get the result of the subtraction as
C=[8,6,4,1,3,3]
You can use the javascript function Math.abs()
C.map(Math.abs);
Using Math.abs
function absSubtract(arr1, arr2) {
return arr2.map(function (el, i) {
return Math.abs(el - arr1[i]);
});
}
absSubtract(A, B); // [ 8, 6, 4, 1, 3, 3 ]
DEMO
Math.abs() is returning the absolute value of a number.
You could do something like
var A=[1,2,3,4,5,6]
var B=[9,8,7,5,8,3]
var C = [];
for(let i = 0; i < A.length; i++) {
C.push(Math.abs(A[i] - B[i]));
}
C = A.map( (x, i) => x - B[i] ).map( x => Math.abs(x) );
Assuming that A and B are the same length.
for (var i = 0; i < A.length; i++) {
C[i] = Math.abs(A[i] - B[i]);
}
A solution for the absolute difference. c = |a - b|
var a = [1, 2, 3, 4, 5, 6],
b = [9, 8, 7, 5, 8, 3],
c = a.map(function (v, i) { return Math.abs(v - b[i]); });
document.write('<pre>' + JSON.stringify(c, 0, 4) + '</pre>');

Categories

Resources