Created
October 22, 2019 14:01
-
-
Save daubattu/dde5c99dc947fb99e798798b24c50de2 to your computer and use it in GitHub Desktop.
[Hackerrank] Solution of Divisible Sum Pairs in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function divisibleSumPairs(n, k, ar) { | |
let result = 0; | |
for(let i = 0; i < n - 1; i++) { | |
result += ar.slice(i + 1, n).filter((item, index) => { | |
if ((item + ar[i]) % k === 0) { | |
return item; | |
} | |
}).length; | |
} | |
return result; | |
} |
instead of .filter(), you can use regular .forEach() since we don't need the return value of .filter()
function divisibleSumPairs(n, k, ar) {
let tempArr = [];
let finalArr = [];
for (let i = 0; i < ar.length; i++) {
tempArr.push(ar.slice(i, ar.length));
}
tempArr.forEach((el) => {
for (let i = 1; i < el.length; i++) {
if ((el[0] + el[i]) % k === 0) {
finalArr.push([el[0], el[i]]);
}
}
});
return finalArr.length;
// end of function
}
function divisibleSumPairs(n, k, ar) { // Write your code here
let counter = 0 for(let i = 0; i < n; i++) { for(let j = i + 1; j < n; j++ ) { let sum = ar[i] + ar[j] if(sum % k === 0) { counter++ } } } return counter
}
this does not work for single element array
for(let i = 0; i < n; i++) {
for(let j = i + 1; j < n; j++ ) {
let sum = ar[i] + ar[j]
if(sum % k === 0) {
counter++
}
}
this does not work for single element ... the following code will work
function divisibleSumPairs(n, k, ar) {
// Write your code here
var sum = 0;
var pair = 0;
// for single element array where the element is divisible by k
if(n==1 && (ar[0]%k == 0)){
pair = 1;
}
else if (n > 1){
for(i = 0; i<n; i++){
// for adding the values
for(j = i+1; j<n; j++){
sum = ar[i] + ar[j];
if(sum % k == 0){
pair++;
// console.log("I am pair", pair);
}
}
}
}
else {
pair = 0;
}
return pair;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
// no need for n inside ar.slice
// To avoid confusion refer https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice