How to find the sum of a series of repeated numbers? - javascript

The question I'm trying to solve is:
Find the sum of the series (3 + 33 + 333 + 3333 + ... + n), to n terms, where n is an input provided by the user (using prompt).
Example: Given 5. So the series will become (3 + 33 + 333 + 3333 + 33333).
Expected output: 37035
This is my code:
const number = 5;
let sum = 3;
let add;
for (i = 0; i <= number; i++){
add = "";
for (j = 1; j <= i; j++) {
add += 3;
sum = add * 10 + 3
}
sum = sum + *5;
}
console.log(sum);
It's not giving me the desired outcome (which is obviously the issue I'm running into). I haven't used prompt yet because I don't know how to implement it. Could someone please help me?

You don't need a nested loop. Use just a single loop, and inside, increment add based on the power of 10 of the current iteration, and add the result to the sum:
const count = 3
let sum = 0;
let add = 0;
for (i = 0; i < count; i++){
add += 3 * 10 ** i;
sum += add;
}
console.log(sum);

You can use the padEnd() method to add padding at end of a string. Please check the snippet for the solution by using the padEnd() method. In this way, you can avoid string concatenation or extra loop.
Please check the link to know more about the method padEnd
const count = 5;
let number = 3;
let sum = 0;
for(i = 1; i <= count; i++) {
sum += Number(number.toString().padEnd(i, number.toString()));
console.log(i.toString() + ". " + number.toString().padEnd(i, number.toString()));
}
console.log("Sum: " + sum);

Here is what you ask i think, so i turn to string the iteration number in order to add it to an array and then reduce javascript property to sum all it's elements!!
const number = 5;
let sum = 3;
let added = '';
let add = [];
sum = sum.toString();
added = sum;
for(let i = 0; i<number; i++){
add.push(added);
added += sum;
}
let result = add.reduce((ant,sum)=>{
return parseInt(ant) + parseInt(sum);
});
console.log(result);
Edit: for the prompt question here's a link that i hope it helps you!
You can use it this way: const number = prompt("enter how much numbers");

Here's how you can do it:
const sumNum = 3;
const number = Number(prompt('Please enter a number for repeatitions: '));
let sum = '';
for (let i = 0; i < number; i++) {
for (let j = 0; j <= i; j++) {
sum += sumNum;
}
if (i < number) sum += '+';
}
let total = 0;
sum = sum.split('+');
sum.pop(); //to remove last empty field
while (sum.length) {
total += Number.parseFloat(sum.shift());
}
console.log(total);

To repeat a number:
const x = 3;
Number(`${x}`.repeat(1)); //=> 3
Number(`${x}`.repeat(2)); //=> 33
Number(`${x}`.repeat(3)); //=> 333
Number(`${x}`.repeat(4)); //=> 3333
Number(`${x}`.repeat(5)); //=> 33333
So from such array [3, 3, 3, 3, 3] we can do:
[3, 3, 3, 3, 3].map((x, i) => Number(`${x}`.repeat(i+1)));
//=> [3, 33, 333, 3333, 33333]
But we don't need to manually fill an array with n identical numbers:
const n = 5;
const x = 3;
Array(n).fill(x);
//=> [3, 3, 3, 3, 3]
Or:
Array.from(Array(n), () => x);
//=> [3, 3, 3, 3, 3]
But obviously if we can apply a function on each item we may as well produce the full series:
Array.from(Array(n), (_, i) => Number(`${x}`.repeat(i+1)));
//=> [3, 33, 333, 3333, 33333]
Finally we can reduce the series to the sum of all numbers:
[3, 33, 333, 3333, 33333].reduce((tot, x) => tot + x, 0);
//=> 37035
So altogether we have:
const n = 5; // use prompt() but don't forget to coerce the result into a number
const x = 3;
Array.from(Array(n), (_, i) => Number(`${x}`.repeat(i+1)))
.reduce((tot, x) => tot + x, 0);
If you don't need to produce a series then a recursive function is perhaps simpler:
const sum_series =
(x, n, tot=0) =>
n === 0
? tot
: sum_series(x, n-1, tot+=Number(`${x}`.repeat(n)))
sum_series(3, 5);
//=> 37035

Related

array help. How to multiply arrays by itself, without the first element in one, and without the last element in the other

