I have a two-dimensional array, and I want to sum all the values in that array, where the value is not -1.
Suppose I have a matrix that has the following values:
0,1 = 1.68
1,2 = 1.74
2,0 = 1.61
3,4 = -1
...
I want to add the all the numbers that are not -1
What I did try, and which obviously doesn't work for me, is:
for(i=0; i<data.length; ++i) {
for(j=0; j<data.length; ++j) {
if(data[i][j] != -1) {
sum += data[i][j]+data[j][i]
}
}
}
In my case, if an index (n, m) = k then it is also true that index (m, n) = k.
So for example, if (n, m) = 1.74, then (m, n) = 1.74. That is why I need to do data[i][j]+data[j][i] in the code above
What I REALLY want as result, is this: sum = (0,1 + 1,0) + (1,2 + 2,0) + (2,0 + 0,2) => sum = 2*(1,68) + 2*(1,74) + 2*(1,68)
What I get as result from my code above, is undefined.
I tried an alternative solution using .map (...), which according to the document, takes a function to map. But for now it is just a bit too complicated for me with the double array (I'm not experienced programmer yet)
data.map((a,i) => a.map((n,j) => n+data[i][j]));
I got an error here saying a not a function
You can use nested reduce
const data = [];
var dt = [1,2,3]
data[0] = dt;
data[1] = dt;
data[2] = dt;
var total = data.reduce((n,arr)=> n+arr.reduce((n,val)=>n+val), 0);
console.log(total);
I suppose that you want to sum all the values in a square matrix. So even though (m,n) = (n,m) in your matrix, one simple way to sum the values is :
let sum = 0;
for (let i = 0; i < data.length; i++) {
for (let j = 0; j < data.length; j++) {
if (data[i][j] !== -1) sum += data[i][j];
}
}
console.log(sum);
But if you want to do some calculation that take into account the fact that (m,n) = (n,m) in your matrix, you can try this:
let sum = 0;
for (let i = 0; i < data.length; i++) {
for (let j = 0; j < data.length; j++) {
if (data[i][j] !== -1) {
if (i === j) sum += data[i][j];
if (j < i) sum += 2*data[i][j];
}
}
}
console.log(sum);
Related
I'm working on this CodeSignal exercise that says:
You have an array of integers nums and an array queries, where queries[i] is a pair of indices (0-based). Find the sum of the elements in nums from the indices at queries[i][0] to queries[i][1] (inclusive) for each query, then add all of the sums for all the queries together. Return that number modulo 10^9 + 7.
This is my code:
function solution(nums, queries) {
let accumulator = 0;
let M = 1000000007;
for(let i = 0; i < queries.length; i++){
accumulator += nums.slice(queries[i][0],queries[i][1]+1).reduce((a,b) => a+b);
}
return accumulator < 0 ? ((accumulator % M) + M) % M : accumulator%M;
}
It works perfectly, BUT the penultimate hidden test throws a timeout, and I'm out of ideas on how to make this faster.
Thanks in advance for any help you may provide.
PS: if you're wondering about the difference using modulo at the end, it's because it seems JS has a bug when using negative numbers.
As tflave pointed out, using a prefix sum made the code perform faster, and it didn't timeout. Here's the code if anyone needs it:
let pre = new Array(1000,0);
function preCompute(nums)
{
let n = nums.length;
pre[0] = nums[0];
for (let i = 1; i < n; i++) {
pre[i] = nums[i] + pre[i - 1];
}
}
function solution(nums, queries)
{
preCompute(nums);
let accumulator = 0;
let M = 1000000007;
for(let i = 0; i < queries.length; i++){
if (queries[i][0] === 0) {
accumulator += pre[queries[i][1]];
} else {
accumulator += pre[queries[i][1]] - pre[queries[i][0] - 1];
}
}
return accumulator < 0 ? ((accumulator % M) + M) % M : accumulator%M;
}
I try to develop a simple program that prints all numbers in between 1 and 100 that divide by 3 without any residual and calculate the total sum
I did it with for loop:
var sum = 0;
for (var i = 3; i <= 100; i = i + 3) {
document.write("<br/>" + i);
sum = sum + i;
}
document.write("<br/>sum = " + sum); //1683
But I failed when I wanted to do it with array:
var numbers = [];
var sum = 0;
for (var i = 0; i <= 100; i = i + 3) {
numbers[i - 1] = i;
}
for (var index = 0; index < 100; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + i;
}
document.write("<br/>sum = " + sum);
Use it like this,
Array indexes should start from 0, that is why I have introduced another variable j=0
var numbers = [];
var sum = 0;
for (var i = 0, j = 0; i <= 100; i = i + 3, ++j) {
numbers[j] = i;
}
Update
First Issue:
In your code, ie. below code of yours,
for (var i = 0; i <= 100; i = i + 3) {
numbers[i - 1] = i;
}
In the first iteration,
i = 0;
numbers[0-1] = i // i.e numbers[-1] = 0;
and in your second loop, you are starting the index from 0
for (var index = 0; index < 100; index++) {
Second issue:
Also, if you don't use a sequential counter to fill the Array, you will end with undefined values for the ones you did not fill.
If you notice, the output after the loop, it says numbers.length = 99 which is wrong it will not have that many items in it.
Third Issue:
In below code, even if you introduce a sequential counter, this is still wrong
for (var i = 0; i <= 100; i = i + 3) {
numbers[i - 1] = i;
}
because i should start with 3 instead of 0, otherwise you will end up with 34 elements in the array because numbers[0] will be 0;
Fourth Issue:
In this code,
for (var index = 0; index < 100; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + i;
}
You don't actually have to loop it till 100, you already have the numbers array filled, so you just need to use numbers.length, like this
var len = numbers.length;
for (var index = 0; index < len; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + i;
}
A better way to write this
var numbers = [];
for (var i = 3, j=0; i <= 100; i = i + 3, j++) {
numbers[j] = i;
}
var sum = numbers.reduce((a, b) => a+b);
console.log(sum);
The line var sum = numbers.reduce((a, b) => a+b); uses Array.reduce() method.
adding number to array
var numbers = [];
for(var i = 3; i <= 100; i = i +3){
numbers.push(i);
}
summation and printing values
var sum = 0;
for (var i = 0; i < numbers.length; i++) {
document.write("<br/>" + numbers[i]);
sum = sum + numbers[i];
}
document.write("<br/>sum = " + sum); //1683
There are few issues in your code.
for (var i = 0; i <= 100; i = i + 3) {
numbers[i - 1] = i;
}
1: array is 0 based. so first insertion into the array goes for a toss.
2: the number array created will have skipping index like 3, 6 ,9
for (var index = 0; index < 100; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + i;
}
3: Here you are iterating index till 100 , you should iterate it till the length of the numbers array only.
when index is 1,2
number[index] will become undefined.
4: sum = sum + i (i ??????)
You should try like this or you can also use push()
var numbers = [];
var sum = 0;
for (var i = 0,j=0; i <= 100; i = i + 3, j= j+1) {
numbers[j] = i; // array is 0 based.
}
for (var index = 0; index < numbers.length; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + numbers[index];
}
document.write("<br/>sum = " + sum);
Indexes in an array begin with zero.
for (var i = 0; i <= 100; i = i + 3) {
numbers[i - 1] = i; // In the first iteration, there will be numbers[-1] = i;
}
You have several issues i suppose.
var numbers = [];
var sum = 0;
for (var i = 0; i <= 100; i = i + 3) {
numbers.push(i);
}
for (var index = 0; index < numbers.length; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + i;
}
document.write("<br/>sum = " + sum);
Also for array you can use:
for (var i in array) {
console.log(array[i]);
}
And I'm pretty sure, that array of number sequence is absolutely useless, if there is no other information in it.
Try this
var numbers = [];
var sum = 0;
for (var i = 0; i <= 100; i = i + 3) {
numbers[(i-3)/3] = i;
}
for (var index = 0; index < numbers.length; index++) {
document.write("<br/>" + numbers[index]);
sum = sum + numbers[index];
}
document.write("<br/>sum = " + sum);
Here is the fiddle i tried
https://jsfiddle.net/4ncgnd7c/
This should work using a single loop
var numbers = [];
var sum = 0;
for (var i = 3; i <= 100; i = i + 3) {
numbers[i] = i;
document.write("<br/>" + i);
sum = sum + i;
}
document.write("<br/>sum = " + sum);
I'm working in JavaScript and this is a bit confusing because the code is returning the correct sum of primes. It is working with larger numbers. There is a bug where for 977 it returns the sum of primes for 976, which is 72179, instead of the sum for 977 which is 73156. Everything I've test so far has come back correctly.
function sumPrimes(num) {
var sum = 0;
var count = 0;
var array = [];
var upperLimit = Math.sqrt(num);
var output = [];
for (var i = 0; i < num; i++) {
array.push(true);
}
for (var j = 2; j <= upperLimit; j++) {
if (array[j]) {
for (var h = j * j; h < num; h += j) {
array[h] = false;
}
}
}
for (var k = 2; k < num; k++) {
if (array[k]) {
output.push(k);
}
}
for (var a = 0; a < output.length; a++) {
sum += output[a];
count++;
}
return sum;
}
sumPrimes(977);
The problem stems from the fact that your "seive" Array is indexed from 0, but your algorithm assumes that array[n] represents the number n.
Since you want array[n]===true to mean that n is prime, you need an Array of length 978 if you want the last item to be indexed as array[977] and mean the number 977.
The issue seems to be fixed when I change all instances of < num to < num+1.
How can I find the number of multiple for N numbers(as an array input) for a range 1 to K, where 1 < K < 10⁸ and 3 ≤ N < 25.
function findNumberOfMultiples(inputArray, maxSize) {
var count = 0;
var tempArray = [];
for (var i=0; i<maxSize; i++){
tempArray[i] = 0;
}
for (var j=0; j<inputArray.length; j++) {
for (var i=1; i<=maxSize; i++) {
if (i % inputArray[j]) {
tempArray[i-1] = 1;
}
}
}
for (var i=0; i<maxSize; i++) {
if (tempArray[i]==1) {
count++;
}
}
return count;
}
The above program fails for large number K. For example, if inputArray = [2,3,4] and maxSize(k) is 5,
Multiple of 2 is 2,4
Multiple of 3 is 3
multiple of 4 is 4
so total number of mutiple of 2 or 3 or 4 is 3 in range 1 to 5
You can solve this in O(N^2) where N is the number of elements in your array.
let us say you have two element in your array [a1,a2] and the range is K
your answer will be = >
K/a1 + K/a2 - K/lcm(a1,a2) // because you added them in both a1 and a2
So If you have a1,.....ax elements, your answer would be
K/a1+.....K/ax - K/lcm(ai,aj) (you have to replace i,j by (n*n-1)/2 combinations.
You will have to do K/lcm(ai,aj) O(N^2) times ((n*n-1)/2 time to be precise). So the algorithm complexity will be O(N^2) (There will be a Log(min(ai,aj)) factor but that would not make much difference to the overall complexity).
This will work any K as it only depends on your innput array size.
public int combinations(int K, int[] input){
int total = 0;
for(int i=0;i<input.length;i++){
total = total + Math.floor(K/input[i]);
}
for(int i=0;i<input.length;i++){
for(int j=i+1;j<input.length;j++){
if(i!=j){
int lcm =lcmFind(input[i], input[j]);
total = total - Math.floor(K/lcm);
}
}
}
return total;
}
The test case you have provided:
This function seems to do the trick :
var findMultiplesLength = function(arrayInput, max) {
var globalMultiples = [];
for (var j = 0; j < arrayInput.length; j++) {
var x = arrayInput[j];
var n = max / x;
for (var i=1; i < n; i++) {
mult = i * x;
if (globalMultiples.indexOf(mult) === -1) {
globalMultiples.push(mult);
}
}
}
return globalMultiples.length;
};
EDIT : You won't have any stack error but choosing big values for the range may hang your browser.
If I have n balls and k containers then this -> ( (n+k-1)! / n!(k-1)! ) will work out how many combinations there are.
I am having difficulty changing this to produce a list of all combinations in javascript.
In a function taking an array of balls and some amount of containers.
combinations([1,2,3,4,5,6], 3)
Each container can have any number of balls and containers can be empty.
Here is something i attempted but im only getting one ball in each container.
function generateCombinations(array, r, callback) {
function equal(a, b) {
for (var i = 0; i < a.length; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
function values(i, a) {
var ret = [];
for (var j = 0; j < i.length; j++) ret.push(a[i[j]]);
return ret;
}
var n = array.length;
var indices = [];
for (var i = 0; i < r; i++) indices.push(i);
var final = [];
for (var i = n - r; i < n; i++) final.push(i);
while (!equal(indices, final)) {
callback(values(indices, array));
var i = r - 1;
while (indices[i] == n - r + i) i -= 1;
indices[i] += 1;
for (var j = i + 1; j < r; j++) indices[j] = indices[i] + j - i;
}
callback(values(indices, array));
}
count = 0
generateCombinations([1,2,3,4,5,6,7,8,9,1],3,function(first){
$("#hello").append(first+"<br />")
count = count +1
})
$("#hello").append(count)
You can do it in this way:
var containers = [];
// n - number of balls, k - number of containers
function dfs(n, k) {
// Ending point of recursion, all balls are placed
if(n == 0) {
var output = [];
for(var i = 0; i < k; i++) {
output.push('{' + containers[i].join(', ') + '}');
}
output = '[' + output.join(', ') + ']';
console.log(output);
return;
}
// Try to put ball #n
for(var i = 0; i < k; i++) {
containers[i].push(n);
// Now we have placed ball #n, so we have 1 .. n - 1 balls only
dfs(n - 1, k);
// Remove ball when back to use again
containers[i].pop();
}
}
var n = 4;
var k = 3;
for(var i = 0; i < k; i++) {
containers[i] = [];
}
dfs(n, k);
I initially thought you wanted all the combinations of k elements out of n, but your problem is different, it's partitioning n elements in k parts.
When going through the elements, at each steps, you may choose to put the current element in any container, that's k possibilities. In total, you will have kn possible solutions.
Therefore, it would be faster to iterate through all the solutions, rather than storing them in an array.
You can represent a solution as a unique number in base k, with n digits, and iterate through the solutions by incrementing that number.
In your example, the base is 3, and the number of digits is 6. The first solution is to put all the balls in container 0, ie.
000000
The next solution is to put all the balls in container 0, excepted the last which goes in container 1.
000001
...
000002
000010
000011
000020
Hopefully you should get the idea.