For Loop that calculates sum of squred numbers in array - javascript

I am working on a challenge and in need of some help:
Write a for loop that calculates sum of squares of items in an array of numbers. Example: For array [ 1, 2, 3, 4 ] it calculates the sum of squares as 30 (i.e. 1 + 4 + 9 + 16). I have a fiddle set up if anyone wants to have a closer look. Thanks for your help!
https://jsfiddle.net/jamie_shearman/2drt56e3/23/
var aFewNumbers = [ 1, 2, 3, 7 ];
var squareOfAFewNumbers = 0;
for( var i = 0; i <= aFewNumbers; i++ ) {
squareOfAFewNumbers = squareOfAFewNumbers * aFewNumbers[i] ;
}
console.log( squareOfAFewNumbers );

Your math is wrong. As an obvious issue, the variable starts at 0 and then is multiplied by each array element; 0 times anything is 0, so it will always remain 0 no matter what the values are. Not to mention your loop isn't looking at the length of the array as a stopping condition, which it should be, since you want to iterate from the beginning to the end of the array.
You need to iterate through to the array's length, square each array element, and add that square to the variable:
for( var i = 0; i < aFewNumbers.length; i++ ) {
squareOfAFewNumbers += aFewNumbers[i] * aFewNumbers[i];
}
If you can use ES6, you can even use higher-order array functions to simplify this more:
var squareOfAFewNumbers = aFewNumbers.reduce((result, entry) => result + entry * entry, 0);

There are multiple approaches you can take for reaching the desired result, but as you've mentioned that you must write a for loop; therefore, I sorted the answers by having that in mind.
Using the for loop
let numbers = [1, 2, 3, 7],
sum = 0;
for(let i = 0; i < numbers.length; i++) {
sum += Math.pow(numbers[i], 2)
}
// Sum is now 63
Using forEach method of the array object
let numbers = [1, 2, 3, 7],
sum = 0;
numbers.forEach(number => sum += Math.pow(number, 2))
// Sum is now 63
Oneliner
let sum = [1, 2, 3, 7].reduce((a, c) => a + Math.pow(c, 2))
The reduce method uses an accumulator to store temporary results, the accumulator is passed to the callback as the first argument and the second argument is the element's value, you can read more about the reduce method here.

You can use JavaScript pow() Method to create the square and sum it to the sumSquareOfAFewNumbers.
var aFewNumbers = [ 1, 2, 3, 7 ];
var sumSquareOfAFewNumbers = 0;
aFewNumbers.forEach(function(element) {
sumSquareOfAFewNumbers += Math.pow(element, 2);
});
console.log(sumSquareOfAFewNumbers)

Related

Know the last number equal to another within an array in Javascript

const numbersArray = [5, 3, 1, 3, 4, 5, 3, 1];
var pastNumbers = [];
for (let i = 0; i < numbersArray.length; i++) {
const number = numbersArray[i];
pastNumbers.push(number);
var count = 0;
pastNumbers.forEach((v) => (v === number && count++));
console.log(`There are ${count} numbers before equal to ${number}. The last equal number is in the ${???} position.`);
}
I have an array called pastNumbers that stores the numbers that were previously traversed by the for loop of another array called numbersArray. Then with forEach I get the amount of previous numbers equal to number.
I want to know the position of the last number equal to number within the pastNumbers array.
How can I do it?
Updated with for loop
Use an object instead of array to track, it makes it a bit easier.
In this example, I'm going over each number and adding the position at the beginning (unshift) to pastNumber[number].
I'm using unshift so that the first item is the last position registred. That way I can look up with [0] instead of using [$.length-1] (but I'm still still using the length anyway so you push is fine too 🤷‍♂️)
const numbersArray = [5, 3, 1, 3, 4, 5, 3, 1];
const pastNumbers = {};
for (let i = 0; i < numbersArray.length; i++) {
const number = numbersArray[i];
if (!pastNumbers[number]) {
pastNumbers[number] = [];
}
if (pastNumbers[number].length > 0) {
console.log(
`There are ${pastNumbers[number].length} numbers before equal to ${number}. The last equal number is in the ${pastNumbers[number][0]} position.`
);
}
pastNumbers[number].unshift(i);
}

Split array into arrays of numbers where the sum is equal to a specific target

