Trying to figure out what's wrong with this piece of code.
//Code to return the sum of all values in an array
var x = [ 1,2,3,4,5 ];
//Function to return sum of values in an array
function sum(arr) {
var sum = 0;
for (i=1; i < arr.length; i++) {
sum = sum + x[i];
}
return sum;
}
What will be the value of sum(x)?
There's a couple issues here, some are worse than others
First of all you should delcare i as a variable, i=0 -> var i = 0
Then you need to start your for loop at 0 instead of 1 for(var i = 1 -> for(var i = 0 Arrays in javascript (and pretty much every other language) are 0-indexed. That means the first item is arrayName[0] not arrayName[1]
Then you were accessing your value in the array wrong you need to use arr[i] not x[i]. You want to access the value passed to the function, not the actual array you created before.
Line 8 can be shortened using += and was also missing a semicolon
//Code to return the sum of all values in an array
var x = [1, 2, 3, 4, 5];
//Function to return sum of values in an array
function sum(arr) {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
console.log(sum(x)); //15 -- it works! (1+2+3+4+5=15)
As others have stated the issue is that arrays, and most other things in programming, are zero-indexed.
May I suggest an alternative stylistic choice...
var x = [ 1,2,3,4,5 ];
//Function to return sum of values in an array
var sum = function (arr) {
return arr.reduce(function(a,b){return a+b;})
}
console.log(sum(x));
Though, at this point the function is one line of code, and not really worth wrapping in a function. With things like that I simply do it inline.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
As #user6188402 mentions, i must start at 0.
Here's why:
var x = [ 1,2,3,4,5 ]; creates an array whose index starts at 0, so:
x[0] = 1
x[1] = 2
x[2] = 3
x[3] = 4
x[4] = 5
If you do sum = sum + x[i]; starting at 1, the answer will be 14 instead of 15
Related
I want to find all possible arrays -of non-negative integers- of size L that sum up to -at most- N in JavaScript:
function findArrays(size, maxSum){}
Example input: findArrays(3, 2)
Example output:
[[0,0,0], [0,0,1], [0,0,2], [0,1,0], [0,1,1], [0,2,0], [1,0,0], [1,0,1], [1,1,0], [2,0,0]]
What I tried:
I came up with this algorithm:
Starting from left, add the array members
If the sum is equal to N at slot i:
If the member at the current index is equal to N, reset all the indices up to here and increment the next slot
Otherwise: reset previous slots and increment this slot
Otherwise:
Increment the first available slot
My code:
let getNextArray = (r,L,N)=>{
let sum=0, ind=0, i;
for(i=0; i<L; i++){
sum += r[i];
if(sum===N){
ind = i + (r[i]===N?1:0);
break;
}
}
r[ind]++;
for(i=0; i<ind; i++){
r[i]=0;
}
return r;
};
let findArrays=(L, N)=>{
let arrays=[],r=[],i;
for(i=0; i<L; i++){
r[i] = 0;
}
while(r[L-1]<N){
r = getNextArray(r,L,N);
arrays.push(r.slice());
}
return arrays;
}
It works for my example input, but when I call it with findArrays(5,3) it finds half (28 / 56) of the answers. Even if I made it work, I doubt it would be efficient for bigger inputs as it calculates the sum for each turn. I'm sure there is a more clever way to do it which I can't find..
Yesterday I asked a similar question which had a very good answer in terms of efficiency, but I realized I need fixed sized arrays. Apologies for the similar question but maybe it will help someone else one day :)
I could also use a method findArrays(size, sum) and iterate it with sums 1:N, unfortunately I don't know how to do that either.
You could modify trincot's solution with a small filter at the end:
function findArrays(maxSize, maxSum) {
let arr = [];
let result = []; // <--- will collect all the subarrays
function recur(maxSum) {
let k = arr.length;
result.push([...arr]);
if (k === maxSize) return;
for (let i = 0; i <= maxSum; i++) {
arr[k] = i;
recur(maxSum - i);
}
arr.length = k;
}
recur(maxSum);
return result.filter(({ length }) => length == maxSize);
}
// demo
for (let arr of findArrays(3, 2))
console.log(JSON.stringify(arr));
Here's a non-yielding version of a recursive function which will give the results you want. It figures out all possible values at the current level (0..maxSum) and then appends them to all possible results for arrays with size-1:
const findArrays = (size, maxSum) => {
let possibles = Array.from({
length: maxSum + 1
}, (_, i) => i);
if (size == 1) return possibles;
let result = [];
possibles.forEach(p => {
findArrays(size - 1, maxSum - p).forEach(a => {
result.push([p].concat(a));
});
});
return result;
}
console.log(findArrays(3, 2));
Update: The answer to this question is bellow. Thanks to dougtesting on a different thread. add array together, display sum
function hello() {
var arr = [];
for (var i = 0; i < 10; i++) {
arr.push(prompt('Enter number' + (i+1)));
}
var total = 0;
for(i=0; i<arr.length; i++) {
var number = parseInt(arr[i], 10);
total += number;
}
console.log(total);
}
//End of answer.
I am trying to have a user input 10 numbers. Then add those numbers together and display the output to the user. I was able to get the amount of inputs (10) into a array but I can't get arrays contents. I feel like I'm missing something simple. Would you mind taking a look?
// https://stackoverflow.com/questions/28252888/javascript-how-to-save-prompt-input-into-array
var arr = []; // define our array
for (var i = 0; i < 10; i++) { // loop 10 times
arr.push(prompt('Enter number' + (i+1))); // push the value into the array
}
alert('Full array: ' + arr.join(', ')); // alert the result
var arrEquals = []; //Empty Arr
arrEquals = arr.push(); //turn string into var
alert (arrEquals);//show string to admin for debug
//(for loop) console out # of array elements. does not output what is in array
//this is half the battle
for (var a = 0; a < arrEquals; a++){
var a = Number(a); //ensure input is Number()
console.log(a + "A"); //used for debug
}
//taks sums in array and adds them together
//this is the other half of the problem
// https://www.w3schools.com/jsref/jsref_forEach.asp
// var sum = 0;
// var numbers = [65, 44, 12, 4];
// function myFunction(item) {
// sum += item;
// demo.innerHTML = sum;
// }
This is probably one of the simplest examples of something that Javascript's built in array .reduce() function would be used for. Effectively, you're "reducing an array to a single value".
A reduce works by taking an array and running a function on each item. This "callback" function receives the value that the previous function returns, processes it in some way, then returns a new value. Worth noting, the reduce function also takes a 2nd argument that acts as the initial value that will be passed to the callback function the first time.
array.reduce(callbackFunction, initialValue);
Here's an example of reduce being used to sum an array.
var result = [1,2,3,4,5,6,7,8,9,10].reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0); // start with an initial value of 0
console.log(result);
Using ES6 syntax, this can be further simplified to a one-liner
var result = [1,2,3,4,5,6,7,8,9,10].reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(result);
In your loop you're referencing arrEquals like for (var a = 0; a < arrEquals; a++){. you need to reference it like for (var a = 0; a < arrEquals.length; a++){ because just referencing the array doesn't tell javascript how long it is, or what number to count to. the .length returns a number, that number is how many items are in the array.
var arr = []; // define our array
for (var i = 0; i < 10; i++) { // loop 10 times
arr.push(prompt('Enter number' + (i+1))); // push the value into the array
}
arr = arr.join(', ');
alert('Full array: ' + arr); // alert the result
var arrEquals = []; //Empty array
arrEquals.push(arr); //assign arr string to an empty array
alert (arrEquals[0]); //show array[0] string to admin for debug
Is this what you are looking for? You need to put the arr.join() result to a variable, like itself.
You shouldnt be using arr.push() at all if you're not pushing new array items on it
//(for loop) console out # of array elements. does not output what is in array
//this is half the battle
for (var a = 0; a < arrEquals.length; a++){
//a is always a int in this case
console.log(a + "A"); //used for debug
}
I'm working on an algorithm problem (on leetcode) which is asking the following:
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3] return 2.
My current answer is:
var missingNumber = function(nums) {
return nums.filter(function(item, index, arr) {
return arr[index] - arr[index - 1] > 1;
}).shift() - 1;
};
However, leetcode is using these two test cases (among some others) which make no sense to me:
Input: [0]
Expected: 1
Input: [0, 1]
Expected: 2
EDIT: also...
Input: [1]
Expected: 0
From what I understand, the algorithm is asking to return a single number that is missing from an array, given there is a number that is actually missing in the first place. Am I missing something here or are the instructions for this algorithm very unclear?
There is a different way to do it using XOR operation. The idea here is that a number XORed with itself will always be 0. We can store XORs of all the numbers from 0 to N in variable xor1 and XORs of all the numbers of our array in variable xor2. The XOR of xor1 and xor2 will be the missing number as it will only appear in xor1 and not in xor2.
function foo(arr){
var n = arr.length;
var xor1 = 0, xor2 = 0;
for(var i = 0;i <= n;i++)
xor1 ^= i;
for(var i = 0;i < n;i++)
xor2 ^= arr[i];
return xor1 ^ xor2;
}
The total of the integers from 1..n is:
So, the expected total of an array of length n with values from 0..n would be the same. The missing number would be the total minus the sum of the actual values in the array:
"use strict";
let missingNumber = function(nums) {
let n = nums.length;
let expected = n * (n + 1) / 2;
let total = nums.reduce((a, b) => a + b, 0);
return expected - total;
}
This is how I would implement it, you can loop until <= to the array length so if the passed in array passes the test it will try to look at nums[nums.length] which will be undefined and return i correctly. Return 0 if they pass in an empty array.
var missingNumber = function(nums){
for(var i = 0; i <= nums.length; i++){
if(nums[i] !== i) return i;
}
return 0;
}
Try using indexOf() method. It returns -1 if the item is not found.
nums = [0, 1, 3];
var missingNumber = function(nums){
for(i = 0; i <= nums.length; i++){
if(nums.indexOf(i) < 0 ) {
return i;
}
}
return 0;
}
All the relevant code is provided here http://jsfiddle.net/DuWGj/ , as well as print(appendTo) statements.
To keep it short, I'm making 4 arrays. Each array has 4 numbers. Then I create a new array that has all those 4 arrays numbers inside of it, so it's one array.
For example the end result is
four.myArraysCombined = [5,3,20,12,3,4,18,11,12,5,8,2,1,9,10,6];
However, when I try
four.myArraysCombined[3] , it says it's undefined.
so obviously when I do the following it doesn't work
var total = 0;
for (var x = 0; x < 16; x++) {
total += four.myArraysCombined[x]);
}
I'm looking to be able to add all those numbers together with a for loop. I've tried several things but it keeps giving me undefined or NaN.
What is happening
After running:
prePickNumbers(four, 4, 40, 20, 1);
...the value of four.myArraysCombined is:
[[[2, 17, 20, 1], [7, 2, 20, 11], [7, 14, 3, 16], [12, 17, 3, 8]]]
In other words, it is not the result that you claim it is. You should verify that you have the result that you think you do at each step of the process, before moving on. As it stands, you do not have a flattened array. You need to fix that first and then move on to iterating and summing.
Why this is happening
The reason for the final structure starts at the following line in prePickNumbers:
tempMyArraysCombined.push(objName.myArray[x]);
You're pushing an array into another array each time, so the result after the loop is an array of arrays. But, then, you push that result into another array:
objName.myArraysCombined.push(tempMyArraysCombined);
So the final result is actually an array containing an array of arrays (notice the extra set of brackets in the output above). The problem is that you're pushing an entire array into your output at each step in the process, which is creating a nested mess. You should be pushing elements of each array, not the arrays themselves.
How to fix it
Here is one possible solution. Replace prePickNumbers with the following function:
function prePickNumbers(objName, theNum, theSumNum, theMaxNum, theMinNum) {
var tempMyArraysCombined = [];
for (var x = 0; x < theNum; x += 1) {
pickNumbers(objName.myArray[x], theNum, theSumNum, theMaxNum, theMinNum);
for (var j = 0; j < objName.myArray[x].length; j++) {
objName.myArraysCombined.push(objName.myArray[x][j]);
}
}
}
You may want to try
total += four.myArraysCombined[0][x]
I extract this from you fiddle:
function prePickNumbers(objName, theNum, theSumNum, theMaxNum, theMinNum) {
var tempMyArraysCombined = [];
for (var x = 0; x < theNum; x += 1) {
pickNumbers(objName.myArray[x], theNum, theSumNum, theMaxNum, theMinNum);
tempMyArraysCombined.push(objName.myArray[x]);
}
objName.myArraysCombined.push(tempMyArraysCombined);
}
edit the last line to:
function prePickNumbers(objName, theNum, theSumNum, theMaxNum, theMinNum) {
/* your code */
objName.myArraysCombined=tempMyArraysCombined; //edit this line not push() but =
}
now there are no "UNDEFINED" in output html.
:)
I recently came across the following piece of sample code:
function range(upto) {
var result = [];
for (var i = 0; i <= upto; i++) {
result[i] = i;
}
return result;
}
and I'm confused as to why:
result[i] = i;
as opposed to:
i = result[i];
Isn't 'i' the variable and 'result[i]' the value?
This fills the array :
result[0] = 0 // sets the first cell of the array to the value 0
result[1] = 1
etc.
This function returns
[0, 1, 2, ... upto]
More about arrays in JavaScript
The
result[i] = i;
assigns the value of i to the i-th element of result.
Thus, result[0] becomes 0, result[1] becomes 1 and so on.
result[i] = i; means you are assigning the value of i to the index i of the array result.
i = result[i]; means you are assigning the value of the i-th index of the array result,to the variable i.
That's it.