Sum of range in array - javascript

I am having a huge issue with a coding problem I need to make. I am being asked to run a sum of numbers inside of an array and I can't get the code to run properly.
This is my code and below are the instructions of what I am being asked to run:
function sumOfRange(numbers){
var numbers = [1,-1,1,-1,1];
var sum = 0;
for (var i = 0; i < numbers.length; i++){
sum += numbers[i];
}
return sum;
}
// Your Challenge:
// - Create a function named sumOfRange.
// - It accepts one parameter, called numbers, that
// represents an array of numbers.
//
// - In your function, sum the numbers inside the array.
// (Reminder: you'll need a variable to store the result.)
// - Return the result.
// Hint: You do not need to create a new array - you will be
// looping through the parameter, which is already coming in as
// an array.
// Someone else will be calling your function like this:
// sumOfRange([1,2,3,4,5])
// sumOfRange([-4,-5,-10,0])
I keep getting
errors saying
You returned '1'. That isn't quite right. The sum of [1,2,3,4,5] is 15.
Any help with this would greatly appreciate it.

Remove the first line of your function sumOfRange() var numbers = [1,-1,1,-1,1] because you are re-initializing the value of numbers, you need to use to array that is passed to the function when it is called.
function sumOfRange(numbers) {
var sum = 0;
for (var i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
return sum;
}
console.log(sumOfRange([1,-1,1,-1,1]));
console.log(sumOfRange([1,2,3,4,5]));
console.log(sumOfRange([-4,-5,-10,0]));

var a = [1,2,3,4,5];
function sum (arr) {
return arr.reduce(function(prev, curr) {
return prev + curr;
}, 0);
}
//sum(a) -> returns 15

Related

Seeking Help Understanding Difference between For Loop & .forEach

I have two functions that should produce the same result. I would like clarification as to why they do not. I'm not grasping the significant difference that must exist between for-loop and .forEach.
I'd like to though :)
//
//DEMO OBJECT WITH TWO ARRAYS
//
var myArray = {
myList1 : [1,2,3,4],
myList2 : [5,6,7,8]
}
//
//FUNCTION ONE: Produces the sum of myArray.myList1 as expected.
//
var firstWay = function(){
var sum = 0;
for(var i = 0; i < myArray.myList2.length; i++){
sum += myArray.myList2[i];
}
return sum
};
var results2 = firstWay();
console.log(results2);
//FUNCTION TWO PRODUCES NaN
//1.) I don't know why it produced NaN.
//2.) I don't understand why this function wouldn't produce the same result as firstWay.
var secondWay = function() {
var sum = 0;
myArray.myList1.forEach(function(cur){
sum += cur.value;
});
return sum;
};
var results1 = secondWay();
console.log(results1);
Remove value from sum += cur.value so it's just sum += cur. The value
you need is already contained in cur.
var secondWay = function() {
var sum = 0;
myArray.myList1.forEach(function(cur){
sum += cur;
});
return sum;
};
var results1 = secondWay();
console.log(results1);
Many answers just stand in the doc and might be found by googling.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
callback
Function to execute on each element. It accepts between one and three arguments:
currentValue
The current element being processed in the array
index Optional
The index currentValue in the array
array Optional.
The array forEach() was called upon "
So cur in your code is the current element of your array of integers. So it's an integer. So it has no value property, it IS the value you're looking for, as pointed out in a comment.
On the second iteration you wrongly put sum += cur.value.
The right way shoud be : sum += cur.

How to iterate over an array of numbers to find the first number that occurs 3 times in the array

I have the following code
let range = [1,2,3];
let multiples = [1,2,3,4,5,6,2,4,6,3,6];
I want to find the first number in the multiples array that occurs range.lenght times (3);
I want to start with multiples[0] check how many times it occurs in multiples, if it occurs 3 times I want to return multiples[0], if it is less than 3 times, I want to check how many times multiples[1] occurs in the multiples array. If multiples[1] occurs 3 times I want to return multiples[1], else I move on to check multiples[2], etc. until I find a number that occurs 3 times. In the code above I should return 6.
I've looked at
How to count the number of certain element in an array?
and
Idiomatically find the number of occurrences a given value has in an array
and
get closest number out of array
among other research but have not figured it out yet.
I tried to simplify the question as much as possible. But if more info is needed it relates to this challenge on freeCodeCamp. Where I am at with my code is
function smallestCommons(arr) {
let sortArr = arr.sort((a, b) => a - b);
console.log(sortArr);
let range = [];
for (let i = sortArr[0]; i <= sortArr[1]; i++) {
range.push(i);
}
console.log("range = " + range);
let maxNum = range.reduce( (a, b) => a * b);
console.log("maxNum = " + maxNum);
let multiples = [];
for (let i = 0; i < maxNum; i++) {
let j = 0;
do {
multiples.push(j + range[i]);
j += range[i];
} while (j < maxNum);
//j = 0;
}
for (let i = 0; i < multiples.length; i++) {
let numberToFind = multiples[i];
/*stuck here hence my question, maybe I shouldn't even start with a for loop*/
//tried reduce, forEach, filter, while loop, do while loop
}
console.log("multiples = " + multiples);
}
console.log(smallestCommons([1,3]));
The logs are
1,3
range = 1,2,3
maxNum = 6
multiples = 1,2,3,4,5,6,2,4,6,3,6,NaN,NaN,NaN
What you can do is, first split your string with , and then using below function loop for check.
function countLength(arr, checkNumber) {
var count = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] === checkNumber) {
count++;
}
}
return count;
}
countLength(list, NUMBER YOU WANT TO CHECK);
And if you want to check first number occur for 3 time then you need to make change in function and introduce .map or .filter in action to count number.
Example
const multiples = [1,2,3,4,5,6,2,4,6,3,6];
let occurance_arr=[];
const aCount = [...new Set(multiples)].map(x => {
if(multiples.filter(y=> y==x).length == 3) {
occurance_arr.push(x);
}
});
console.log(occurance_arr);
Above code will give you 6 in console, if you have multiple value then 0th element is the answer you are looking for which is first three time occurrence of item.
You can loop through your list keeping an object that maps each number to the number of times you've seen it. You can check the counts object as you loop, so if you see a number and the count is one less than your target, you can return it. If you make it through the loop without returning you didn't find what you're looking for — return something sensible :
let range = [1,2,3]
let multiples = [1,2,3,4,5,6,2,4,6,3,6]
function findFirstMult(arr, len){
let counts = {} // to keep track of how many times you've seen something
for (let n of arr){ // loop throught the array
if (!counts[n]) counts[n] = 0 // if it's then first time you've seen n, defined that key
if (counts[n] == len - 1) return n // found it
counts[n] +=1 // otherwise increase the count
}
return undefined
}
console.log(findFirstMult(multiples, range.length))
This will require only one loop through the array in the worse case and will return early if if finds something.