I need to create a function that take as parameter an array and a target. It should return an array of arrays where the sum of these numbers equals to the target
sumPairs(array, target) {
}
For example:
sumPairs([1, 2, 3, 4, 5], 7) // output : [[2, 5], [3, 4]]
I know I have to use map(), and probably reduce(), set(), or filter() maybe (I read their documentation in MDN but still cant find out). I tried some ways but I can't get it.
If you guys could help me to find out how to dynamically create arrays and push them into a new array..
I read there some solutions (Split array into arrays of matching values) but I hate to just use created functions without knowing what they really do or how they work.
Some very basic code for achieving it, Just run all over combinations and conditionally add the items you want.
function sumPairs(array, target) {
var res = [];
for(var i = 0; i < array.length; i++){
for(var j = 0; j < array.length; j++){
if(i!=j && array[i]+array[j]==target &&
res.filter((x)=> x[0] == array[j] && x[1] == array[i]).length == 0 )
res.push([array[i], array[j]]);
}
}
return res;
}
var result = sumPairs([1, 2, 3, 4, 5], 7);
console.log(result);
Option 2 - see this answer for more options (like using reduce)
function sumPairs(array, target) {
return array.flatMap(
(v, i) => array.slice(i+1).filter(w => (v!=w && v+w==target)).map(w=> [w,v])
);
}
var result = sumPairs([1, 2, 3, 4, 5], 7);
console.log(result);
"The exercise says that it sould be arrays of pairs that sum the
target value so I think only 2 items"
If you need a pair that matches a sum and you pick any number from the list, you are left with
the following equation to solve num + x = sum where we want to find x. E.g. if you picked 7 and the target sum is 10 then you know you are looking for a 3.
Therefore, we can first construct a counting map of the numbers available in our list linear (O(n)) time and then search for matches in linear time as well rather than brute forcing with a quadratic algorithm.
const nums = [1, 2, 3, 4, 5];
console.log(findSumPairs(nums, 7));
function findSumPairs(nums, sum) {
const countByNum = countGroupByNum(nums);
return nums.reduce((pairs, num) => {
countByNum[num]--;
const target = sum - num;
if (countByNum[target] > 0) {
countByNum[target]--;
pairs.push([num, target]);
} else {
countByNum[num]++;
}
return pairs;
}, []);
}
function countGroupByNum(nums) {
return nums.reduce((acc, n) => (acc[n] = (acc[n] || 0) + 1, acc), {});
}
Here's another implementation with more standard paradigms (e.g. no reduce):
const nums = [1, 2, 3, 4, 5];
console.log(findSumPairs(nums, 7));
function findSumPairs(nums, sum) {
const countByNum = countGroupByNum(nums);
const pairs = [];
for (const num of nums) {
const target = sum - num; //Calculate the target to make the sum
countByNum[num]--; //Make sure we dont pick the same num instance
if (countByNum[target] > 0) { //If we found the target
countByNum[target]--;
pairs.push([num, target]);
} else {
countByNum[target]++; //Didin't find a match, return the deducted num
}
}
return pairs;
}
function countGroupByNum(nums) {
const countByNum = {};
for (const num of nums) {
countByNum[num] = (countByNum[num] || 0) + 1;
}
return countByNum;
}
You can also sort your array and find all the pairs with given sum by using two pointer method. Place the first pointer to the start of the array and the second pointer to the end.
if the sum of the values at the two places is :
More than target: Decrement your second pointer by 1
Less than target: Increment your first pointer by 1
Equal to target: This is one possible answer, push them to your answer array and increment your first pointer by 1 and decrement your second pointer by 1.
This is more performant solution with complexity O(n*log(n))

Improve the speed of a JavaScript function

