So basically there are two sequences from I to j and j to k.
For example 3 to 5 and 5 to 2.
And we need to know the sum. 3 + 4 + 5 + 4 + 3 + 2.
And my code is not working.
var arr = [];
var sum = 0;
function pushIn(i, j, k){
for(var a = i; a < j; a++){
arr.push(a);
}
for(var a = j; a == k; a--){
arr.push(a);
}
for(var i = 0; i <arr.length;i++){
sum += arr[i];
}
}
}
I think the problem lies in your second for loop
Perhaps you should try this
for(var a = i; a < j; a++){
arr.push(a);
}
for(var a = j; a > k; a--){
arr.push(a);
}
for(var i = 0; i <arr.length;i++){
sum += arr[i];
}
Hope this helps
In for loop, second argument is a comparator- condition for executing the code block.
In your second loop, condition is never met hence it does not iterate at all.
In your case, I am assuming you want loop to be iterated unless it is less than or equals to k hence you need to make it >= so that condition will meet andloop will be iterated.
var arr = [];
var sum = 0;
function pushIn(i, j, k) {
for (var a = i; a < j; a++) {
arr.push(a);
}
for (var a = j; a >= k; a--) {
arr.push(a);
}
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
console.log(pushIn(3, 5, 2));
You may use .concat() and .reduce() to get the resultant value:
let reducer = (i, j, k) => [].concat(
Array.from({length: j - (i - 1)}, (_, index) => i + index),
Array.from({length: j - k}, (_, index) => j - (index + 1))
).reduce((r, c) => r + c, 0);
console.log(reducer(3, 5, 2));
Related
I want to get the common multiple in any given array, the problem i think is in my loop condition i dont want j to be less than 30, i want j to keep multiplying until the common multiple is found you can see the desired output down, how can i do this? thanks in advance.
function m(arr){
for(let i = 0; i < arr.length; i++){
console.log(`when arr[i] = `, i);
for(let j = arr[arr.length - 1]; j < 30; j += arr[arr.length - 1]) {
if(j % arr[i] === 0) console.log(j)
}
}
}
m([2,3,4,5])
this code outputs:
when arr[i] = 2
10
20
when arr[i] = 3
15
when arr[i] = 4
20
when arr[i] = 5
5
10
15
20
25
desired output
when arr[i] = 2
60
when arr[i] = 3
60
when arr[i] = 4
60
when arr[i] = 5
60
According to #Prosy Arceno's suggestion extended a little.
Thanks Prosy.
function m(arr) {
let m = multiply( arr )
for (let i = 0; i < arr.length; i++) {
console.log(`when arr[i] = `, i);
for (let j = arr[ arr.length - 1 ] ; j < m ; j++) {
let result = arr.every(function (element) {
return j % element === 0;
});
if (result) { console.log(j); break }
}
}
}
multiply =( arr )=>{
let m = 1
arr.map( element =>{ m = m * element } )
return m
}
m([2, 3, 4, 5 , 18]);
I think that your general approach is a bit problematic. Your inner for loop searches for the first common multiple of your current arr[i] and the last element of the array arr[arr.length-1].
In your example, this boils down to the inner loop logging a 10 because it is the first common multiple of 2 and 5.
There are many ways to solve your problem (see https://en.wikipedia.org/wiki/Least_common_multiple)
You may use every method of Array.
function m(arr) {
for (let i = 0; i < arr.length; i++) {
console.log(`when arr[i] = `, i);
for (let j = arr[ arr.length - 1 ] ; j < 100; j++) {
let result = arr.every(function (element) {
return j % element === 0;
});
if (result) { console.log(j); }
}
}
}
m([2, 3, 4, 5]);
function m(arr) {
for (let i = 0; i < arr.length; i++) {
console.log(`when arr[i] = `, i);
for (let j = 5; j < 100; j++) {
let result = arr.every(function (element) {
return j % element === 0;
});
if (result) console.log(j);
}
}
}
m([2, 3, 4, 5]);
I'm trying to find the number of adjacent element trios with a given sum.
Example:
Inputs arr = [1,2,3,12,1,4,9,6] sum = 6
Output = 2
([1,2,3,12,1,4,1,6])
My Code:
function getCount(arr, sum) {
var count = 0;
var indexes = [];
for (var i = 0; i < arr.length-2; i++) {
for (var j = i + 1; j < arr.length-1; j++) {
for (var k = j + 1; k < arr.length; k++){
if ((arr[i] + arr[j] + arr[k] == sum) && indexes.includes(i) && indexes.includes(j)) {
count++;
}
}
}
}
return count;
}
getCount([1,2,3,12,3,4,9,6],19);
But this is not work for adjacent elements.
I would just use a single loop/pass here:
function getCount(arr, sum) {
if (arr.length < 3) return 0;
var count = 0;
var first = arr[0];
var second = arr[1];
var third;
for (var i=2; i < arr.length; i++) {
third = arr[i];
var currSum = first + second + third;
if (currSum == sum) ++count;
first = second;
second = third;
}
return count;
}
console.log(getCount([], 3));
console.log(getCount([1, 2], 3));
console.log(getCount([1, 2, 3], 3));
console.log(getCount([1, 2, 3], 6));
console.log(getCount([1,2,3,12,3,4,9,6], 19));
The strategy here is to just walk down the input array once, keeping track of the current, previous, and previous previous values at each step. Then, we compute the sum of those three values, and compare against the input target sum.
Here is the problem: Find the number of subarrays in an array, which has the given sum.
this program enter 2 parameters number array and sum.
for example:
subArrayCnt([1,2,3,2,1,8,-3],5)
and the output should be number of subarrays accoding to given sum.
(output should be 3 for above example {2,3}, {3,2}, {8,-3} (number of subarrays))
I tried to do that but there is a problem with it isn't fulfilling the requirment of "The answer should be valid for any given input"
Here is my code:
function subArrayCnt(arr, sum) {
for (var i = 0; i < arr.length; i++) {
var str = [];
var csum= 0;
var output = 0;
for (var j = i; j < arr.length; j++) {
csum+= arr[j];
str.push(arr[j]);
if (csum== sum) {
return(str[i]);
}
}
}
}
console.log(subArrayCnt([1,2,3,2,1,8,-3],5));
this program provide number of subarrays but it isn't fulfilling the requirment of "The answer should be valid for any given input" where should be corrected? any suggetions please.
The other answers seem to be ignoring the fact that the sum can be obtained from any number of elements of the array. Recursion is the best approach here.
function subArrayCnt(arr, sum){
return subArrayRecurse(arr, sum, 0, [], 0)
}
function subArrayRecurse(arr, sum, currentSum, curArray, i){
var count = 0;
//check the current index
var newSum = currentSum + arr[i];
var newSubArray = curArray.concat([arr[i]]);
if(newSum == sum) {
console.log('found another: ' + newSubArray);
count++;
}
if(i + 1 < arr.length) {
//try including the current in further sums
count += subArrayRecurse(arr, sum, newSum, newSubArray, i + 1);
//try not including the current in further sums
count += subArrayRecurse(arr, sum, currentSum, curArray, i + 1);
}
return count;
}
console.log(subArrayCnt([1,2,3,2,1,8,-3],5));
// 8
The 8 combos from the above example are:
1,2,3,2,-3
1,2,2
1,3,1
2,3
2,3,2,1,-3
2,2,1
3,2
8,-3
From your example, I assumed that the sum of two consecutive elements should be the sum to qualify.
function subArrayCnt(arr, sum) {
let outputArr = [];
for(var i=0; i<arr.length; i++){
if(arr[i]+arr[i+1]==sum){
let obj = {l:arr[i],r:arr[i+1]};
outputArr.push(obj);
}
};
return outputArr.length;
};
Try this approach:
function subArrayCnt(arr, sum){
var count = 0;
for(var i = 0; i < arr.length-1; i++){
for(var n = i+1; n < arr.length; n++){
if(arr[i] + arr[n] == sum){
count++;
}
}
}
return count;
}
console.log(subArrayCnt([1,2,3,2,1,8,-3],5));
// 3
You can do that using nested loop. This will get all the possible adjacent sums and then you can compare that sum with the given sum and increase count.
function func(arr,sum){
if(!Array.isArray(arr)) return 0;
let count = 0;
let cur = 0;
for(let i = 0;i<arr.length-1;i++){
cur = arr[i];
for(let j = i+1;j<arr.length;j++){
cur += arr[j];
if(cur === sum){
count++;
break;
}
if(cur > sum) break;
}
}
return count+'';
}
console.log(func([1,2,3,2,1,8,-3],5)) //3
console.log(func([1,2,3,4],10)) //1
Try this:
<script>
function subArray(arr,sum)
{
var subArray=new Array();
count=0;
for(var i=0;i<arr.length;i++)
{
if(arr[i]+arr[i+1]==sum)
{
subArray[count]=[arr[i],arr[i+1]]
count++;
}
}
return subArray;
}
console.log(subArray([1,2,3,2,1,8,-3],5));
</script>
Try this:
I wrote this function. It fulfill the requirement of "The answer should be valid for any given input".
function getSubArrayCount(arr, sum){
if(!Array.isArray(arr)) return 0;
var len = arr.length;
var count = 0;
for(var i = 0; i < len; i++){
var n = 0;
for(var j = i; j < len; j++){
n += arr[j];
if(n === sum) {
count++;
break;
}
}
}
return count;
}
getSubArrayCount([1,2,3,2,1,8,-3],5);
EDITED:
Can someone help me with the problem below further. I have a class and an array inside the class. I want now use a for loop to sum the length of the previous array length, but for each iteration. If i == 1 I want sum the length of arr[0].x.length, If i == 2 I want sum the length of arr[0].x.length+arr[1].x.length, ect. It will be a lot of code to check each iteration.
Is there a simple way to do this? Instead allways use a new line like
if (i == 1) n = n + arr[i-1].x.length;
if (i == 2) n = n + arr[i-1].x.length+arr[i-2].x.length;
if (i == 3) n = n + arr[i-1].x.length+arr[i-2].x.length+arr[i-3].x.length;
function Class() {
var x = [];
}
for (var i = 0; i < 9; i++) {
arr[i] = new Class();
}
I add 4 items to each object.
arr[0].x.push(...)
arr[0].x.push(...)
...
arr[1].x.push(...)
arr[1].x.push(...)
...
var n = 0;
for (var i = 0; i < arr.length; i++) {
if (i == 1) {
n = n + arr[i-1].x.length;
} else if (i == 2) {
n = n + arr[i-1].x.length+arr[i-2].x.length;
} else if (i == 3) {
n = n + arr[i-1].x.length+arr[i-2].x.length+arr[i-3].x.length;
}
// ect.
}
You could use reduce to get a total of all the lengths of your sub-arrays. For example:
const arrs = [[1, 2, 3], [4, 5, 6]];
const sum = arrs.reduce((acc, arr) => acc += arr.length, 0);
console.log(sum);
// 6
Just nest the loop two times: go over the indexes once then go up to that index from 0 in an inner loop:
for (var i = 0; i < arr1.length; i++) {
for(var j = 0; j <= i; j++) {
n = n + arr1[j].length;
}
}
Edit: benvc's answer is what you are looking for if you want to use reduce.
var arr = [[1,2,3], [4,5,6], [7]];
var n = 0;
for (var i = 0; i < arr.length; i++){
n += arr[i].length;
}
console.log(n);
What is the most JS-style way to solve the following problem?
Given an array A, find all arrays B, such that for i <= A.length: B[i] <= A[i]. Example of what I expect:
#Input
A = [1,2,0]
#Output
B = [[0,0,0],
[1,0,0],
[1,1,0],
[1,2,0],
[0,1,0],
[0,2,0]]
In Python I used:
B = [[]];
for t in [range(e+1) for e in A]:
B = [x+[y] for x in B for y in t]
Thanks in advance!
Use the following code (any loop for one item of the array a):
var a = [1, 2, 0], b = [];
for (var i = 0; i < a[0]; i++) {
for (var j = 0; j < a[1]; j++) {
for (var k = 0; k <= a[2]; k++) {
b.push([i, j, k]);
}
}
}
If you know the numebr of items in the array a only on runtime, use the following recursive function:
function fillArray(source, dest, recursionLevel, tempArr) {
if (recursionLevel >= source.length) {
dest.push(tempArr);
return;
}
for (var i = 0; i <= source[recursionLevel]; i++) {
var tempArr2 = tempArr.slice(); // Copy tempArr
tempArr2.push(i);
fillArray(source, dest, recursionLevel + 1, tempArr2);
}
}
fillArray(a, b, 0, []);
I found this solution. I'm sure it can be coded in a much nicer way. However, it works and I hope you find it useful
all_combinations(A){
var B = [];
for (var i = 0; i < A[0] + 1; i++) {
B.push([i]);
}
for (var i = 1; i < A.length; i++) {
var _tmp_array = [];
for (var j = 0; j < A[i] + 1; j++) {
for (var k = 0; k < B.length; k++) {
var _new_element = B[k].concat([j]);
_tmp_array.push(_new_element);
}
}
B = _tmp_array;
}
return B;
}