Multiplying array numbers sequentially - javascript

The best and the easiest way to multiply array numbers sequentially
I have got an array with some values:
const arr = [1, 5, 12, 3, 83, 5];
Now I want to get the product of all values from arr. It should works like this: 1 * 5 * 12 * 3 * 83 * 5
I have tried with this code:
const arr = [1, 5, 12, 3, 83, 5];
multiply(arr);
function multiply(arr) {
for(i = 0; i < arr.length; i++) {
product = array[i] * array[i];
console.log(product);
}
}
This code above works like this: 1 * 1, 5 * 5, 12 * 12, 3 * 3, 83 * 83, 5 * 5 and that is not result that I need. I think I know why it works like this but I'm not sure how to write code that I need.
So what's the best option for this kind of tasks?
Edit.
For non-experienced people looking here in future this is the best option that we've found:
Leo Martin answer:
const array = [1, 5, 12, 3, 83, 5];
console.log(multiply(array)); // we log function return value
function multiply(array) {
let score = array[0];
for (i = 1; i < array.length; i++) {
score = score * array[i];
}
return score;
}
and also the shorter version:
By the way, you could use Array.reduce:
const array = [1, 5, 12, 3, 83, 5];
const result = array.reduce((acc, value, index) => {
if (index === 0) return value;
acc = acc * value;
return acc;
}, 0);
console.log(result);

Just move console.log outside for body:
const array = [1, 5, 12, 3, 83, 5];
console.log(multiply(array)); // we log function return value
function multiply(array) {
let score = array[0];
for (i = 1; i < array.length; i++) {
score = score * array[i];
}
return score;
}
By the way, you could use Array.reduce:
const array = [1, 5, 12, 3, 83, 5];
const result = array.reduce((acc, value, index) => {
if (index === 0) return value;
acc = acc * value;
return acc;
}, 0);
console.log(result);

You can use reduce method to multiply all numbers
const array = [1, 5, 12, 3, 83, 5];
const total = array.reduce((total,num) => total * num, 1);
console.log(total)

Corrected your program.
const array = [1, 5, 12, 3, 83, 5];
multiply(array);
function multiply(array) {
var score = 1;
for(i = 0; i < array.length; i++) {
score = score * array[i];
}
console.log(score);
}

Hope the solution is self explanatory. Loop through array. Multiply each product and store the result in the same variable.
const array = [1, 5, 12, 3, 83, 5];
multiply(array);
function multiply(array) {
let product = 1;
for(i = 0; i < array.length; i++) {
product *= array[i];
}
console.log(product);
}

const array = [1, 5, 12, 3, 83, 5];
multiply(array);
function multiply(array) {
var score = array[0];
for(i = 1; i < array.length; i++) {
score = score * array[i];
}
console.log(score);
}

var array = [1, 5, 12, 3, 83, 5];
var result = array.reduce(function(a, b) {
return a * b;
});
console.log(result);

const array = [1, 5, 12, 3, 83, 5];
multiply(array);
function multiply(array) {
for(i = 0; i < array.length-1; i++) {
score = array[i] * array[i+1];
console.log(score);
}
}

For the calculation of the final result of multiply:
const array = [1, 5, 12, 3, 83, 5];
multiply(array);
function multiply(array) {
score = 1;
for(i = 0; i < array.length; i++) {
score = score * array[ i ];
}
console.log(score); // expected result: 74700
}
Are you asking for a textual representation of the calculations? If so, use this:
const array = [1, 5, 12, 3, 83, 5];
multiply(array);
function multiply(array) {
score = '';
for(i = 0; i < array.length; i++) {
score += array[i].toString();
if ( i < array.length -1 ) score += '*';
}
console.log(score); // expected result: '1*5*12*3*83*5'
}
This should start to put you on the right way, hope it helps.

