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);
The aim of the bellow function is to output only the non-unique items from an array that is passed as an argument:
"use strict";
function nonUnique(data){
var tab = [];
for(var d = 0; d < data.length; d++) {
if(typeof(data[d]) == "string"){
tab[d] = data[d].toUpperCase();
}
else{
tab[d] = data[d];
}
}
var count = 0;
var tab_non_unique = [];
var tab_unique = [];
for(var i = 0; i < tab.length; i++){
for(var j = 0; j < tab.length; j++){
if(tab[i] == tab[j]){
count ++;
}
if(count > 1){
tab_non_unique.push(tab[i]);
count = 0;
break;
}
if (count == 1) {
tab_unique.push(tab[i]);
}
}
}
return tab_non_unique;
}
I have tested the function by calling it on different arrays but somehow on
nonUnique([1, 2, 3, 4, 5]);
it fails by returning:
=> [ 2, 4 ]
I don't understand what in my code causes 2 and 4 to raise the counter higher than 1 and thus end up in the tab_non_unique array. Any help would be greatly appreciated, thanks.
The problem is that you reset count only if a non-unique is found. But it should be reset always when starting with a new number.
So put the count=0 at the top of the loop.
for (var i = 0; i < tab.length; i++) {
count = 0;
for (var j = 0; j < tab.length; j++) {
if (tab[i] == tab[j]) {
count++;
}
if (count > 1) {
tab_non_unique.push(tab[i]);
break;
}
if (count == 1) {
tab_unique.push(tab[i]);
}
}
}
OBJECTIVE
I am trying to highlight the dfferences between two arrays. Please note that arr1 and arr2 will vary in length and have multiple types present (strings and numbers).
MY CODE
function diff(arr1, arr2) {
var diffArr = [];
if (arr1.length >= arr2.length) {
for (var i = 0; i < arr1.length; i++){
if (arr2.indexOf(arr1[i]) < 0) {
diffArr.push(arr1[i]);
}
}
} else {
for (var j = 0; j < arr2.length; j++){
if (arr1.indexOf(arr2[j]) < 0) {
diffArr.push(arr2[j]);
}
}
}
return diffArr;
}
ISSUES
diff([1, 2, 'cat', 'fish'], [1, 2, 3,'dog']); //returns only ['cat', 'fish']
I am pretty sure that my code is only returning the duplicates in one of the arrays via diffArr.push (even if there are unique values in both arrays). However, I am unsure how to overcome this.
My references
Removes Duplicates from Javascript Arrays
Removed Duplicates from an Array Quickly
Javascript Array Difference
Your code currently only crawls through one array (let's call it A) and pushes in all the A values that don't exist in B. You never go the other way and push in the B values that don't exist in A. There's also no need to have different behavior based on which array is longer. Here is the final answer in a simple way:
function diff(arr1, arr2) {
var diffArr = [];
for (var i = 0; i < arr1.length; i++) {
if (arr2.indexOf(arr1[i]) < 0) diffArr.push(arr1[i]);
}
for (var j = 0; j < arr2.length; j++) {
if (arr1.indexOf(arr2[j]) < 0) diffArr.push(arr2[j]);
}
return diffArr;
}
And in a slightly more functional way:
function diff(arr1, arr2) {
var elsIn1Not2 = arr1.filter(function(el){ return arr2.indexOf(el) < 0; });
var elsIn2Not1 = arr2.filter(function(el){ return arr1.indexOf(el) < 0; });
return elsIn1Not2.concat(elsIn2Not1);
}
Both functions return [ 'cat', 'fish', 3, 'dog' ] for your example.
function diff(arr1, arr2) {
var diffArr = {};
if (arr1.length >= arr2.length) {
for (var i = 0; i < arr1.length; i++){
if (arr2.indexOf(arr1[i]) < 0) {
diffArr[arr1[i]] = 1;
}
}
} else {
for (var j = 0; j < arr2.length; j++){
if (arr1.indexOf(arr2[j]) < 0) {
diffArr[arr2[j]] = 2;
}
}
}
return diffArr.keys();
}
I'd like to check which elements are equal in my two arrays, but can't get it working.
This is my code:
for (var i; i < bombs.length; i++) {
for (var j; j < bombsDb.length; j++) {
if (bombs[i].name === bombsDb[j].address) {
console.log(bombs[i].name);
} else {
console.log("non-equal elements");
}
}
}
So the first array contains objects from the google places api and the second one contains data from my database.
Thanks in advance!
You have to initialize i and j;
for (var i = 0; i < bombs.length; i++) {
for (var j = 0; j < bombsDb.length; j++) {
if (bombs[i].name === bombsDb[j].address) {
console.log(bombs[i].name);
} else {
console.log("non-equal elements");
}
}
}
Comparing can also be done using the .not selector from jquery. Check this:
var a = [1,2,3,4,5,6];
var b = [4,5,6,7,8,9];
$(a).not( $(a).not(b).get() ).get();
This will return the following array
[4,5,6]
You are missing the initial assignment to i and j in your for loop.
// here
// v
for (var i = 0; i < bombs.length; i++) {
// your loop
}
This causes the comparision to return false in the first iteration of the loop since undefined < bombs.length always return false, so it will not proceed.
I have an array of objects called seasons of length 300, and I trying to search through a certain property "Date" and add it to an array if it has not been found before. So far I have
var day=[];
for (var i=1; i<300; i++) {
var found=false;
for (var j=0; j<day.length; j++) {
if (day[j]==seasons[i]["Date"]) {
found=true;
break;
}
if (!found) {
day[day.length]=seasons[i]["Date"];
}
}
}
I'm not too sure where this is going wrong, and would appreciate some help. Thanks
You break out of the inner for-loop, so the if (!found) block is never executed.
Just put it after the inner loop:
for (var i = 1; i < 300; i++) {
var found = false;
for (var j = 0; j < day.length; j++) {
if (day[j] == seasons[i]["Date"]) {
found = true;
break;
}
}
if (!found) {
day[day.length] = seasons[i]["Date"];
}
}
Or do it in the if-block:
for (var i = 1; i < 300; i++) {
for (var j = 0; j < day.length; j++) {
if (day[j] == seasons[i]["Date"]) {
day[day.length] = seasons[i]["Date"];
break;
}
}
}
I guess the latter solution is easier to understand.