This function needs to find the first occurrence of consecutive numbers whose sum equals 10, and return them as an array. My idea was to keep summing the numbers until the accumulator, in this case x becomes greater than 10, at which point the value of x is reset to zero, and i is reset back to index 1, by being assigned to the ct variable that is supposed to grow by one on each reset, so the loop would go back and start at the next element, until it gets the correct value. But for some reason ct is stuck at 1 and doesn't grow and the loop doesn't move past the second array element at index 1. Is there an error in the logic or the implementation?
Warning: This code may cause the page to crash or become unresponsive
const arr = [2, 3, 1, 2, 7, 2, 5, 4, 5, 1, 2, 1];
function test(arr) {
let x = 0;
for (let i = 0; i < arr.length; i++) {
let ct = 0;
x = x + arr[i]
if (x > 10) {
x = 0;
i = ct;
ct++
}
console.log(x)
}
}
console.log(test(arr))
The problem is that you've defined ct in the wrong place. It's inside the loop, meaning that every time you get to a point where i = ct, i is reset to 0 and ct++ has no effect (because every iteration, ct is reset to 0). You need to define ct in the same scope as x:
const arr = [2, 3, 1, 2, 7, 2, 5, 4, 5, 1, 2, 1];
function test(arr) {
let x = 0;
let ct = 0;
for (let i = 0; i < arr.length; i++) {
x = x + arr[i];
if (x > 10) {
x = 0;
i = ct;
ct++;
}
console.log(x);
}
}
test(arr);
I've also filled in the rest of the logic of the function for you in case you'd like it:
const arr = [2, 3, 1, 2, 7, 2, 5, 4, 5, 1, 2, 1];
function test(arr) {
let x = 0;
let ct = 0;
let result = [];
for (let i = 0; i < arr.length; i++) {
x = x + arr[i];
if (x > 10) {
x = 0;
i = ct;
ct++;
}
if (x == 10) {
result = arr.slice(ct, i + 1);
return result;
}
console.log(x);
}
return result;
}
console.log(test(arr));
Related
The input is an array ints [11, 2, 7, 8, 4, 6] and and integer s 10. The function is to output an array with a pair of two numbers from ints which first form a sum of 10. So here the output should be [2, 8], because 2 + 8 = 10. Why does it output empty array? The arrResults was updated in the nested for loop, so why doesn't it show up like that after the final return statement?
function sumPairs(ints, s) {
let arrResults = [];
let sumOfTwo;
for (i = 0; i < ints.length; i++) {
for (j = 0; j < ints.length; j++) {
sumOfTwo = ints[i] + ints[j];
if (sumOfTwo === s) {
arrResults.push(ints[i]);
arrResults.push(ints[j]);
break;
}
}
if (arrResults !== []) {
break;
}
}
return arrResults;
}
console.log(sumPairs([11, 2, 7, 8, 4, 6], 10));
Beside the wrong comparing of an array with another array (without having the same object reference)
a = []
b = []
a === b // false
// other example
a = []
b = a
a === b // true
for checking the length,
a = []
a.length // 0
and by using a nearly quadratic time complexity of n², even with looping
i = 0; i < array.length - 1
j = i + 1; j < array.length
which is more then the half of n², but strill quadratic,
you could take a single loop with an object fo already seen values.
This approach finds the first pair of the array for a certain sum.
function sumPairs(ints, s) {
const needed = {};
for (const value of ints) {
if (needed[value]) return [s - value, value];
needed[s - value] = true;
}
}
console.log(sumPairs([11, 2, 7, 8, 4, 6], 10));
Your code fails because you are checking to see if the array is empty. The problem is that check is never going to be false, so it exits on the first iteration.
console.log([]===[]);
console.log([]!==[]);
So code with changes to improve performance and to exit out
function sumPairs(ints, s) {
let arrResults = [];
let sumOfTwo;
for (let i = 0; i < ints.length; i++) {
for (let j = i + 1; j < ints.length; j++) {
sumOfTwo = ints[i] + ints[j];
if (sumOfTwo === s) {
arrResults.push(ints[i]);
arrResults.push(ints[j]);
break;
}
}
if (arrResults.length) {
break;
}
}
return arrResults;
}
console.log(sumPairs([11, 2, 7, 8, 4, 6], 10));
There is no need to break out twice, just return the array
function sumPairs(ints, s) {
let arrResults = [];
let sumOfTwo;
for (let i = 0; i < ints.length; i++) {
for (let j = i + 1; j < ints.length; j++) {
sumOfTwo = ints[i] + ints[j];
if (sumOfTwo === s) {
return [ints[i], ints[j]];
}
}
}
return null;
}
console.log(sumPairs([11, 2, 7, 8, 4, 6], 10));
I've been trying to push a number after the "for loop" into "x" but I cant use "x += count.push()" because it's not an array.
function partsSums(ls) {
let count = 0;
let x = []
while (ls.length > 0) {
for (let i = 0; i < ls.length; i++) {
count += ls[i]
}
x += count;
count = 0;
ls.shift()
}
return x;
}
console.log(partsSums([0, 1, 3, 6, 10]));
I need to get x = [20, 20, 19, 16, 10, 0] and I'm getting 2020191610 instead.
I'm pretty sure this is a no-brainer but I seem to be missing something...
You could reduce from the right.
function partsSums(array) {
return array.reduceRight((r, v) => [v + r[0], ...r], [0]);
}
console.log(partsSums([0, 1, 3, 6, 10]));
i'm starting studying javascript. I'm stuck with this exercise: Create a function that takes an array as argument and return the sum of all elements of the array.
I have written this code:
function sum(table) {
let x = table[0];
let y = [table.length - 1];
let totale = 0;
for (count = x; count <= y; count++) {
total += x;
x += 1;
};
return total;
};
console.log(sum[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
I don't know why the result is undefined instead of 55. Thanks for helping.
total not totale
the function call needs parentheses as sum([…])
y = table.length - 1 you want the length, not an array that holds the length
x = 0 you don't need to set it to the first element of the array
total += table[count]; you don't need to set it to x or to deal with x at all
function sum(table) {
let x = 0;
let y = table.length - 1;
let total = 0;
for (count = x; count <= y; count++) {
total += table[count];
};
return total;
};
console.log(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
Quicker Solution
function sum(table) {
return table.reduce((p,c)=>p+c,0);
};
console.log(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
Here are couple of things.
You need to execute the sum function by calling like sum([array elements]) .Note the ( & ) braces
Secondly count <= y will give undefined as it will exceed the length of the array. The array index starts from 0;
There is a typo here totale.
You can avoid these set of lines
let x = table[0];
let y = [table.length - 1];
if you just initialize the loop conditional statement like this
for (let count = 0; count < table.length; count++)
function sum(table) {
let x = 0
for (let count = 0; count < table.length; count++) {
x += table[count];
};
return x;
};
console.log(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
Another option is to use the reduce method
function sum(table) {
return table.reduce(function(acc, curr) {
return acc += curr;
}, 0) // 0 is the initial value
};
console.log(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
Lets assume we have an array of those elements (always sorted).
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]
Our goal is to find the min-index and max-index of a given value e.g. Lets assume we're searching for the min-index and max-index of the element 3.
We quickly see, that the min-index for 3 is 8 and the max-index is 11.
For the value 1, the min is 0 and the max is 3.
How would you develop a solution for that returns the min and max in JavaScript? I have tried to do this, but I can't figure how to, I always get the wrong answer.
You can try Array.indexOf() and Array.lastIndexOf()
var sortedArr =[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3];
console.log(sortedArr.indexOf(1));
console.log(sortedArr.lastIndexOf(1));
Basically Array.indexOf() and Array.lastIndexOf() will do it but they'll do a linear search (go through whole array with a loop until the element is found) which is obviously done in linear time O(n).
If it is true that your array is always sorted then we can use this property to optimize it and use binary search. It is way faster and will do it in logarithmic time O(log n).
After that we simply check the elements before (and after) the found index and until we find an element which isn't equal to our element.
For finding last occurence:
var i= foundIndex;
while(sortedArr[i] == sortedArr[foundIndex]){
i++;
}
foundIndex = i;
And for first occurence:
var i= foundIndex;
while(sortedArr[i] == sortedArr[foundIndex]){
i--;
}
foundIndex = i;
That's it! This will help a lot with the run time especially if you have big arrays.
You can find binary search implementations everywhere, just use any of them.
Is that what you want?
var myarr = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3];
var minNum = myarr[0];
var maxNum = myarr[1];
var minNumStartINDX, maxNumStartINDX, minNumEndINDX, maxNumEndINDX;
/********************************************/
for (var x = 0; x < myarr.length; ++x) {
if (minNum >= myarr[x]) {
minNum = myarr[x];
minNumEndINDX = x;
}
}
for (var x = 0; x < myarr.length; ++x) {
if (minNum >= myarr[x]) {
minNumStartINDX = x;
break;
}
}
for (var x = 0; x < myarr.length; ++x) {
if (maxNum <= myarr[x]) {
maxNum = myarr[x];
maxNumEndINDX = x;
}
}
for (var x = 0; x < myarr.length; ++x) {
if (maxNum <= myarr[x]) {
maxNumStartINDX = x;
break;
}
}
/********************************************/
console.log(minNum);
console.log(minNumStartINDX + "-" + minNumEndINDX);
console.log(maxNum);
console.log(maxNumStartINDX + "-" + maxNumEndINDX);
var data={1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3};
var value=3;
var min=data.length;
var max=0;
for(var key in data){
if(data[key]==value){
if(key<min){
min=key;
}
if(key > max){
max=key;
}
}
console.log(min);
console.log(max);
in the for loop below I have arr[i] = x * i; I am basically trying to get multiples of numbers. the results of the code I have now is [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] I do not want the first element of the array to be 0 ..
var n = 10;
var arr = [];
var x = 2;
for(var i = 0; i < n; i++ ){
//arr[0] = x;
arr[i] = x * i;
// arr.push(x += x)
}
console.log(arr)
i want to be able to do arr[0] and see x. In this case that would be 2 (the number for the multiples..I don't know math words) [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
I know that the problem is that 2 * 0 is equal to 0 so arr[0] = 0. what is the best way to make it so that the first element will be the second loop. I was thinking about making an if statement. or using an array method that slices of the beginning of the array. I hope there is an easier way like changing the for loop.
There are two simple ways to fix this
Change the loop starting value
var arr = [],
x = 2,
n = 10;
for (var i = 1; i <= n; i++) { // Start with `1`
arr.push(x * i);
}
Or, multiply with the next value of i,
var arr = [],
x = 2,
n = 10;
for (var i = 0; i < n; i++) {
arr.push(x * (i + 1)); // Multiply with i + 1
}
If you still want to solve it with array index assignment, then just remove the first element, with Array.prototype.slice after creating the entire array, like this
var n = 10,
arr = [],
x = 2;
for (var i = 0; i <= n; i++) { // Note the limits, 0 to <= n
arr[i] = x * i;
}
console.log(arr);
// [ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 ]
arr = arr.slice(1);
console.log(arr);
// [ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 ]