I have a task I found on CodeWars and I managed to solve it, however, after submitting is says:
Execution timed out: (12000 ms)
When I try to test the function is passed, but I guess it is too slow.
Before you condemn me for not finding the answer on my own. I don't really care about submitting that as a response, but I have no idea how to make it faster and that is why I am here.
Here is the function:
const ls = [0, 1, 3, 6, 10]
const partsSums = (ls) => {
const sum = []
for(let i = 0, len = ls.length; i < len + 1; i++) {
let result = ls.slice(i).reduce( (accumulator, currentValue) => accumulator + currentValue, 0)
sum.push(result)
}
return sum
}
Here are the instructions:
Let us consider this example (array written in general format):
ls = [0, 1, 3, 6, 10]
Its following parts:
ls = [0, 1, 3, 6, 10]
ls = [1, 3, 6, 10]
ls = [3, 6, 10]
ls = [6, 10]
ls = [10]
ls = []
The corresponding sums are (put together in a list): [20, 20, 19, 16,
10, 0]
The function parts_sums (or its variants in other languages) will take
as parameter a list ls and return a list of the sums of its parts as
defined above.
For this kind of array maipulations, you better not use build in methods, like slice or reduce, because they are slow in comparison to a for loop, or any other looping approaches.
This approach takes a sinlge loop and uses the index for getting a value of the given array and takes the last sum of the new array.
Some speed tests on Codewars: Sums of Parts:
5621 ms with sparse array sum = []; sum[i] = 0; (the first version of this answer),
3452 ms with Array(i + 1).fill(0) and without sum[i] = 0;,
1261 ms with Array(i + 1) and sum[i] = 0; (find below),
3733 ms with Icepickle's first attempt.
const
partsSums = (ls) => {
let i = ls.length;
const sum = Array(i + 1);
sum[i] = 0;
while (i--) sum[i] = sum[i + 1] + ls[i];
return sum;
},
ls = [0, 1, 3, 6, 10];
console.log(...partsSums(ls));
You can still take a more functional approach but optimise the way you're doing the calculations.
Here is the idea - since you're trying to sum all items, then sum all but the first, then sum all but the second, etc., mathematically equivalent to getting the sum then subtracting from it each number in order and keeping the total.
[sum([41, 42, 43]), sum([42, 43]), sum([43]), sum([])]
is the same as:
total = sum([41, 42, 43])
[total - 0, total - 0 - 41, total - 0 - 41 - 42, total - 0 - 41 - 42- 43]
is the same as:
total = sum([41, 42, 43])
[total -= 0, total -= 41, total -= 42, total -= 43]
Generalised, this looks like:
total = sum([a1, a2, ..., aN])
[total -= 0, total -= a1, total -= a2, ..., total -= aN]
Using the trusty Array#reduce we can derive the sum once. Then we can derive the new array using Array.map using ls.map(num => total -= num).
The only problem here is that we get one less item - we don't calculate the initial total -= 0 which has to exist for all items. One way to do it is to append it to the start [0].concat(ls) will create the correct array to map over. However, since we already know what the value there would be, we can skip this step and directly substitute with total (after all the result of total -= 0 is total and leaves total unchanged). So, we can directly use [total].concat(ls.map(num => total -= num)) to start with total and add the rest of the items. to the end.
const ls = [0, 1, 3, 6, 10]
const partsSums = (ls) => {
let total = ls.reduce((a, b) => a + b, 0);
return [total]
.concat(
ls.map(num => total -= num)
);
}
console.log(partsSums(ls));
Personally, I would just use the previous sum to calculate the next, I don't see any need to re-iterate all the previous sums, so, I would probably go for a basic loop and then reverse the results, like so
function partsSums(ls) {
const result = [0];
if (ls.length === 0) {
return result;
}
for (let i = ls.length, q = 0; i--; q++) {
result.push(result[q] + ls[i]);
}
return result.reverse();
}
or, without reversing, look more like Nina's solution (except for predefining the length of the array)
function partsSums(ls) {
const len = ls.length;
const result = new Array(len+1);
result[len] = 0;
for (let i = len; i--;) {
result[i] = result[i+1] + ls[i];
}
return result;
}
Both also seem to run faster than Nina's on codewars nodejs engine, in the first part probably because of push, in the second one, probably because the array's length is defined from the start, for more information see this question
A solution using normal for loop along the time of execution .
var arr = [0, 1, 3, 6, 10];
function giveList(array){
var sum=0;
for(let i=0;i<array.length;i++){
sum=sum+array[i];
}
var result = [];
result.push(sum);
var temp;
for(let i=0;i<array.length;i++){
temp=sum-array[i];
result.push(temp);
sum=sum-array[i];
}
return result;
}
console.time();
console.log(giveList(arr));
console.timeEnd();
const partsSums = (ls, sum = 0) =>
[...ls, 0].reverse().map(x => sum = x + sum).reverse();
Takes around 1100 ms when I run it on CodeWars, which is slightly faster than other answers.
The repeated operation is too more. e.g: when you compute sum of [3, 6, 10], the up step [1, 3, 6, 10] already compute。 So you can think in another direction, back to end compute the sum of array
const ls = [0, 1, 3, 6, 10];
function partSums(ls) {
const len = ls.length;
const dp = [];
if(len === 0) { return [0] }
dp[len] = 0;
dp[len - 1] = ls[len - 1];
for (let i = len - 2; i >= 0; i--) {
dp[i] = dp[i + 1] + ls[i];
}
return dp;
}

