Node JS displaying value at index instead of indices - javascript

Written this 2sums code to get efficent O(N) Time complexity algorithm for below problem
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
unfortunately saw value at array nums got displayed in the output ,whereas the need is to get the indices to be displayed in output
What change needs to be done below
let hashTwoSum = (array, sum) => {
let numsObj = {}
let nums = []
for(let i in array){
let addend = sum - array[i]
if (addend in numsObj){
nums.push([addend, array[i]])
}
numsObj[array[i]] = i
}
return nums
}
let array = [2,7,11,15]
console.log(hashTwoSum(array,9))
Your help is appreciated
Regards,
Carolyn

As #jriend00 said, do not use for(... in ...) loop for iterating arrays. But in your case, where you need indices, you need to use the good old for loop: for(let i = 0; i < array.length; i++). And when you save results, you need to push both indices: nums.push([numsObj[addend], i]).
Here's a complete example:
let hashTwoSum = (array, sum) => {
let numsObj = {}
let nums = []
for(let i = 0; i < array.length; i++){
let addend = sum - array[i]
if (addend in numsObj){
nums.push([numsObj[addend], i])
}
numsObj[array[i]] = i
}
return nums
}
let array = [2,7,11,15,6]
console.log(hashTwoSum(array,17))
This will output:
[ [ 0, 3 ], [ 2, 4 ] ]
because 2 + 15 and 11 + 6 are both equal 17.

Related

distinct integers in JavaScript

Given a zero-based permutation nums (0-indexed), build an array ans of the
same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and
return it.
A zero-based permutation nums is an array of distinct integers from 0 to
nums.length - 1 (inclusive).
Example 1:
Input: nums = [0,2,1,5,3,4]
Output: [0,1,2,4,5,3]
nums = [0,2,1,5,3,4]
var buildArray = function(nums) {
return nums.map(n => nums[n]);
};
console.log(buildArray(nums))
can any one explain dry run of this and why it is giving output as shown above and what is distinct integers?
Maybe this example will help you understand what is going on in the code. All examples will produce same result. In the example using map, n is equivalent to nums[i].
const nums = [0, 2, 1, 5, 3, 4];
// Using Array.map()
var buildArray = function(nums) {
return nums.map(n => nums[n]);
};
console.log('Using Array.map() : ', buildArray(nums))
// Using Array.map() with index
var buildArray2 = function(nums) {
return nums.map((n, i) => nums[nums[i]]);
};
console.log('Using Array.map() with index : ', buildArray2(nums))
// Using For Loop
let ans = new Array(nums.length);
for (let i = 0; i < nums.length; i++) {
ans[i] = nums[nums[i]];
}
console.log('Using for loop : ', ans);

How to get unique sub arrays within an array in Javascript

So I have this function that determines whether 2 the sum of two numbers within an array are equal to a given target number.
The function gives out all the possible combinations of achieving the target number but I only want unique sub-arrays.
let targetNum = 10
const array = [5,2,3,3,7,1,5]
const sumTwoNums = (array,num) => {
let newArray = [];
for (var i=0;i<array.length;i++) {
for (var j=0;j<array.length;j++) {
if(i!==j && array[i]+array[j]===num){
newArray.push([array[i],array[j]]);
}
}
}
return newArray
}// returns [[5,5],[3,7],[3,7],[7,3],[7,3],[5,5]]
What can I do to solve this issue?
I think this answer solves your problem .
function allPairs(ints, s) {
var hash = Object.create(null),
i,
value,
pairs = [];
for (i = 0; i < ints.length; i++) {
value = ints[i];
if (hash[value]) pairs.push([s - value, value]);
hash[s - value] = true;
}
return pairs;
}
console.log(allPairs([7, 2, 5, 8, 4, 3], 7));

NodeJS: how to separate large strings into an array of numbers, and then add all of those with an even index

