Fibonacci Sequence - Starts at a specific # in javascript - javascript

//var myInputNumber=10;
function fibonacci(num) {
let fib = [1,1];
for (let i = 2; i <= num; i++) {
fib.push(fib[i-1] + fib[i-2]);
}
return fib;
}
console.log(fibonacci(10));
Complete javascript newbie here. I need help with a homework project. I have this work and displays up to the x (for easier display) Fibonacci numbers.
Here is the results from the above code: [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ]
What I want to be able to do is specify the starting number/point (>=10, for example), and have it only display numbers from that point going forward.
So if my input number is 10, I want this result [ 13, 21, 34, 55, 89 ].

Use array filter and in the callback function return those element which are greater than the number passed as argument
function fibonacci(num) {
let fib = [1, 1];
for (let i = 2; i <= num; i++) {
fib.push(fib[i - 1] + fib[i - 2]);
}
return fib.filter(function(item) {
return item > num
});
}
console.log(fibonacci(10));

just add another variable then
function fibonacci(num) {
let result = [];
let fib = [1,1];
for (let i = 2; i <= num; i++) {
let temp = fib[i-1] + fib[i-2];
fib.push(temp);
if(result>=num)
result.push(temp)
}
return result;
}

You may also want to define a limit to stop. The rest is pretty much similar to your existing code
function fibonacci(num, limit) {
let fib = [1,1];
for (let i = num; i <= limit; i++) {
fib.push(fib[i-1] + fib[i-2]);
}
return fib;
}

Related

Find lowest positive integer that does not appear in array