score = array[i] * array[i]; you are trying to multiply exact exp-rations.
const array = [1, 5, 12, 3, 83, 5];
its like: 1*1, 5*5
you can multiply array[i] * i
another approach might be an array function.
const array = [1, 5, 12, 3, 83, 5];
multiply(array);
function multiply(array) {
let product = 1;
`enter code here`for(i = 0; i < array.length; i++) {
product *= array[i];
}
console.log(product);
}
let multiArray = array.map((num, index) => num *index)
console.log(multiArray)
for more info:https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Global_Objects/Array/map.

Related

How would I write a function that returns all combinations of 3 numbers that equal the target sum WITH RECURSION

What I have so far
let threeSum = (array, targetSum) => {
let newArray = []
if (array.length === 0) {
return newArray
}
for (let i = 0; i < array.length; i++) {
const num1 = array[i];
for (let j = i + 1; j < array.length; j++) {
const num2 = array[j];
for (let k = j + 1; k < array.length; k++) {
const num3 = array[k];
if (num1 + num2 + num3 === targetSum) {
newArray.push([num1, num2, num3])
}
}
}
}
return newArray
}
console.log(threeSum([12, 3, 1, 2, -6, 5, -8, 6], 0))
// [[-8, 2, 6], [-8, 3, 5], [-6, 1, 5]]
This works but only because I'm iterating through the array, I've tried checking the last and first number then slicing the array everytime I recall the function. I've written a base case so far but I'm lost on the recursion step.
This is what I have for the recursion:
let threeSum = (array, targetSum) => {
let newArray = []
if (array.length === 0) {
return newArray
}
let num1 = array[0]
let num2 = array[1]
let num3 = array[2]
if (num1 + num2 + num3 === targetSum) {
newArray.push([num1, num2, num3])
}
return array.slice(1), targetSum
}
console.log(threeSum([12, 3, 1, 2, -6, 5, -8, 6], 0))
// [[-8, 2, 6], [-8, 3, 5], [-6, 1, 5]]
Generators make recursion a bit easier because you can just yield the results. Here the base case is a set of three numbers and a total that equals the values passed in (or no more numbers).
Then just take the first number, add it to found, use it to adjust the total and found numbers and recurse with the rest:
function* threeSum(a, total, found = []) {
if (found.length == 3) {
if (total == 0) yield found
return
}
if (a.length == 0) return
yield* threeSum(a.slice(1), total - a[0], [...found, a[0]])
yield* threeSum(a.slice(1), total, found)
}
console.log([...threeSum([12, 3, 1, 2, -6, 5, -8, 6], 0)])
As pointed out, recursion may not be the best approach, but if you must use it, ...
The idea here is at each level of recursion, you make the problem smaller (by using one of the numbers), and then recurse on the 'rest of the array'.
You stop after 3 numbers are used or you go over the target.
This is called Backtracking.
<div id=divvie> </div>
<script>
var html = "";
var target = 23; // or pass it down
function threesum(subsum, sumsofar, n, Arr, istart)
{
var i;
if (n == 0)
{
if (sumsofar == target)
html += subsum + "<br>";
return;
}
for (i = istart; i < Arr.length; i++)
{
var j = Arr[i];
if (sumsofar + j <= target)
threesum(subsum + "," + j, (sumsofar+j), n-1, Arr, i+1);
}
}
threesum(target + " = ", 0, 3, [8, 5, 2, 6, 9, 7, 4, 1, 12, 3], 0);
document.getElementById("divvie").innerHTML = html;
</script>
Output is:
23 = ,8,6,9
23 = ,8,12,3
23 = ,5,6,12
23 = ,2,9,12
23 = ,7,4,12

issue with merge sorted arrays problem using javascript