The array I get my original strings from looks something like this:
arr[0]:
11-3
12-6
arr[1]:
5-9
7-2
18-2
arr[2]:
2-7
(That's just an example, the general idea is that there can be any number of objects in arr and the string in each of them contains any number of #-# combos)
I'm trying to add all the numbers on the left together (if using the example above it would add something like 11, 12, 5, 7, 18, and 2 together) and store that number in a variable.
How would I go about this?
Edit 1: attempted code:
var winsLossNums = winLoss[0].match(/\d+/g).map(Number)
for (var i = 0; i < winLoss[0].match(/\d+/g).map(Number).length; i++) {
if (i % 2 === 0) {
totalNums.push(winLoss[0].match(/\d+/g).map(Number)[i]);
}
}
}
This code is in a loop, and every loop there is a new arr object like in the example above
Assuming your array values are strings with a new line between them, you can reduce over the array, split each value on \n and reduce again on that taking the first value of splitting on '-':
let arr = ['11-3\n12-6', '5-9\n7-2\n18-2', '2-7']
let tot = arr.reduce((a, c) => {
let pairs = c.split('\n')
return a + pairs.reduce((a, c)=> a + Number(c.split('-')[0]), 0)
}, 0)
console.log(tot)
console.log(11 + 12 + 5 + 7+ 18 + 2)
You might need to clean up data or split on whitespace if it's not cleanly one \n per line. But this should be a good start.
You can try this:
let arr = [
[
'11-3',
'12-6'
], [
'5-9',
'7-2',
'18-2'
], [
'2-7'
]
];
let sum = 0;
for (let index=0; index<arr.length; index++) {
let arrayMasterElement = arr[index];
// console.log(arrayMasterElement);
for (let index2=0; index2<arrayMasterElement.length; index2++) {
let arrayElement = arrayMasterElement[index2];
let elementArray = arrayElement.split('-');
let intVal = parseInt(elementArray[0]);
console.log('Int value: ' + intVal);
sum += intVal;
}
if (index == arr.length - 1) {
console.log('Sum: ' + sum);
}
}

Find averages in an array of different numbers