my array from user input: [1,2,3,4]
what I want:
[1,2,3]*[2,3,4]
(1*2) + (2*3) + (3*4) = 20
what I have so far:
var array = [];
var number= document.getElementById("number").value; //this is where user inputs the number for my array
var sum = 0;
for (var i = 0; i< number.length; i++){
array.push(parseInt(number[i]));
var first= number[i-1];
var second = number[i+1];
sum += (first*second);
}
console.log(sum);
that is my solution with reduce method of array
[1, 2, 3, 4].reduce((a, c, i, s) => (s[i + 1] ? c * s[i + 1] + a : a), 0);
No need for an array for this.
In the following pattern: (1*2) + (2*3) + (3*4) you can see how this can occur using for loop without array.
Following works:
var number= parseInt(document.getElementById("number").value); //this is where user inputs the number for my array
var sum=0;
for (var i = 1; i< number; i++){
sum += i*(i+1);
}
console.log(sum);
You could use slice to get subsets of the arrays and then use reduce to create the sum like this:
const arr = [1,2,3,4]
const first = arr.slice(0, -1)
const last = arr.slice(1, arr.length)
const result = first.reduce((acc, num, idx) => acc + num * last[idx], 0)
console.log(result)

How do I divide the sum with 2 after a loop

How do I divide the sum with 2 after a loop, so I get the value 38? I want to print out the answer in an alert box.
My Javascript code:
var nums = ['1','75'];
var sum = 0;
for(var i=0; i < nums.length; i++){
sum += parseInt(nums[i]);
}
alert(sum);
Or if I have the values 1, 2, 3, 4, I want to get the sum (in this case 10) in the loop and divide it with 2 and print out it in an alert box.
//variable declaration and loop above
alert(sum/2);
You need to divide by 2 then...
var nums = ['1','75'];
var sum = 0;
for(var i=0; i < nums.length; i++){
sum += parseInt(nums[i]);
}
sum /= 2;
alert(sum);
var nums = ['1','75'];
let sumDiv2 = (nums)=> {
var sum = 0;
for(var i=0; i < nums.length; i++){
sum += Number(nums[i]);
}
return sum
}
alert(sumDiv2(nums)/2);
var nums = ['1','75'];
var sum = 0;
for(var i=0; i < nums.length; i++){
sum += parseInt(nums[i]);
}
alert(sum/2);
This isn't complex to solve.
Using array reduce method you can do like below
var arr = ["1", "67"];
var divide = arr.reduce(function (acc, ele) {
return acc += +ele; // To convert element from string to array use +
}, 0) / 2;
console.log(divide);
You can do it on 1 line.
var nums = ['1','2', '3', '4'];
var result = nums.reduce((el, acc) => parseInt(el) + parseInt(acc), 0) / 2;
console.log(result);
var nums = ['1','75'];
var sum = 0;
for(var i=0; i < nums.length; i++){
sum += parseInt(nums[i]);
}
alert(sum/2);
You can try this without any loop. Short, simple and stylish:
var arr=['1', '75'],
sum_2=arr.reduce(function(a,b){return a*1+b*1;},0)/2;
alert(sum_2);
console.log(['1','2'].reduce((p,c) => +p + +c, 0) / 2)
// ^ ^ ^ ^ ^
// | | | | |
// "p" as "previous"_| | |____| |_first "p" value
// | |
// "c" as "current"_| |_convert strings to integers
Run the snippet; what happens:
.reduce() starts on the ['1','2']
In the first call to the inner function ((p,c) => +p + +c) the value of p(revious) is 0, as the second argument passed to the .reduce(), and value of the c(urrent) is '1', the first array element; the 0 + +'1' executes, resulting in 1
In the second call to the inner function the value of p is 1 - from previous execution, and the value of c is '2'; the 1 + +'2' executes, resulting in 3
As here are no more items in the array, the final result of .reduce() call gives as 3, which is then divided by 2 in 3 / 2, resulting in 1.5
Unary operator + preceding string (+'1', '+'2'`) converts the string into integers.
You could divide the sum by 2.
BTW, while you have already integer values as strings, you could use an unary plus + for a conversion to number.
sum += +nums[i];
// ^
var nums = ['1', '75'],
sum = 0,
i;
for (i = 0; i < nums.length; i++) {
sum += +nums[i];
}
alert(sum / 2);

Loop from 0 to a number and loop through all numbers in array (javascript)

Here is the idea:
var a = [4, 5, 6];
for (var m = 0; m < a[0]; m++)
for (var n = 0; n < a[1]; n++)
for (var p = 0; p < a[2]; p++)
console.log(`${m} + ${n} + ${p} = ${m+n+p}`);
Live Copy:
// This just tells the Stack Snippets in-snippet console not
// to throw away entries once it reaches a max (the default max
// is just the last 50 logs).
console.config({maxEntries: Infinity});
var a = [4, 5, 6];
for (var m = 0; m < a[0]; m++)
for (var n = 0; n < a[1]; n++)
for (var p = 0; p < a[2]; p++)
console.log(`${m} + ${n} + ${p} = ${m+n+p}`);
/* This just makes the console take up the full output area */
.as-console-wrapper {
max-height: 100% !important;
}
The code would get longer if the array a has more indexes. Could the code be shorten using Array.map or filter or a function?
We can do this without taking up massive amounts of memory, and fairly simply, by using recursion:
const process = (array, n, numbers) => {
if (n < array.length) {
// Not done yet, recurse once for each number at this level
const max = array[n];
for (let i = 0; i < max; ++i) {
process(array, n + 1, [...numbers, i]);
}
} else {
// Done with this level, process the numbers we got
console.log(`${numbers.join(" + ")} = ${numbers.reduce((s, e) => s + e)}`);
}
}
process([4, 5, 6], 0, []);
Live Copy, with cross-checking against your results to ensure the above does the same thing:
// This just tells the Stack Snippets in-snippet console not
// to throw away entries once it reaches a max (the default max
// is just the last 50 logs).
console.config({maxEntries: Infinity});
function thisSolution() {
const results = [];
const process = (array, n, numbers) => {
if (n < array.length) {
// Not done yet, recurse once for each number at this level
const max = array[n];
for (let i = 0; i < max; ++i) {
process(array, n + 1, [...numbers, i]);
}
} else {
// Done with this level, process the numbers we got
const result = numbers.reduce((s, e) => s + e);
results.push(result);
console.log(`${numbers.join(" + ")} = ${result}`);
}
}
process([4, 5, 6], 0, []);
return results;
}
function yourSolution() {
const results = [];
var a = [4, 5, 6];
for (var m = 0; m < a[0]; m++)
for (var n = 0; n < a[1]; n++)
for (var p = 0; p < a[2]; p++)
results.push(m + n + p);
return results;
}
const thisResult = thisSolution();
const yourResult = yourSolution();
if (thisResult.some((entry, index) => entry !== yourResult[index])) {
console.log("WRONG");
} else {
console.log("RIGHT");
}
/* This just makes the console take up the full output area */
.as-console-wrapper {
max-height: 100% !important;
}
This never goes deep into the stack (a.length + 1 stack frames, to be precise, so four in the example case). It builds up a number of temporary arrays (145 in the example case) that max out at a.length entries, releasing them as soon as they aren't needed anymore (a max of four are retained at any given time). Here's the quick and dirty metrics on that:
let maxStack = 0;
let stack = 0;
let totalArrays = 0;
let maxArrays = 0;
let arrays = 0;
// A wrapper for counting stack frames
const process = (...args) => {
if (++stack > maxStack) {
maxStack = stack;
}
const result = process2(...args);
--stack;
return result;
};
const process2 = (array, n, numbers) => {
if (n < array.length) {
// Not done yet, recurse once for each number at this level
const max = array[n];
for (let i = 0; i < max; ++i) {
++totalArrays;
if (++arrays > maxArrays) {
maxArrays = arrays;
}
process(array, n + 1, [...numbers, i]);
--arrays;
}
} else {
// Done with this level, process the numbers we got
//console.log(`${numbers.join(" + ")} = ${numbers.reduce((s, e) => s + e)}`);
}
}
process([4, 5, 6], 0, []);
++maxArrays; // To account for the one in the last argument above
++totalArrays; // "
console.log(`Max stack: ${maxStack}, max arrays: ${maxArrays}, total arrays: ${totalArrays}`);
It's easier if you break it down. First, you need to create a series per every element of your array.
let series = num => Array.from({ length: num + 1 }, (n, i) => i); //creates an array with nums from 0 to num.
That's the first part of your question. Then you need to do a cross product of your series.
Basically for two series [1, 2, 3] and [1, 2, 3, 4] you'll end up with a set of 12 elements:
[2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7]
And for that you could do:
let crossProduct = (a1, a2) => Array.prototype.concat.call(...a1.map(n1 => a2.map(n2 => n1 + n2)));
Now all you need to do is have a crossProduct for every series.
let final = numbers.map(series).reduce(crossProduct);
And there you have it:
let numbers = [4, 5, 6];
let series = num => Array.from({ length: num + 1 }, (n, i) => i);
let crossProduct = (a1, a2) => Array.prototype.concat.call(...a1.map(n1 => a2.map(n2 => n1 + n2)));
let final = numbers.map(series).reduce(crossProduct);
console.log(final);
Edit: If it's from 0 to the number before (e.g. 4 is [0, 1, 2, 3]) then just take the + 1 in the series function.
2nd Edit: Less objects created for your crossProduct:
let crossProduct = (a1, a2) => {
let resultingSet = [];
for(let i = 0; i < a1.length; i++)
for(let j = 0; j < a2.length; j++)
resultingSet.push(a1[i] + a2[j]);
return resultingSet;
} //only one array is created
And if you want to avoid having the series on memory all the time:
let numbers = [4, 5, 6];
let series = function* (num){
for(let i = 0; i < num; i++){
yield i;
}
}
let crossProduct = (set, num) => {
let resultingSet = [];
for(let i = 0; i < set.length; i++){
for(let j of series(num)){
resultingSet.push(set[i] + j);
}
}
return resultingSet;
}
let final = numbers.reduce(crossProduct, [0]);
console.log(final);
Another solution that doesn't consume alot of memory and fairly efficient is by using an array that represnt the value of the indexes and update it each iteration.
first you create an array that represent in each element the amount of iterations you need to run in order to update the indexes respectively for example for this array [1, 2, 3 ,4 ,5] you will get:
[280, 140, 20, 5, 1] this means that index[0] will be updated each 280 iterations, index[1] will be updated each 140 iterations and so on..
totally you will run arr[n] * arr[n-1] * arr[n-2] * .... * arr[0] iterations as you did with ordinary nested for loop.
var arr = [1, 2, 7, 4, 5];
var indexes = Array.from({length: arr.length}, () => 0);
iterationsPerElement = arr.map((_, i) => arr.slice(i+1).reduce((acc, elem) => acc * elem, 1));
var totalIterations = iterationsPerElement[0] * arr[0];
for(var iteration = 1; iteration <= totalIterations; iteration++) {
// sum those indexes
console.log(`sum = ${indexes.reduce((acc, index) => acc + index, 0)}`);
// update indexes
for(i = 0; i < indexes.length; i++) {
if(iteration % iterationsPerElement[i] == 0) {
indexes[i]++;
// empty the indexes on the right
for(var j=i+1; j <indexes.length; j++) {
indexes[j] = 0;
}
}
}
}

JavaScript: calculate the average of an odd number

I want to count the average value of the odd numbers from a list of numbers. I have a starting code to count the average, but I don't know how can I choose only the odd numbers from the list?
Here is my code:
var numberArray = [1,2,3,4,5,6], thisTotal=0,thisAverage=0;
for (var i=0; i<numberArray.length; i++) {
thisTotal += numberArray[i];
}
thisAverage = (thisTotal/numberArray.length);
alert(thisAverage)
You can use a filter function to return only the odd numbers:
var oddArray = numberArray.filter(function(val) {
return val % 2 !== 0;
});
Full example:
var numberArray = [1, 2, 3, 4, 5, 6];
var thisTotal = 0;
var thisAverage = 0;
var oddArray = numberArray.filter(function(val) {
return val % 2 !== 0;
});
console.log(oddArray); // [1, 3, 5]
var thisTotal = oddArray.reduce(function(accumulator, currentValue) { return accumulator + currentValue;
});
console.log(thisTotal); // 1 + 3 + 5 => 9
var thisAverage = thisTotal / oddArray.length;
console.log(thisAverage); // 9 / 3 => 3
var numberArray=[1,2,3,4,5,6], thisAverage=0,oddlength=0;
for(var i=0;i<numberArray.length;i++)
{
if(numberArray[i]%2!==0){
thisAverage+=numberArray[i];
oddlength++;
}
}
thisAverage=(thisAverage/oddlength);
alert(thisAverage)
Well, you can get what you want by this.
var numberArray=[1,2,3,4,5,6], thisTotal=0,thisAverage=0;
for(var i=0; i < 3; i++) {
thisTotal += numberArray[i * 2];
thisAverage= (thisTotal/numberArray.length);
}
console.log(thisAverage);
or if you want general solution, use this.
var numberArray=[1,2,3,4,5,6,7,8,...on and on], thisTotal=0,thisAverage=0;
for(var i=0; i < Math.ceil(numberArray.length() / 2); i++) {
thisTotal += numberArray[i * 2];
thisAverage= (thisTotal/numberArray.length);
}
console.log(thisAverage);
hope my code be helpful :)
You can use the function reduce to add and count.
var numberArray = [1, 2, 3, 4, 5, 6],
result = numberArray.reduce((a, n) => {
if (n % 2 !== 0) {
a.sum += n;
a.count++;
}
return a;
}, {sum: 0, count: 0}),
average = result.sum / result.count;
console.log(average);
Assuming the numbers are in an array, you can do this:
var numbers = [1, 2, 3, 4, 5, 6];
var info = numbers.filter(function(n) { return n % 2 !== 0})
.reduce(function(acc, item) {
return {sum: acc.sum + item, count: acc.count + 1}
}, {sum: 0, count: 0});
var avg = info.sum / info.count;
This example uses filter and reduce methods, which are declarative and more clear.
filter returns a new array with the items for which the function returns true, and then reduce, for each item, updates an 'accumulator'. The accumulator can be anything, and in this case is an object with the sum of the numbers and their count. For each item, we add add the current number to the sum property and add 1 to count. Finally, we just devide sum by count and done.
var acc = 0, oddCount = 0;
for(var i = 0; i < numberArray.length; i++) {
if(numberArray[i] % 2 !== 0) {
acc += numberArray[i];
oddCount++;
}
}
return acc / oddCount;
You can create a new array and store odd values in that array and after that you can apply your logic to that array.
var a=[1,2,3,4,5,6,10,11];
var ar=[];
for (var i = 0; i < a.length; i++) {
if(a[i] % 2 !== 0) {
ar.push(a[i]);
}
}
console.log(ar);
var numberArray=[1,2,3,4,5,6,7,8];
var count = 0;
var result = 0;
for (let i = 0; i <= (numberArray.length-1); i++)
{
if (numberArray[i] % 2 != 0)
{
result += numberArray[i];
count++;
}
}
alert(result / count);