I am trying to solve merge 2 sorted arrays problem using javascript. Please find my solution below:
input:
const arr1 = [1, 4, 7, 8, 10];
const arr2 = [2, 3, 9];
output:
[1, 2, 3, 4, 7, 8, 9 10]
const arr1 = [1, 4, 7, 8, 10];
const arr2 = [2, 3, 9];
let arrayItem1 = arr1[0];
let arrayItem2 = arr2[0];
let i = 1;
let j = 1;
let mergedArray = [];
while(arrayItem2 || arrayItem1) {
arrayItem1 = arrayItem1 === undefined ? 0 : arrayItem1;
arrayItem2 = arrayItem2 === undefined ? 0 : arrayItem2;
if (arrayItem1 < arrayItem2) {
console.log('inside if');
console.log("first array", arrayItem1);
arrayItem1 = arr1[i];
i++;
mergedArray.push(arrayItem1);
} else {
console.log('inside else');
console.log("second array", arrayItem2);
arrayItem2 = arr2[j];
j++;
mergedArray.push(arrayItem2);
}
console.log("== merged array ==", mergedArray);
}
But it is going in infinite loop. Not sure where I am going wrong. Need a watchful pair of eyes here.
thanks
You need to check the index with the lengths of the arrays and add a final check for getting the rest of the arrays added to the merged array.
const
array1 = [1, 4, 7, 8, 10],
array2 = [2, 3, 9],
mergedArray = [];
let i = 0,
j = 0;
while (i < array1.length && j < array2.length) {
if (array1[i] < array2[j]) {
mergedArray.push(array1[i++]);
} else {
mergedArray.push(array2[j++]);
}
}
if (i < array1.length) mergedArray.push(...array1.slice(i));
if (j < array2.length) mergedArray.push(...array2.slice(j));
console.log(...mergedArray);
const arr1 = [1, 4, 7, 8, 10];
const arr2 = [2, 3, 9];
const mergedArrays = [...arr1, ...arr2];
// WITH SORT
const result = mergedArrays.sort((a, b) => Number(a) - Number(b));
console.log(result);
// WITHOUT SORT
const bubbleSort = (arr) => {
let done = false;
while (!done) {
done = true;
arr.forEach((el, i) => {
if (arr[i - 1] > arr[i]) {
done = false;
const tmp = arr[i - 1];
arr[i - 1] = arr[i];
arr[i] = tmp;
}
});
}
return arr;
};
const result2 = bubbleSort(mergedArrays)
console.log(result2)
You don't really need to go through all that trouble, you can merge your arrays by destructuring your arrays in new one and just use the Array.sort() method.
UPDATE:
Added sorting without using using Array.sort(), using a sorting algorithm Bubble sort
This will also work for non positive numbers
//[1, 2, 3, 4, 7, 8, 9 10]
const arr1 = [1, 4, 7, 8, 10];
const arr2 = [2, 3, 9];
let arrayItem1 = arr1[0];
let arrayItem2 = arr2[0];
let i = 1;
let j = 1;
let mergedArray = [];
while(arrayItem2 !== undefined || arrayItem1 !== undefined) {
if (arrayItem2 === undefined || arrayItem1 < arrayItem2) {
mergedArray.push(arrayItem1);
arrayItem1 = arr1[i];
i++;
} else {
mergedArray.push(arrayItem2);
arrayItem2 = arr2[j];
j++;
}
console.log('Merged array: ' + mergedArray)
}
Some issues:
The actions in the if block (and else block) occur in the wrong order. You first want to push the item, then increment the index, and then get the next value from the array so it will be used in the next comparison.
Don't assign the value 0 when a value is undefined. Just leave it undefined, otherwise you risk to push a 0 into the result that was never there in the input.
So:
const arr1 = [1, 4, 7, 8, 10];
const arr2 = [2, 3, 9];
let arrayItem1 = arr1[0];
let arrayItem2 = arr2[0];
let i = 1;
let j = 1;
let mergedArray = [];
while(arrayItem2 || arrayItem1) {
if (arrayItem2 === undefined || arrayItem1 < arrayItem2) {
mergedArray.push(arrayItem1);
i++;
arrayItem1 = arr1[i];
} else {
mergedArray.push(arrayItem2);
j++;
arrayItem2 = arr2[j];
}
}
console.log("== merged array ==", mergedArray);
const arr1 = [1, 4, 7, 8, 10];
const arr2 = [2, 3, 9];
var children = arr1.concat(arr2);
console.log (children.sort(function(a, b){return a - b}));
children.sort(function(a, b){return a - b});
const arr1 = [1, 4, 7, 8, 10];
const arr2 = [2, 3, 9];
var children = arr1.concat(arr2);
console.log (children.sort(function(a, b){return a - b}));