I am trying to solve a leetcode type problem that is a practice problem that came with an upcoming code test I need to do for a job and I am having trouble with it. Can anyone help me understand whats going wrong?
I am essentially looking for the brute force option as I dont know algos/DS.
PROBLEM:
Write a function:
function solution(A);
that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
Given A = [1, 2, 3], the function should return 4.
Given A = [−1, −3], the function should return 1.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [−1,000,000..1,000,000].
HERE IS MY SOLUTION:
function solution(A) {
let newArray = A.sort(function(a, b){return a-b})
let lowestNumber = 1
for(i=0; i < newArray.length; i++) {
if(lowestNumber > newArray[0]) {
return lowestNumber
}
if(lowestNumber == newArray[i]) {
lowestNumber = lowestNumber + 1
}
if(i = newArray.length - 1) {
return lowestNumber
}
}
}
The below snippet isnt working like I expect it to. lowestNumber isnt being increased and also the loop is exiting here I believe.
if(lowestNumber == newArray[i]) {
lowestNumber = lowestNumber + 1
Thanks for your help!
You can do this in O(N) using a Map():
First set every number in the array.
Then starting from 1 look for and return the missing number in the sequence.
function solution(arr) {
const seen = new Map();
for (let i = 0; i < arr.length; i++) {
seen.set(arr[i]);
}
for (let i = 1; i <= arr.length + 1; i++) {
if (!seen.has(i)) return i;
}
return 1;
}
console.log(solution([1, 3, 6, 4, 1, 2])); //-> 5
console.log(solution([1, 2, 3])); //-> 4
console.log(solution([-1, -3])); //-> 1
I think your > should be <, and the = in if(i = newArray.length - 1) should be ===.
And lowestNumber > newArray[0] will always be true if the array contains a negative number, so 1 will be returned.
Your effort seems careless, so you are going to have to up your game for the interview.
const integers = [5, -345, 562456, 95345, 4, 232, 1, 2, 3, 7, -457];
function solution(A) {
let newArray = A.sort((a, b) => a - b);
let lowestNumber = 1;
for (let i = 0; i < newArray.length; i++) {
const n = newArray[i];
if (n > 0) {
if (lowestNumber < n) {
return lowestNumber;
} else {
lowestNumber = n + 1;
}
}
}
return lowestNumber;
}
console.log(solution(integers));
The fastest solution
function solution(A) {
// write your code in JavaScript (Node.js 8.9.4)
if (!A) return 1;
A.sort();
if (A[A.length - 1] < 1) return 1;
const setA = new Set(A);
let length = setA.size;
for (let i = 1; i <= length; i++) {
if (!setA.has(i)) {
return i;
}
}
return length + 1;
}
I have worked same problem for nowadays, and regardless the original answer, here is my version of finding least positive number which is missing the in the array.
function findLeastPositive(array) {
const numbersSet = new Set(array);
let leastPositiveNumber = 1;
while(numbersSet.has(leastPositiveNumber)) {
leastPositiveNumber++;
}
return leastPositiveNumber;
}
let result = findLeastPositive([1,2,3,4,5,6,7,8,9,0]);
console.log(result);
result = findLeastPositive([10,11,12,13,14,15,16,17,18,19]);
console.log(result);
There are sure similar answers floating on the internet but using given array length disturbing me of which I can't explain properly why we have to create second loop starts with 1 (known the least positive number) and to N.
Using hash table (I am using Set here) for lookup table is fine idea, as in it effect to overall performance O(N) (probably initialize the Set with array) and O(1) for checking if the value in the Set or not.
Then we need to set second loop for obvious reason that checking the the smallest positive number existence, starting from 1..N range. This is the part bugged me, so I decided to go for while loop. It's obvious rather why there's a for..loop starts from 1..N on which N is the length of the array.
Here is 100% code
function solution(A) {
/**
* create new array of positive numbers in given array,
* if there sis no specific number in given array, in result array
* that index will be undefine
*/
const c = A.reduce((arr, cur) => {
if(cur > 0) arr[cur] = 1;
return arr;
} , [1] )
/**
* return first undefined index
*/
for(let i = 0; i < c.length; i++)
if(!c[i]) return i;
// otherwise return the maximum index in array
return c.length;
}
function solution(arr) {
for (let i = 1; i <= arr.length + 1; i++) {
if (!arr.includes(i)) return i;
}
return 1;
}
console.log(solution([1, 3, 6, 4, 1, 2])); //-> 5
console.log(solution([1, 2, 3])); //-> 4
console.log(solution([-1, -3])); //-> 1

How do I write a function that returns the first 5 positive even numbers?

var myArr = [1,2,3,4,5,6,7,8,9,10];
function even(num) {
var newArr = [];
for (var i=1; i<num.length; i++) {
if (num[i] % 2 === 0) {
newArr.push(num[i]);
}
}
return newArr;
}
console.log(even(myArr));
My function throws an exception when called. How can I rewrite or refactor the above code to return the first 5 positive numbers?
You can create it this way.
var myArr = [1,2,0,3,4,-6,5,-3,88,21,-6,5,6,7,8,9,10];
let evens = myArr.filter(x => x > 0 && x % 2 == 0).slice(0, 5);
console.log(evens)
First off, your code appears to work. Can you give an example of the error that is occurring? Second off, if you want a function that returns an array of the first n positive, even integers, you can write something like this.
function firstEven(count) {
var response = []; // Create the response list
for(var i=0;i<count;i++) { // Loop for number of even numbers you want
response.push((i + 1) * 2); // *2 skips every two numbers, and +1 shifts the number to even
}
return response
}
However, if you want to just filter out all odd numbers from an array, you can do the following.
var myArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var myEvens = myArr.filter(function(myNum) { // Filter runs the function for every value in the array, and (if the function returns false) it removed that value
return (myNum % 2) == 0;
});
Feel free to ask if you have any questions!
2 others differnts ways
const myArr = [1,2,3,4,-6,5,-3,88,21,-6,5,6,7,8,9,10];
const even_1 = arr => arr.filter(x=>(x>=0 && !(x&1))).slice(0,5)
const even_2 = arr =>
{
let r = []
for(x of arr)
if (x>=0 && !(x&1)) // test2 = boolean AND on bit zero
{
r.push(x);
if (r.length >= 5) break;
}
return r
}
console.log('even 1:', even_1(myArr).join(','))
console.log('even 2:', even_2(myArr).join(','))
One suggestion:
var myArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
function even(numbersArray) {
var first5EvenNums = [];
for (const num of numbersArray) {
if (first5EvenNums.length >= 5) break;
if (num % 2 === 0) {
first5EvenNums.push(num);
}
}
return first5EvenNums;
}
console.log(even(myArr));
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div id="test"></div>
<script>
var myArr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
function even(num){
var newArr = [];
for (var i=1; i<num.length; i++){
if (num[i] % 2 === 0)
{
newArr.push(num[i]);
if(newArr.length == 5){
return newArr;
}
}
}
return newArr;
};
$("#test").text(even(myArr));
</script>
This return first 5 positive number in array.

Find the biggest number in an array by using JavaScript loops

Create a function called biggestNumberInArray().
That takes an array as a parameter and returns the biggest number.
Here is an array
const array = [-1, 0, 3, 100, 99, 2, 99]
What I try in my JavaScript code:
function biggestNumberInArray(arr) {
for (let i = 0; i < array.length; i++) {
for(let j=1;j<array.length;j++){
for(let k =2;k<array.length;k++){
if(array[i]>array[j] && array[i]>array[k]){
console.log(array[i]);
}
}
}
}
}
It returns 3 100 99.
I want to return just 100 because it is the biggest number.
Is there a better way to use loops to get the biggest value?
Using three different JavaScript loops to achieve this (for, forEach, for of, for in).
You can use three of them to accomplish it.
Some ES6 magic for you, using the spread syntax:
function biggestNumberInArray(arr) {
const max = Math.max(...arr);
return max;
}
Actually, a few people have answered this question in a more detailed fashion than I do, but I would like you to read this if you are curious about the performance between the various ways of getting the largest number in an array.
zer00ne's answer should be better for simplicity, but if you still want to follow the for-loop way, here it is:
function biggestNumberInArray (arr) {
// The largest number at first should be the first element or null for empty array
var largest = arr[0] || null;
// Current number, handled by the loop
var number = null;
for (var i = 0; i < arr.length; i++) {
// Update current number
number = arr[i];
// Compares stored largest number with current number, stores the largest one
largest = Math.max(largest, number);
}
return largest;
}
There are multiple ways.
Using Math max function
let array = [-1, 10, 30, 45, 5, 6, 89, 17];
console.log(Math.max(...array))
Using reduce
let array = [-1, 10, 30, 45, 5, 6, 89, 17];
console.log(array.reduce((element,max) => element > max ? element : max, 0));
Implement our own function
let array = [-1, 10, 30, 45, 5, 6, 89, 17];
function getMaxOutOfAnArray(array) {
let maxNumber = -Infinity;
array.forEach(number => { maxNumber = number > maxNumber ? number : maxNumber; })
console.log(maxNumber);
}
getMaxOutOfAnArray(array);
The simplest way is using Math.max.apply:
const array = [-1,0,3,100, 99, 2, 99];
function biggestNumberInArray(arr) {
return Math.max.apply(Math, arr);
}
console.log(biggestNumberInArray(array));
If you really want to use a for loop, you can do it using the technique from this answer:
const array = [-1,0,3,100, 99, 2, 99];
function biggestNumberInArray(arr) {
var m = -Infinity,
i = 0,
n = arr.length;
for (; i != n; ++i) {
if (arr[i] > m) {
m = arr[i];
}
}
return m;
}
console.log(biggestNumberInArray(array));
And you could also use reduce:
const array = [-1,0,3,100, 99, 2, 99];
function biggestNumberInArray(array) {
return array.reduce((m, c) => c > m ? c : m);
}
console.log(biggestNumberInArray(array));
I think you misunderstand how loops are used - there is no need to have three nested loops. You can iterate through the array with a single loop, keeping track of the largest number in a variable, then returning the variable at the end of the loop.
function largest(arr) {
var largest = arr[0]
arr.forEach(function(i) {
if (i > largest){
largest = i
}
}
return largest;
}
Of course you can do this much more simply:
Math.max(...arr)
but the question does ask for a for loop implementation.
This is best suited to some functional programming and using a reduce, for loops are out of favour these days.
const max = array => array && array.length ? array.reduce((max, current) => current > max ? current : max) : undefined;
console.log(max([-1, 0, 3, 100, 99, 2, 99]));
This is 70% more performant than Math.max https://jsperf.com/max-vs-reduce/1
Another visual way is to create a variable called something like maxNumber, then check every value in the array, and if it is greater than the maxNumber, then the maxNumber now = that value.
const array = [-1,0,3,100, 99, 2, 99];
function biggestNumberInArray(arr) {
let maxNumber;
for(let i = 0; i < arr.length; i++){
if(!maxNumber){ // protect against an array of values less than 0
maxNumber = arr[i]
}
if(arr[i] > maxNumber){
maxNumber = arr[i];
}
}
return maxNumber
}
console.log(biggestNumberInArray(array));
I hope this helps :)
var list = [12,34,11,10,34,68,5,6,2,2,90];
var length = list.length-1;
for(var i=0; i<length; i++){
for(j=0; j<length; j++){
if(list[j]>list[j+1]){
[ list[j] , list[j+1] ] = [ list[j+1] , list[j] ];
}
}
}
console.log(list[list.length-1]);
You Can try My codes to find the highest number form array using for loop.
function largestNumber(number){
let max = number[0];
for(let i = 0; i < number.length; i++){
let element = number[i];
if(element > max){
max = element;
}
}
return max;
}
let arrayNum= [22,25,40,60,80,100];
let result = largestNumber(arrayNum);
console.log('The Highest Number is: ',result);
let arr = [1,213,31,42,21];
let max = 0;
for(let i = 0; i < arr.length; i++) {
if(arr[i] > max) {
max = arr[i]
}
}
console.log(max)
There are multiple ways.
way - 1 | without for loop
const data = [-1, 0, 3, 100, 99, 2, 99];
// way - 1 | without for loop
const maxValue = Math.max(...data);
const maxIndex = data.indexOf(maxValue);
console.log({ maxValue, maxIndex }); // { maxValue: 100, maxIndex: 3 }
way - 2 | with for loop
const data = [-1, 0, 3, 100, 99, 2, 99];
// way - 2 | with for loop
let max = data[0];
for (let i = 0; i < data.length; i++) {
if (data[i] > max) {
max = data[i];
}
}
console.log(max); // 100
THis is the simple function to find the biggest number in array with for loop.
// Input sample data to the function
var arr = [-1, 0, 3, 100, 99, 2, 99];
// Just to show the result
console.log(findMax(arr));
// Function to find the biggest integer in array
function findMax(arr) {
// size of array
let arraySize = arr.length;
if (arraySize > 0) {
// Initialize variable with first index of array
var MaxNumber = arr[0];
for (var i = 0; i <= arraySize; i++) {
// if new number is greater than previous number
if (arr[i] > MaxNumber) {
// then assign greater number to variable
MaxNumber = arr[i];
}
}
// return biggest number
return MaxNumber;
} else {
return 0;
}
}
You can try this if you want to practice functions
const numbs = [1, 2, 4, 5, 6, 7, 8, 34];
let max = (arr) => {
let max = arr[0];
for (let i of arr) {
if (i > max) {
max = i;
}
}
return max;
};
let highestNumb = max(numbs);
console.log(highestNumb);
const array = [-1, 0, 3, 100, 99, 2, 99]
let longest = Math.max(...array);
what about this
const array = [1, 32, 3, 44, 5, 6]
console.time("method-test")
var largestNum = array[0]
for(var i = 1; i < array.length; i++) {
largestNum = largestNum > array[i] ? largestNum : array[i]
}
console.log(largestNum)
console.timeEnd("method-test")

Javascript check random number duplicated

I have this random number from 1 to 10 and an array from 1 to 10 but missing an 8 and 2. I want JS to figure that out and push either 8 or 2 into the array.
Javascript:
var arr = [1, 3, 5, 6, 9, 4, 7, 10];
var num = Math.floor((Math.random() * 10) + 1);
for (i = 0; i < arr.length; i++) {
while (num == arr[i]) {
num = Math.floor((Math.random() * 10) + 1);
}
arr.push(num);
Unfortunately, it does make a new number but duplicate with the previous compared number. Please help.
You can look for the missing numbers and random an element in that array:
var arr = [1, 3, 5, 6, 9, 4, 7, 10];
// Build array of missing numbers
var missingNumbers = [];
for (var i = 1; i <= 10; i++) {
if (arr.indexOf(i) < 0) {
missingNumbers.push(i);
}
}
// Pick one of them at random
var randomNumber = missingNumbers[Math.floor(Math.random() * missingNumbers.length)];
// Push it into the array
arr.push(randomNumber);
// Show results
console.log(randomNumber);
console.log(arr);
.as-console-wrapper {
max-height: 100% !important;
}
You can try this as well
var arr =[1,3,5,6,9,4,7,10];
var num=parseInt((Math.random()*10)+1)
while(arr.indexOf(num)!=-1){
num=parseInt((Math.random()*10)+1);
}
arr.push(num)
console.log(arr)
In above example I am taking a number randomly and checking in loop that, The number is present in the array or not
while(arr.indexOf(num)!=-1)
if number will not be there then inside loop again I am generating again a number and checking. When I got a number which is not present then the loop body will not be execute and I am pushing that number in array.
As you said that only one number you want either 8 or 2
I figured it out.
var arr = [1, 3, 5, 6, 9, 4, 7, 10];
var num = Math.floor((Math.random() * 10) + 1);
for (i = 0; i < arr.length; i++) {
while (num == arr[i]) {
num = Math.floor((Math.random() * 10) + 1); }
arr.push(num);}
basically if it is duplicated, I simply put i=0 to loop again until it is unique. It might not be efficient.
The function find returns an array filled with all the duplicated numbers. It's optimized
function find(a, b) {
let result = [];
for(let i=0; i<a.length; i++) {
let num = NumbersList[i];
if(b[num] == 0) {
b[num] = 1;
} else if (b[num] == 1) {
b[num] = 2;
result.push(num);
}
}
console.log("Duplicated numbers: " +result.length);
return result;
}
var NumbersList = new Array();
var value = 30000;
for(let i=0; i<value; i++) {
let x = Math.floor((Math.random() * value) + 1);
NumbersList.push(x);
}
var map = new Array(NumbersList.length).fill(0);
var t0 = performance.now();
find(NumbersList, map);
var t1 = performance.now();
console.log("Call to find with " +value+ " numbers took " + (t1 - t0) + " milliseconds.");

The sum of a range using Javascript

I wish to execute a program with output as :
console.log(range(1, 10));
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(range(5, 2, -1));
// → [5, 4, 3, 2]
console.log(sum(range(1, 10)));
// → 55
I am getting an error for array.length.Please find the code below:
var array = [];
function range (arr){
var lower = Math.min(arr[0],arr[1]);
var upper = Math.max(arr[0],arr[1]);
for (var i=lower;i<=upper;i++){
array.push(i);
}
}
function sum(array){
for(var i=0;i < array.length;i++){
var total = total+array[i];
}
}
console.log(sum(range(1, 10)));
I am at begineers level, please do help.
Thanks.
You have a few problems here:
1.) You aren't returning anything in your range function. You need to return the filled array.
2.) You aren't passing the array correctly in the sum function call.
3.) You aren't returning anything in your sum function call.
Without returning any values, you aren't letting your code blocks work with eachother
var array = [];
function range (arr){
var lower = Math.min(arr[0],arr[1]);
var upper = Math.max(arr[0],arr[1]);
for (var i=lower;i<=upper;i++){
array.push(i);
}
return array; // return the array to be used in the sum function
}
function sum(array){
var total = 0; // need to create a variable outside the loop scope
for(var i in array){
total = total+array[i];
}
return total;
}
console.log(sum(range([1,10]))); // pass the array correctly
Note that you need to set the total variable outside the scope of the for-loop within the sum function. That way you can return the final value. Otherwise, it would return undefined.
See the fiddle: https://jsfiddle.net/udyhb95a/
You need to pass an array when calling the range function you defined range([1, 10])
You need to rewrite your sum function
As a side note, there are more efficient ways to compute the sum of a range of elements without iterating on them.
function sum_of_range(start, end) {
return end * (end + 1) / 2 - start * (start + 1) / 2;
}
Edit:
Here is a working sum function
function sum(array) {
var accumulator = 0;
for (var i = 0; i < array.length; ++i)
accumulator += array[i];
return accumulator;
}
Here you declare a function with one parameter as an array
function range (arr){
...
But here you call a function with two arguments as numbers
console.log(range(1, 10));
Use this call function
console.log(range([1, 10]));
And don't use for..in for arrays
for(var i in array){ it doesn't work as you expect
Use forEach function or plan for loop
Also you have some error in sum function
See working example below:
function range(arr) {
var array = [];
var lower = Math.min(arr[0], arr[1]);
var upper = Math.max(arr[0], arr[1]);
for (var i = lower; i <= upper; i++) {
array.push(i);
}
return array;
}
function sum(array) {
var total = 0;
for (var i = 0; i < array.length; i++) {
total = total + array[i];
}
return total;
}
document.write('range ' + range([1, 10]) + '<br>');
document.write('sum ' + sum(range([1, 10])));
You need to modify sum & range function
function range (){
var array = [];
var lower = Math.min.apply(null, arguments);
var upper = Math.max.apply(null, arguments);
for (var i=lower;i<=upper;i++){
array.push(i);
}
return array;
}
function sum(array){
return array.reduce((x,y)=>x+y,0);
}
console.log(range(1, 10));
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(range(5, 2, -1)); //if we are considering min & max from params
// [-1, 0, 1, 2, 3, 4, 5]
console.log(sum(range(1, 10)));
// 55
Hello Dear check it now.
var array = [];
function range(arr, arr1) {
var lower = Math.min(arr);
var upper = Math.max(arr1);
for (var i = lower; i <= upper; i++) {
array.push(i);
}
}
function sum() {
var total = 0;
for (var i = 0; i < array.length; i++) {
total = total + array[i];
}
return total;
}
console.log(sum(range(1, 10)));
This is the correct answer to the problem at the end of the data structures chapter within Eloquent JavaScript
function range(start, end, step) {
let arr = []; //declare an empty array
var step = step || 1;//tests to see if step was supplied, otherwise it's 1
if(start < end)
{
for(let i = start; i <= end; i += step)
{
arr.push(i);
}
}
else
{
for(let i = start; i >= end; i += step)
{
arr.push(i);
}
}
return arr;
}
function sum(array) {
let total = 0;
for(let i = 0; i < array.length; i++)
{
total += array[i];
}
return total;
}
console.log(range(1, 10));
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(range(5, 2, -1));
// → [5, 4, 3, 2]
console.log(sum(range(1,10)));
// → 55
This solution takes into account of entering a step that isn't expected to be positive/negative, i.e range from 1 to 5, we would expect step to be positive, but if the user somehow entered a negative step then an empty array would occur.
The browser actually hangs for the opposite, if the array is expected to decrease, but the step sizes are > 0.
'use strict';
function range(start, end, step = 1){
let output = [];
if (start > end){
// Sanity check, all steps if expected to go down should be negative
if (step > 0){
step = -step;
}
for (;start >= end; start += step){
console.log(start);
output.push(start);
}
}
else{
// Likewise, as all steps should be positive
if (step < 0){
step = -step;
}
for (;start <= end; start += step){
output.push(start);
}
}
return output;
}
function sum(arr){
let output = 0;
for (let i of arr){
output += i;
}
return output;
}
console.log(range(1, 5, 1));
// → [1, 2, 3, 4, 5]
console.log(range(5, 1, -1));
// → [5, 4, 3, 2, 1]
// Notice this one step is a positive, but this is handled (original solution returned empty array)
console.log(range(5, 1, 1));
// → [5, 4, 3, 2, 1]
console.log(sum(range(1,10)));
// → 55
An improvement onto this is to use the reduce function for an array to sum instead of a for loop, i.e:
function sum(array){
return array.reduce((x,y)=>x+y,0);
}
For people finding this later on as I did, here is a way to write the range function so you can pass the input as written in the original question:
console.log(sum(range(1, 10)));
…and a cleaned up sum function similar to the one in A. Sharma's answer:
function range(lower, upper) {
let array = []
for (let i = lower; i <= upper; i++) {
array.push(i);
}
return array;
}
function sum(array) {
let total = 0;
for (let i in array) {
total = total + array[i];
}
return total;
}
console.log(sum(range(1, 10)));
Also worth mentioning:
The use of reduce in JagsSparrow's answer, which is elegant, while not entirely obvious and newcomer friendly as Mathias Vonende pointed out.
Negative step tolerant versions in answers from Jimmy Wei and user3225968.
This is the best solution I've got
function range(x,y){
var arr = [];
for(x;x<=y;x++){
arr.push(x);
};
return arr;
};
function sum(array){
return array.reduce((a,b) => a + b, 0);
};
console.log(sum(range(1,10)));
This answer is quite late but I am learning these things now and want to share my solution. I have not seen this solution provided for the specific question "Sum of a range in Javascript" so I wanted to share it. What I have done here is made use of the pop method for the array which allowed me not to specifically pass an array argument to the range function but to provide a solution to the argument in the way it was originally presented in the question.
var result = [];
var counter = 0;
function range(start, end) {
for (let i = start; i <= end; i++) {
result.push(i);
}
return result;
}
function sum(array) {
for (let i = 0; i < result.length; i++) {
counter += result.pop(i);
}
return counter;
}
console.log(range(1, 10));
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(sum(range(1, 10)));
// → 55
This can be accomplished very easily and efficiently without any globally scoped vars.
It's not clear in the original question what behavior should be applied to the -1 argument. It seems to be an indicator to reverse the range. In the below example, I've used a boolean to check this argument. A value of -1 would actually be the same as not providing a third argument. To reverse the range, pass in any truthy value.
function range(from, to, reverse) {
// Make sure our inputs are actually numbers
if (Number(from) != from || Number(to) != to) {
throw new TypeError("range() expects a Number as both it's first and second argument");
}
let o = []; // initialize our output array
// get the lowest value argument as our starting index
let i = Math.min(from, to);
// get the highest value argument as our ending index
let x = Math.max(from, to);
// push i onto our output array and then increment until i == x
while (i <= x) { o.push(i); i++; }
// reverse the range order if necessary
if (reverse) { o = o.reverse(); }
// return our output array
return o;
}
Then we can use Array.reduce to iterate through the range array and add each value (b) to the one before it (a) with the addition assignment operator (+=).
function sum(range) {
if (!(range instanceof Array)) {
throw new TypeError("sum() expects an Array as it's only argument");
} return range.reduce((a,b) => a+=b);
}
Testing it:
let a = range(1,10);
let b = range(5,2);
let c = range(5,2,true);
let d = range(3,-1);
let e = range(10,10);
console.log(a); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
console.log(b); // [ 2, 3, 4, 5 ]
console.log(c); // [ 5, 4, 3, 2 ]
console.log(d); // [ -1, 0, 1, 2, 3 ]
console.log(e); // [ 10 ]
console.log(range('test', 10)); // TypeError
console.log(range(1, 'test')); // TypeError
console.log(sum(a)); // 55
console.log(sum(b)); // 14
console.log(sum(c)); // 14
console.log(sum(d)); // 5
console.log(sum(e)); // 10
console.log(sum('test')); // TypeError
here my answer, I'd glad if you give me feedback about this solution.
let arr = [];
function range(x, y) {
for (let i = x; i <= y; i++) {
arr.push(i);
}
return arr;
}
function sum(array) {
const many = array.reduce((total, number) => {
return total + number;
}, 0);
return many;
}
console.log(sum(range(1, 10)));

Categories

Resources