This question already has answers here:
Creating an array of cumulative sum in javascript
(28 answers)
Closed 2 years ago.
I am working on a running sum problem and I keep getting an array of undefined for my output. Here is the example of what the output should be like
Example 1:
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
here is the work I have so far:
var runningSum = function(arr) {
const sum = arr.map(n => {
for (let i = 0; i < arr.length; i++) {
if (i === 0) {
n + 0
} else {
n + arr[i - 1]
}
}
})
return sum
};
const arr = [1, 2, 5, 4]
runningSum(arr)
You are missing these 2:
index of the current iterated element, I store as nIndex
temporary variable that store accumulated sum from beginning to that element, I store as temp
Below fix could help you
var runningSum = function(arr) {
const sum = arr.map((n, nIndex) => {
let temp = n
for (let i = 0; i < nIndex + 1; i++) {
if (i === 0) {
temp += 0
} else {
temp += arr[i - 1]
}
}
return temp
})
return sum
}
const arr = [1, 2, 3, 4]
console.log(runningSum(arr))
Related
var subarraySum = function(nums, k) {
let obj = {
0: 1
};
let count = 0;
let sum = 0;
for (let i = 0; i < nums.length; i++) {
sum += nums[i];
if (obj[sum - k]) {
count += obj[sum - k];
}
obj[sum] = ++obj[sum] || 1;
}
return count;
};
console.log(subarraySum([1, 2, 3, 3, 2, 1, 3], 4))
console.log(subarraySum([1, 2, 3, 3, 2, 1, 3], 5))
Question statement: Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. A subarray is a contiguous non-empty sequence of elements within an array.
Why did we define obj as {0 : 1}?
And what exactly is happening when you write obj[sum-k]?
More comments in the code. First I simplified some statements meant to confuse. Then we are left with the pure algorithm. The idea is keeping a total and all the totals we have so far as "seen before". If at any point we find current total to be "seen before" + k it means we found a total k sub group
var subarraySum = function(nums, k) {
// obj counts true or false for *every* sum we accomulate
let obj = {
0: 1
};
let count = 0;
let sum = 0;
for (let i = 0; i < nums.length; i++) {
sum += nums[i];
// if we encounter a seen before difference between sum and k
// it means we have a "sum-k subgroup" thus far.
// example:
// consider we encounterd 1, 2, 3, 4 so we encounterd 10, right?
// we keep going then we a point of sum 15
// it means we must have since the last 10 found a subgroup of sum 5
if (obj[sum - k]) {
// so we found one
count++
}
// mark current sum as encountered = true
obj[sum] = 1;
}
return count;
};
console.log(subarraySum([1, 2, 3, 3, 2, 2, 1, 3], 5))
.as-console-wrapper {
max-height: 100% !important
}
This question already has answers here:
javascript reverse an array without using reverse()
(29 answers)
Closed 8 months ago.
const arr = [1, 2, 3, 4, 5, 6, 7];
function rev(arr) {
var value;
var nArr = [];
for (let i = arr.length - 1; i >= 0; i--) {
value = arr[i];
for (let j = 0; j < arr.length; j++) {
nArr[j] = value;
}
}
console.log(nArr);
}
rev(arr);
I thought this would work but i keep getting an output of the first index in the test array which means one, it's not reversed at all and two, the new array is outputed [1,1,1,1,1,1,1]
The problem here is that you have nested for loops, you take value from index of the outside loop and replace entire array with that value with inner loop, then continue to the next index of the ouside loop, so at the end you end up with the value from the last index of the outside loop.
What you need is one loop, and push() value into new array:
const arr = [1, 2, 3, 4, 5, 6, 7];
function rev(arr) {
var value;
var nArr = [];
for (let i = arr.length - 1; i >= 0; i--) {
value = arr[i];
nArr.push(value);
}
console.log(nArr);
}
rev(arr);
Note, this is very inefficient method to achieve that, the answer from #dippas would be a better choice if you need the result, not the journey ;)
[EDIT]
To better understand what's happening in your original code use console.log():
const arr = [1, 2, 3, 4, 5, 6, 7];
function rev(arr) {
var value;
var nArr = [];
for (let i = arr.length - 1; i >= 0; i--) {
value = arr[i];
for (let j = 0; j < arr.length; j++) {
nArr[j] = value;
console.log("i:", i, "j:", j, "value:", value, "nArr:", "[" + nArr + "]");
}
}
console.log("result:", "[" + nArr + "]");
}
rev(arr);
Given a JavaScript function that takes in an array of numbers as the first and the only argument.
The function then removes one element from the array, upon removal, the sum of elements at odd indices is equal to the sum of elements at even indices. The function should count all the possible unique ways in which we can remove one element at a time to achieve balance between odd sum and even sum.
Example var arr = [2, 6, 4, 2];
Then the output should be 2 because, there are two elements 6 and 2 at indices 1 and 3 respectively that makes the combinations table.
When we remove 6 from the array
[2, 4, 2] the sum at odd indexes = sum at even indexes = 4
if we remove 2
[2, 6, 4] the sum at odd indices = sum at even indices = 6
The code below works perfectly. There might be other solutions but I want to understand this one, because I feel there is a concept I have to learn here. Can someone explain the logic of this algorithm please?
const arr = [2, 6, 4, 2];
const check = (arr = []) => {
var oddTotal = 0;
var evenTotal = 0;
var result = 0;
const arraySum = []
for (var i = 0; i < arr.length; ++i) {
if (i % 2 === 0) {
evenTotal += arr[i];
arraySum[i] = evenTotal
}
else {
oddTotal += arr[i];
arraySum[i] = oddTotal
}
}
for (var i = 0; i < arr.length; ++i) {
if (i % 2 === 0) {
if (arraySum[i]*2 - arr[i] + oddTotal === (arraySum[i - 1] || 0)*2 + evenTotal) {
result = result +1
};
} else if (arraySum[i]*2 - arr[i] + evenTotal === (arraySum[i - 1] || 0)*2 + oddTotal) {
result = result +1
}
}
return result;
};
Is there a possibility to restart this loop with a new index number:
let ar = [1, 1, 2, 1, 2, 1, 3, 2, 3, 1];
let sortedArray = ar.sort();
let sameNumbersArray = [];
let numberOfSameNumbers = 0;
let lastIndexNumber = 0;
for (i = lastIndexNumber; i < sortedArray.length; i++) {
if (sortedArray[i] == sortedArray[i + 1]) {
const sameNumber = sortedArray[i];
sameNumbersArray.push(sameNumber);
} else {
break;
}
let lastIndexFromNumberArray = [];
lastIndexFromNumberArray.push(sameNumbersArray.length);
lastIndexFromNumberArray.push(3);
lastIndexFromNumberArray.push(2);
lastIndexNumber = lastIndexFromNumberArray.reduce(function (a, b) {
return a + b;
}, 0);
So basically that the loop (lastIndexNumber) starts with index[0], but then restarts with index[5] and index[7].
How would one add this extra loop?
I'm not 100% clear on the aim here. Are you able to elaborate on the desired result of the above?
It looks like you want to get an array of the unique numbers and perhaps the number of unique numbers from the source array?
If so, here's another way which might be cleaner:
let ar = [1, 1, 2, 1, 2, 1, 3, 2, 3, 1];
let sortedArray = ar.sort();
let newSameNumbersArray = unique(sortedArray);
//array of unique numbers:
console.log(newSameNumbersArray);
//count of unique numbers:
console.log(newSameNumbersArray.length);
function unique(array) {
return Array.from(new Set(array));
}
This is based on this answer: https://stackoverflow.com/a/44405494/4801692
That said, you can directly set the value of i and use continue to move to the 'next' iteration.
i = 5;
continue;
This is bad though as you are in danger of feeding i a lower number and getting stuck in an infinite loop. If you can explain the requirement a little more I might be able to suggest something better.
you can do such thing to find the pairs
let ar = [10, 10, 10, 20, 20, 10 ,30, 20 ,30]
function findPair(ar) {
let counts = {};
let count = [];
let sum = 0;
for(let i = 0; i < ar.length; i++){
let item = ar[i]
counts[item] = counts[item] >= 1 ? counts[item] + 1 : 1;
}
count = Object.values(counts);
for(let i = 0; i < count.length; i++){
if(count[i] >= 2){
sum += Math.floor(count[i]/2)
}
}
console.log(sum)
}
findPair(ar)
This question already has answers here:
How to find the indexes of all occurrences of an element in array?
(16 answers)
Closed 7 years ago.
The goal here is to is count the number of occurrences in the following array:
[2, 3, 7, 9, 7, 3, 2]
For example if the user enters 7, the output should be [2, 4] because 7 occurs at both these indices. What I have so far looks like this
var arr1 = [2,3,7,9,7,3,2];
printArray(arr1);
var indexOfNum = findValueInArray(arr1, num);
if (indexOfNum === -1) {
console.log('%d was not found in the array of random integers.', num);
}
else {
console.log('%d was found in the array of random integers at index %d',num, indexOfNum);
}
My results are:
arr[0] = 2
arr[1] = 3
arr[2] = 7
arr[3] = 9
arr[4] = 7
arr[5] = 3
arr[6] = 2
7 was found in the array of random integers at index 2
I know I'm close but I'm not sure exactly what I'm overlooking. Thank you guys!
try this,
var arr1 = [2,3,7,9,7,3,2];
function occurance(array,element){
var counts = [];
for (i = 0; i < array.length; i++){
if (array[i] === element) {
counts.push(i);
}
}
return counts;
}
occurance(arr1, 2); //returns [0,6]
occurance(arr1, 7); //returns [2,4]
function findValueInArray(arr, num) {
var r = [];
for(i = 0; i < arr.length; i++) (arr[i] == num) ? r.push(i) : '';
return r;
}
function printArray(num, indexOfNum) {
console.log('%d was found ... index %s', num, indexOfNum.join(', '));
}
var arr = [2,3,7,9,7,3,2];
var num = 7;
var indexOfNum = findValueInArray(arr, num);
printArray(num, indexOfNum);
You can do it like this:
var arr = [2, 3, 7, 9, 7, 3, 2];
function occurrences(x, a) {
var pos = [];
a.forEach(function(val, i) {
if (x === a[i]) {
pos.push(i);
}
});
return pos;
}
console.log(occurrences(7, arr)); // [2, 4]
console.log(occurrences(5, arr)); // []
console.log(occurrences(2, arr)); // [0, 6]