Sorting an array by chunks of 3

Assume that you have an array and want to divide it by chunks of 3. If the array is..
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
...the new array would be
let newArr = [1, 4, 7, 10, 13, 2, 5, 8, 11, 3, 6, 9, 12]
// In other words:
1 2 3
4 5 6
7 8 9
10 11 12
13
The chunking part should be this code (if sorted like newArr):
let chunkedArr = _.chunk(_.toArray(newArr), 3);
...however I couldn't figure out how to sort the arr to newArr to be able to chunk in the right order. What is the proper way of handling such case?
Please note that the integers are just pseudo and I will use proper objects of array.
One option is to use ES6 reduce to group the array into a multidimensional array. Use concat to flatten the multidimensional array.
[].concat(...) - basically flattens the multidimensional array. Starting with an empty array [], you concat each secondary array. Use the spread operator (...) to reiterate each secondary array and concat each.
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
let groups = 3;
let newArr = [].concat(...arr.reduce((c, v, i) => {
let k = i % groups;
c[k] = c[k] || [];
c[k].push(v);
return c;
}, []));
console.log(newArr);
Please try the following (jsfiddle):
//This version works for variable chunk sizes as well.
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
alert(chunks(arr, 3)); //You can update chunk size here
function chunks(arr, chunkSize) {
var result = [];
var index = 0;
for (var i = 0; i < chunkSize; i++) {
for (var j = 0; j < arr.length / chunkSize; j++) {
if (arr[i + (chunkSize * j)] != null)
result[index++] = arr[i + (chunkSize * j)];
}
}
return result;
}
//This version only works for chunks of size 3.
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
let subArr1 = [];
let subArr2 = [];
let subArr3 = [];
var result = [];
var i = 0, j = 0, k = 0;
for (var index = 0; index < arr.length; index++) {
if (index % 3 == 0) {
subArr1[i++] = arr[index];
}
if (index % 3 == 1) {
subArr2[j++] = arr[index];
}
if (index % 3 == 2) {
subArr3[k++] = arr[index];
}
}
result.push(subArr1, subArr2, subArr3);
alert(result);
Please check this it may help you. I also take a reference from here. Please check and let us know. any thing else you need.
Thanks
Here is the sample code.
var i,j,resArr,chunkSize = 10;
for (i=0,j=array.length; i<j; i+=chunk) {
resArr = array.slice(i,i+chunk);
}
const original = [1,2,3,4,5,6,7,8,9,10,11,12,13]
const chunks = 3
function getChunckedArr(arr, n) {
let sub = new Array(n);
let result = [];
for (let i=0; i<sub.length; i++)
sub[i] = []
arr.forEach(function (val, index){
let o = (index % n);
sub[o][sub[o].length] = val;
});
for (let i=0; i<sub.length; i++)
result.push.apply(result, sub[i]);
return result;
}
const chunked = getChunckedArr(original, chunks);

I need to write a function that loops through an array of numbers, and returns the odd & even numbers in it's array.