javascript while loop correctly iterating but for loop with same logic is not, on array with integer values and some null values in there

Iterating through a javascript array which has some data in, and some null or not defined values also, is giving funny behaviors with a for loop, but not with a while loop. It is not returning when it should and is stuck in an infinite loop
I have investigated the outputs extensively, the condition whether the number exists in the array is never evaluated to be true, only ever false, but it sometimes enters the if statement region as if it is true. It is seemingly arbitrary.
//function called within this code
function randomArrayOfIndexes() {
var randNumbArray = new Array(4);
var indexToAssign = Math.floor(Math.random() * Math.floor(4));
randNumbArray[0] = indexToAssign;
for (i = 1; i < randNumbArray.length; i++) {
indexToAssign = Math.floor(Math.random() * Math.floor(4));
while (arrayContains(randNumbArray, indexToAssign)) {
indexToAssign = Math.floor(Math.random() * Math.floor(4));
}
randNumbArray[i] = indexToAssign;
}
return randNumbArray;
}
//this works
function arrayContains(arrayin, numberIn) {
var i = arrayin.length;
while (i--) { //takes one from i so highest index is accurate on first iteration
if (arrayin[i] === numberIn) {
return true;
}
}
return false;
}
//this doesn't... not even backwards like the above iteration
function arrayIncludes(arrayin, numberIn) {
for (i = 0; i < arrayin.length; i++) {
if (arrayin[i] === numberIn) {
return true;
}
}
return false;
}
At first each function above is passed in an array with [int value, null, null, null], and a random number; when the function returns, the next null value is filled with the random number that doesn't exist in it already, so [int value, int value, null, null]... until all values are filled... the final array is filled with unique random numbers from 0 to 3, to provide an index for a piece of data in another array... to make sure that it is only used once in the program I am writing.
I would expect it to return true if the number passed in is already in there, another random number then generated outside of the broken function, and the process repeated until a unique random number is found. When it is found, the array being passed back in will be populated at the next available index, and the process repeated. This is not happening. It is getting stuck in an infinite loop, and never returning
you are just missing a var before i:
function arrayIncludes(arrayin, numberIn) {
for (var i = 0; i < arrayin.length; i++) {
// in ^ here
if (arrayin[i] === numberIn) {
return true;
}
}
return false;
}
You may also declare it before loop, like
var i;
for (i = 0; i < arrayin.length; i++) {
...
By the way, this way of generating random numbers without duplicates is very inefficient, I suggest something like having an array of 0-3 (in your current example) or 0-n and then just randomly taking items out of it. then you don't have to loop through the whole array each time you find a new number. every time you just find a random index between 0 and the length of remaining items.
Imagine that the array length is 1000, and the last item remaining is a number like 100, how many times you have to find a random number and loop through whole array till your random number is 100?
var n = 5;
var a = new Array(n);
for(var i=0;i<n;i++) a[i] = i;
var result = new Array(n);
var i = n;
while(i)
{
var index = Math.floor(Math.random() * i);
result[--i] = a[index];
a.splice(index,1);
}
document.getElementById('a').innerHTML = result;
<div id="a"></div>
You need to declare variables in you loops with for i=0. if you don't do this the variable is global and when you use the same loop variable in nested loops one can change the other.
You are using i in both loops so when you call the for loop with:
function arrayIncludes(arrayin, numberIn) {
for (i = 0; i < arrayin.length; i++) {
// etc
}
You set i back to 0 ad iterate it — this is the same i you are using in randomArrayOfIndexes so it interferes with that loop. This is a common cause of hard-to-find bugs and is hy you should always declare loop variables.
Here's the bug in it's simplest form. Notice that the out loop only runs once because i is incremented in the inner loop causing the outloop to exit early:
for (i = 0; i < 4; i++){
console.log("out loop number: ", i)
for (i = 0; i < 4; i++){
console.log("inner_loop: ", i)
}
}
If you declare the variables for for let i =, each loop gets its own version of i both loops run independently:
for (let i = 0; i < 4; i++){
console.log("out loop number: ", i)
for (let i = 0; i < 4; i++){
console.log("inner_loop: ", i)
}
}

Count Bits from unsigned integer

I am attempting to write a function that takes an (unsigned) integer as input, and returns the number of bits that are equal to one in the binary representation of that number.
Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case.
Here is my answer:
var newArr;
var count = 0;
function countBits(num){
newArr = num.toString(2).split('').map(function(el){
if(el == '1')
count++
});;
return count;
}
In my program when I call countBits(7) it returns //3 but when I submit my response it says it is returning //4. Can someone see what I am missing in my response based on question?
Your problem is that you are declaring the variables outside of the function, so when the function is called multiple times they'll keep their values and just increase the count.
Btw, you also shouldn't use map if you don't want to create another array - so better do
function countBits(num){
var newArr = num.toString(2).split('').map(Number);
var count = 0;
for (var i=0; i<newArr.length; i++)
count += newArr[i];
}
return count;
}
or
function countBits(num){
return num.toString(2).split('').reduce(function(count, el) {
return count + (el == "1");
}, 0);
}
function countBits(num){
/* Convert num Base10 to num Base2
then find Ones and save them in an array
length of the array is equal their sum */
return num.toString(2).match(/1/g).length
}
function countBits(num){
// convert num Base10 to Base2
let base2 = num.toString(2)
// declare variable for sum of bits
let sum = 0
// for loop to check bits (bit = 1) and ignore Zeros in the String base2
for(let i = 0; i < base2.length; i++){
if(base2[i] == 1){
// use Number() to convert string to number
count += Number(base2[i])
}
}
return sum ;
}

Sorting odd and even numbers with the remainder operator Javascript

If a number, when divided by two, has a remainder that is not equal to 0, this number must be odd. I'm trying to use that logic in my if statement to keep only odd values, and get rid of even ones. I'm not sure how I'm doing this wrong, but myArray is returning even values as well as odd. Any ideas?
function sumFibs(num) {
var myArray = [1,1];
// Create fibonacci sequence
// Stop creating fibonacci numbers at num
// Push odd numbers to oddNums array
for (var i = 0; i < myArray.length; i++) {
if (myArray[i+1] + myArray[i] <= num && myArray[i+1] + myArray[i] % 2 !== 0) {
myArray.push(myArray[i+1] + myArray[i]);
}
} // End loop.
console.log(myArray);
// Summation of oddNums array.
return myArray.reduce(function(a,b) {
return a + b;
});
} // End function.
sumFibs(1000);
You are trying to filter odd values while generating your fib sequence, which probably not the best approach. If you wrap the modulo expression in parentheses,
(myArray[i+1] + myArray[i]) % 2
Your array will not contain the values necessary to continue generating the sequence. Ideally you should generate the full fib series and then filter:
var myArray = [1,1];
for (var i = 0; i <= num; i++) {
myArray.push(myArray[i+1] + myArray[i]);
} // End loop.
myArray = myArray.filter(function(a){ return a%2 !== 0 })
or save some reference to the even values so that they can be used to calculate the desired subset of the series.

Categories

Resources