Project Euler #2, Fibonacci, javascript attemp

I was attempting to do some problems on project euler. For the second one I did get the correct answer but I cheated a bit.
Heres the problem:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
Heres my code:
var fib = [1,2];
var i = 0;
var sum = 0;
while (fib[0] + fib[1] < 4000000){
i = fib[0] + fib[1];
console.log(i); //just to show myself the number came out correctly.
fib[0] = fib[1];
fib[1] = i;
if (i % 2 === 0){
sum += i;
}
}
console.log(sum + 2);
I added sum by 2 because I can't figure a way for the code to add the initial fib[1], which is a even number itself. Thanks.
Simple solution
var sum = 0;
var term1 = 1;
var term2 = 1;
while (term2 < 4000000) {
term2 = term1 + term2;
term1 = term2 - term1;
sum += term2 % 2 === 0 ? term2 : 0;
}
console.log(sum);
If you start with [1, 2], the first fibonacci number that you get is 3.
In your loop you have:
i = 1+2 = 3
i = 2+3 = 5
So simply start with [0, 1]:
i = 0+1 = 1
i = 1+1 = 2
i = 1+2 = 3
Fixed code:
var fib = [0,1];
var i = 0;
var sum = 0;
while (fib[0]+fib[1] < 4000000){
i= fib[0]+fib[1];
fib[0]=fib[1];
fib[1]=i;
if(i%2 === 0){
sum += i;
}
}
console.log(sum);
for (var sum = 0, i = 0, j = 0, k = 1; 4e6 > j + k; i++) i = j + k, j = k, k = i, sum += 0 == i % 2 ? i : 0;
It could help you.
let num1 = 0;
let num2 = 1;
let total = 0;
let num3 = 0;
let i = 0;
while(num1 + num2 < 4000000){
num3 = num1 + num2;
num1 = num2; //as loop keep going is changes the position of number
num2 = num3; //as loop keep going is changes the position of number
if(num3 % 2 === 0 ){ // check weather number is even or not
total += num3; //every even number gets added
}
i++
}
console.log(total);
function firstNofFibonacci(n)
{
let fibArr = [];
for (let i = 0; i < n; i++) {
if (fibArr.length > 1) {
fibArr.push(fibArr[fibArr.length - 1] +
fibArr[fibArr.length - 2]);
} else {
fibArr.push(i);
};
};
return fibArr;
}
This is my code for the same problem. It is not perfect but I hope this will help someone who reads this.
function fibonacci(stop) {
var a = 1, b = 0, c, storage = []
for (var i = 0; a < stop; i++) {
c = a
a = a + b
b = c
if (b%2 == 0) {
let even = b
storage.unshift(even)
}
}
var all = storage.reduce((x, y) => {return x + y}, 0)
console.log(all)
}
fibonacci(4000000); // 4613732
well, what I did here is that I create a function with the stop parameter (where you tell the function to stop) and then I create variables to make the Fibonacci sequence and create a variable where I can store the even values. Then push all the even values in the array, at the end of the function I add all the values in a variable and console.log() the value
If you have suggestions or comments all ears :)

Categories

Resources