I need to write a function that loops through an array of numbers, and returns the odd & even numbers in it's array.
I'm not sure if there's a better way to do this, and I'm stuck. Is there a way to return both statements?
var myNums = [1, 2, 3, 4, 5, 6, 7, 9];
var evens = [];
var odds = [];
function oddsAndEvens(nums) {
for(var i = 0; i < nums.length; i++){
if(nums[i] % 2 === 0){
evens.push(nums[i])
}
else if (!nums[i] % 2 === 0) {
odds.push(nums[i])
}
}
console.log(evens);
console.log(odds);
//I need it to "return" the array,
//not console log
}
console.log(oddsAndEvens(myNums));
A clean function to separate the evens from the odds.
function arrangeNums(array) {
let odd = array.filter(i=>i%2!==0);
let even = array.filter(i=>i%2===0);
return {even:even,odd:odd};
}
console.log(arrangeNums([...Array(100).keys()]));
return arrays instead of console.log should work
var myNums = [1, 2, 3, 4, 5, 6, 7, 9];
var evens = [];
var odds = [];
function oddsAndEvens(nums) {
for(var i = 0; i < nums.length; i++){
if(nums[i] % 2 === 0){
evens.push(nums[i])
}
else if (!nums[i] % 2 === 0) {
odds.push(nums[i])
}
}
// return array of values you want
return [evens, odds]
}
console.log(oddsAndEvens(myNums));
You could use an object for the result and taken an array for the keys of the object to push the value.
function getGrouped(array) {
return array.reduce(function (r, a) {
r[['even', 'odd'][a % 2]].push(a);
return r;
}, { odd: [], even: [] });
}
var myNums = [1, 2, 3, 4, 5, 6, 7, 9];
console.log(getGrouped(myNums));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Off course you can, just return an object containing both evens and odds,
function oddsAndEvens(nums)
{
var evens = [];
var odds = [];
for(var i = 0; i < nums.length; i++){
if(nums[i] % 2 === 0){
evens.push(nums[i])
}
else if (!nums[i] % 2 === 0) {
odds.push(nums[i])
}
}
return {"evens":evens,"odds":odds};
}
var myNums = [1, 2, 3, 4, 5, 6, 7, 9];
result = oddsAndEvens(myNums);
console.log(result.evens);
console.log(result.odds);

Extracting the most duplicate value from an array in JavaScript?

my question is actually similar to: Extracting the most duplicate value from an array in JavaScript (with jQuery)
Solution (the one I found as the best, and slightly changed by me):
var arr = [3, 7, 7, 7, 7, 10, 10, 8, 5, 5, 5, 5, 20, 20, 1],
result = {},
max = 0,
res;
for( var i = 0, total = arr.length; i < total; ++i ) {
var val = arr[i],
inc = ( result[val] || 0 ) + 1;
result[val] = inc;
if( inc > max ) {
max = inc;
res = val;
}
}
alert(res);
I would like to add an extra which is : if we have, say two numbers with the same number of occurrences, how could we find the minimum of them (the above should alert 5 and not 7, which is the case)? The current solution works for getting only the first most duplicate found, but it does not deal with repetition.
Thanks!
Sort the array before you count the incidences:
var arr = [3, 7, 7, 7, 7, 10, 10, 8, 5, 5, 5, 5, 20, 20, 1];
function min_most_duplicate (arr) {
var result = {},
max = 0,
res;
arr = arr.slice(0); // make a copy of the array
arr.sort(function(a, b) { return (a - b); }); // sort it numerically
for( var i = 0, total = arr.length; i < total; ++i ) {
var val = arr[i],
inc = ( result[val] || 0 ) + 1;
result[val] = inc;
if( inc > max ) {
max = inc;
res = val;
}
}
return res;
}
min_most_duplicate(arr); // returns 5
This works because the way the for loop is written it's going to return the first one that it finds that has the most duplicates, so if the array is sorted, the smallest number will come first, so it'll be the one that the for loop finds.
This would work, example:
var arr = [3, 7, 7, 7, 7, 10, 10, 8, 5, 5, 5, 5, 20, 20, 1],
result = {},
max = 0,
res, key, min;
for (var i = 0, total = arr.length; i < total; ++i) {
var val = arr[i],
inc = (result[val] || 0) + 1;
result[val] = inc;
if (inc > max) {
max = inc;
res = val;
}
}
for (var i in result) {
if (result[i] === max) {
key = parseInt(i, 10);
min = min || key;
console.log(min)
if (min > key) {
min = key;
}
}
}
res = min;
alert(res);
let getMostDuplicated = array => {
let duplicated = '';
let max = 0;
for (let i = 0; i < array.length; i++) {
let counter = 0;
for (let j = 1; j < array.length - 1; j++) {
if (array[i] === array[j])
counter++;
}
if (counter > max) {
duplicated = array[i];
max = counter;
}
}
return duplicated;
};
let array = [3, 7, 7, 7, 7, 10, 10, 8, 5, 5, 5, 5, 20, 20, 1];
getMostDuplicated(array);

Categories

Resources