How do you test whether both sides of an array total the same? | Javascript Algorithm

Question
You are going to be given an array of integers. Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1.
For example:
Let's say you are given the array {1,2,3,4,3,2,1}: Your function will return the index 3, because at the 3rd position of the array, the sum of left side of the index ({1,2,3}) and the sum of the right side of the index ({3,2,1}) both equal 6.
Answer
function findEvenIndex(arr){
for(let i = 0; i <arr.length; i++){
let arr1 = arr.slice(0, (arr[i] - 1));
let arr2 = arr.slice((arr[i] + 1),);
let arr11 = arr1.reduce((total, item)=>{
return total + item;
}, 0);
let arr22 = arr2.reduce((total, item)=>{
return total + item;
}, 0);
if(arr11 === arr22){
return arr[i];
}
}
return -1;
}
console.log(findEvenIndex([1, 2, 3, 4, 3, 2, 1]))
console.log(findEvenIndex([1, 100, 50, -51, 1, 1]))
console.log(findEvenIndex([1, 2, 3,4,5,6]))
I can't see an error here, but it yields incorrect results. Any ideas?
You have this part:
let arr1 = arr.slice(0, (arr[i] - 1));
let arr2 = arr.slice((arr[i] + 1),);
This is incorrect: arr[i]. That is a value, eg in [2,4,6,8,10] arr[3]==8. You want to slice on the index itself:
let arr1 = arr.slice(0, i - 1);
let arr2 = arr.slice(i + 1,);
Please note: There is another error in the two lines :) I leave that to you. Hint: you're now slicing two values out of the array instead of one. Perform the following code in your head first, then somewhere where you verify your results.
let arr = [0,1,2,3,4]
let x = 2;
console.log(arr.slice(0, x - 1));
console.log(arr.slice(x + 1,));
You could also use the array method findIndex, which, we shouldn't be surprised to learn, finds an index in an array subject to a certain condition.
const sum = (ns) =>
ns .reduce ((total, n) => total + n, 0)
const findBalancedIndex = (ns) =>
ns .findIndex ((_, i) => sum (ns.slice (0, i)) === sum (ns.slice (i + 1)))
console .log (findBalancedIndex ([1, 2, 3, 4, 3, 2, 1]))
console .log (findBalancedIndex ([1, 100, 50, -51, 1, 1]))
console .log (findBalancedIndex ([1, 2, 3, 4, 5, 6]))
Here we include a simple helper function to find the sum of an array, and then we pass a function to findIndex which uses it twice on the elements before the index and those after it. We use the second parameter of the callback function, the index to do this. This means we are skipping the first parameter altogether, and rather than naming it with something like n, we use the somewhat common convention of calling it _, signalling a placeholder we won't use. Note that you don't need to subtract one from the right-hand boundary of slice, since that boundary value is already excluded. And of course, others have pointed out that you need to slice to the index and not the array value at that index.
This finds the first correct index. You would have to use a different technique if you wanted to find all such indices. (That it's possible to have more than one should be clear from arrays like [1, 2, 3, 0, 0, 0, 0, 3, 2, 1] -- the indices for all those 0s would work.)
you return arr[i] when you need to return just i

Picking 2 random elements from array

What is the most efficient way to select 2 unique random elements from an array (ie, make sure the same element is not selected twice).
I have so far:
var elem1;
var elem2;
elem1 = elemList[Math.ceil(Math.random() * elemList.length)];
do {
elem2 = elemList[Math.ceil(Math.random() * elemList.length)];
} while(elem1 == elem2)
But this often hangs my page load.
Any better solution?
Extra question, how do I extend this to n elements
do NOT use loops and comparisons. Instead
shuffle the array
take first two elements
It can be done using built-in functionality (slice and sort),
var n = 2
randomItems = array.sort(() => .5 - Math.random()).slice(0, n);
http://underscorejs.org/#sample
_.sample(list, [n])
Produce a random sample from the list. Pass a number to return n random elements from the list. Otherwise a single random item will be returned.
_.sample([1, 2, 3, 4, 5, 6]);
=> 4
_.sample([1, 2, 3, 4, 5, 6], 3);
=> [1, 6, 2]
Looking at the source it uses shuffle just like #thg435 suggested.
Your code will hang when the list contains only one item. Instead of using ==, I recommend to use ===, which looks more suitable in this case.
Also, use Math.floor instead of Math.ceil. The length property is equal to <highest index> + 1.
var elem1;
var elem2;
var elemListLength = elemList.length;
elem1 = elemList[Math.floor(Math.random() * elemListLength)];
if (elemListLength > 1) {
do {
elem2 = elemList[Math.floor(Math.random() * elemListLength)];
} while(elem1 == elem2);
}
On what Rob W told you, I'll add that a different solution would be to find a random point and for the second point find a random offset from the point:
var elem1;
var elem2;
var elemListLength = elemList.length;
var ix = Math.floor(Math.random() * elemListLength);
elem1 = elemList[ix];
if (elemListLength > 1) {
elem2 = elemList[(ix + 1 + Math.floor(Math.random() * (elemListLength - 1))) % elemListLength];
}
We add 1 because the current element can't be reselected and subtract 1 because one element has already been selected.
For example, an array of three elements (0, 1, 2). We randomly select the element 1. Now the "good" offset value are 0 and 1, with offset 0 giving the element 2 and offset 1 giving the element 0.
Note that this will give you two random elements with different INDEX, not with different VALUE!
If you want to get n random elements you could create a shuffled version of your list and then return the first n elements of the shuffled array as a result.
If you shuffle the array and splice the number of elements you want to return,
the return value will contain as many items as it can,
if you ask for more items than are in the array.
You can shuffle the actual array or a copy, with slice().
Array.prototype.getRandom= function(num, cut){
var A= cut? this:this.slice(0);
A.sort(function(){
return .5-Math.random();
});
return A.splice(0, num);
}
var a1= [1, 2, 3, 4, 5];
a1.getRandom(2)
>>[4, 2]
If you want to remove the selected items from the original array,
so that a second call will not include the elements the first call returned,
pass a second argument: getRandom(3,true);
window.Memry=window.Memry || {};
Memry.a1= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
Memry.a1.getRandom(3,true);
>>[5,10,7]
Memry.a1.getRandom(3,true);
>>[3,9,6]
Memry.a1.getRandom(3,true);
>>[8,4,1]
Memry.a1.getRandom(3,true);
>>[2]
While shuffle the array and pick the first two is correct.
You don't need to shuffle the whole array.
Just shuffle the first two!
var arrElm = [1, 2, 3, 4, 5, 6, 7]
var toTake = 2
var maxToShuffle = Math.min(arrElm.length - 1, toTake)
for (let i = 0; i < maxToShuffle; i++) {
const toSwap = i + Math.floor(Math.random() * (arrElm.length - i))
;[arrElm[i], arrElm[toSwap]] = [arrElm[toSwap], arrElm[i]]
}
console.log(arrElm.slice(0, toTake))
basically the same as
https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
Except you just quit early when you have enough item shuffled.
You can do something easy like this
const elements = ['indie hackers', 'twitter', 'product hunt', 'linkedIn'];
const randomIndex = Math.floor(Math.random() * elements.length);
const a = elements[randomIndex];
const filteredElements = [...elements].splice(randomIndex, 1);
const b = filteredElements[Math.floor(Math.random() * elements.length)];
a and b will be your random elements.
I find this to be one of the most useful techniques:
var index1 = Math.floor(Math.random() * array.length);
var index2 = Math.floor(Math.random() * (array.length-1));
if index1 == index2 {
index2 += 1;
}
You cannot go out of bounds as index2 cannot get the last element.

Categories

Resources