I feel like I didn't phrase my title very well, can someone please correct it if you understand my question.
I have an array of
arr = [1,2,3,4,5,
6,7,8,9,0,
3,4,7,2,1,
4,6,1,2,3,
5,6,8,9,3
2,3,4,5,6
]
And I want to do several things
Split it into chunks with the size of 5
Calculate the number of chunks. In this case, it should be 6 chunks.
Calculate the sum of numbers of all chunks in each position and divide it by the total number of chunks. In this case,
(1+6+3+4+5+2)/6, (2+7+4+6+6+3)/6, ..., (5+0+1+3+3+6)/6
Return results as an array
var result = [3.5, 4.66, ..., 3]
I have got the idea, but not sure how to implement it.
Thanks
I believe this code accomplishes what you want.
function averageValues (arr) {
var chunks = Math.ceil(arr.length / 5); // find the number of chunks
var sums = [0, 0, 0, 0, 0]; // keep a running tally
for (var i = 0; i < arr.length; i ++) {
sums[i % 5] += arr[i]; // add each element to the proper part of the sum
}
for (var i = 0; i < sums.length; i ++) {
sums[i] /= chunks; // divide each part of the sum by the number of chunks
}
return sums;
}
You can solve this by maintaining five separate sums to end with five separate averages.
Prepare your sums array of length 5:
var sums = [ 0, 0, 0, 0, 0 ];
For each number in your set, increment the corresponding sum by that number.
for (var x = 0; x < arr.length; x++)
sums[x % 5] += arr[x];
Divide each sum by how many numbers were used:
var numbers = arr.length / 5; // 6 numbers each
var result = sums.map(
function(s) {
return s / numbers; // divide each sum by 6
}
);
This uses the assumption that your set length is always a multiple of 5.
Here is a more functional approach to your problem. This uses the assumption that your set length is always a multiple of 5.
// add extra array helpers
Array.prototype.eachSlice = function (n, fn) {
let slices = [];
for (let i = 0; i < this.length; i += n) {
let slice = this.slice(i, i + n);
slices.push(slice);
}
if (fn) slices.forEach(fn);
return slices;
}
Array.prototype.sum = function (fn) {
let fnReduce = fn ? (acc, ...args) => acc + fn(...args) : (acc, v) => acc + v;
return this.reduce(fnReduce, 0);
}
Array.prototype.avg = function (fn) {
return this.sum(fn) / this.length;
}
// actual solution
let arr = [
1,2,3,4,5,
6,7,8,9,0,
3,4,7,2,1,
4,6,1,2,3,
5,6,8,9,3,
2,3,4,5,6,
];
let chunkSize = 5;
console.log('--- question #1 ---');
console.log('Split it into chunks with the size of 5.');
console.log('-------------------');
let chunks = arr.eachSlice(chunkSize);
console.log(chunks);
console.log('--- question #2 ---');
console.log('Calculate the number of chunks. In this case, it should be 6 chunks.');
console.log('-------------------');
console.log(chunks.length);
console.log('--- question #3 ---');
console.log('Calculate the sum of numbers of all chunks in each position and divide it by the total number of chunks.');
console.log('-------------------');
let avgChunks = new Array(chunkSize).fill()
.map((_, i) => chunks.avg(chunk => chunk[i]));
console.log('See the result under question #4.');
console.log('--- question #4 ---');
console.log('Return results as an array.');
console.log('-------------------');
console.log(avgChunks);
It could be useful:
//The average method using an array
function average(arr) {
var sum = arr.reduce(function (a,b) { return a + b; },0)
return sum/ arr.length
}
//Chunk array method, it returns an array of the sliced arrays by size
function chunkArray(arr, chunkSize){
var numChunks = arr.length / chunkSize
var chunks= []
for (let index = 0; index < numChunks; index++) {
chunks.push(arr.slice(index * chunkSize, (index * chunkSize) + chunkSize))
}
return chunks
}
//Finally, the average of arrays, it returns the average of each array
function averageArrays(arrs){
return arrs.map(function (arr) {
return average(arr)
})
}
//Example of usage
var chunks = chunkArray([
1,2,3,4,5,
6,7,8,9,0,
3,4,7,2,1,
4,6,1,2,3,
5,6,8,9,3,
2,3,4,5,6
],5)
console.log(averageArrays(chunks))
I think #Aplet123 has the most straight forward and easy to understand approach, though I changed up a little bit to suit my needs.
var chunks = Math.ceil(arr.length / 5) // Find the number of chunks
var sums = new Array(5).fill(0) // Keeps a running tally and fill values 0
arr.map((x, i) => sums[i%5] += arr[i]) // add each element to the proper part of the sum
var avgs = sums.map((x) => x/chunks /divide each part of the sum by the number of chunks

looping infinitely through multiple arrays at the same time until a condition is met

I'm trying to find least common multiples of the two numbers given [3,5] and return only the number that's divisible by all the number in the range of the two numbers... for example:
The given array of two numbers --> let arr = [3,5];
The first number Multiples should be as follow:
[3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60];
The second number Multiples should be as follow:
[5,10,15,20,25,30,35,40,45,50,55,60];
The Least common multiples should be as follows:
[15,30,45,60];
the only that is divisible by all the number in the range is 60.
This is my approach to solve this problem but I want to know what's wrong with my code below (PLEASE EXPLAIN 'cause I'm tired of guessing):
let arr = [3, 5];
let arrRange = []; // [3, 4, 5]
// creating a loop to create the range
for (var i = arr[0]; i <= arr[1]; i++) {
arrRange.push(i);
}
let f = arr[0], s = arr[1], c = 0, result = 0, firstMultiples = [], secondMultiples = [], leastCommonMultiples = [];
// This function is made if the number least Common number is divisible by all the numbers in the "arrRange"
function isDivisible(num) {
for(var i = 0; i < arrRange.length; i++) {
if(num % arrRange[i] != 0) {
return false;
}
}
return true;
}
while(true) {
firstMultiples.push(f);
secondMultiples.push(s);
f = f + arr[0];
s = s + arr[1];
let vals = secondMultiples.values();
for(let val of vals){
if( firstMultiples.includes(val) ) {
leastCommonMultiples.push(val);
}
}
let cmlVals = leastCommonMultiples.values();
for(let cmlVal of cmlVals){
if(isDivisible(cmlVal)) {
result += cmlVal;
break;
}
}
c++;
}
console.log(result);
To fix it, change the while-loop from while (true) {/*code*/}; to
while(isDivisible(cmlVal) == true) {/*code*/}; and remove the
if(isDivisible(cmlVal)) {/*code*/ break;}.

Categories

Resources