Find largest d in array such that a + b + c = d - javascript

Task
You are given a sorted integer array arr. It contains several unique integers(negative, positive, or zero).
Your task is to find the largest d such that a + b + c = d, where a, b, c, and d are distinct elements of arr. If no such an element d found, return null.
Example:
For arr = [2,3,5,7,12], the output should be 12 (this array passes my function correctly)
For arr = [-100,-1,0,7,101], the output should be 0 (this one does not pass)
I could manage the positive numbers check but my function miserably fails with negatives
function findD(arr) {
myArr = arr.sort((a, b) => b - a);
for (var i = 0; i < myArr.length; i++) {
for (var k = i + 1; k < myArr.length - 2; k++) {
var j = k + 1,
d = myArr.length - 1;
while (j < d) {
let sum = myArr[k] + myArr[j] + myArr[d];
if (sum == myArr[i]) {
return myArr[i];
} else if (sum < myArr[i]) {
d--;
} else if (sum > myArr[i]) {
j++;
}
}
}
}
return null
}
how to handle negative values in the array?

Let's imagine there's an array like [-2, -1, 0, 3].
Then, after sorting it in the descending order as per your algorithm it will be [3, 0, -1, -2]. Obviously, your algorithm will pick only 3 as you assume d must be larger than numbers at the remaining 3 positions. That's wrong, of course. You shouldn't assume that a, b and c are necessarily less than d. That's why you must check other cases when d occupies all possible positions in relation to a,b,c. So, first consider a brute force approach that will have O(n^4) time and O(1) space complexity:
...
for (var i = myArr.length; i >= 0 ; i--) {
for (var k = 0; k < myArr.length; k++) {
if (k == i) {
continue
}
for (var j = k + 1; j < myArr.length; j++) {
if (j == i) {
continue
}
for (var d = j + 1; d < myArr.length; d++) {
if (d == i) {
continue
}
if (myArr[i] == myArr[k] + myArr[j] + myArr[d]) {
return myArr[i]
}
}
}
}
}
return null
...
But this problem can be solved in O(n^2) time and O(n^2) space.
First we should realise that a + b = d - c.
So, for the given array arr and every pair of indices i,j: i<j we store arr[i] + arr[j] (a + b) as a key and pair i,j as an item of a value (the value is a list of pairs of indices) in sumsMap. The value must be a list because there can be several pairs of indices corresponding to the same sum a + b.
Then, go through each pair of indices again k,l and check if a key arr[l] - arr[k] (d - c) or arr[k] - arr[l] (c - d) exists in sumsMap. If it does and indices l,k are different from the ones in sumsMap[s] then update the maximum element if it's lower than arr[l].
function solve(arr) {
var sumsMap = {}
for (var i = 0; i < arr.length; i++) {
for (var j = i + 1; j < arr.length; j++) {
var sum = arr[i] + arr[j]
// several pairs of indices can correspond to the same summ so keep all of them
var mappedIndices = sumsMap[sum]
if (typeof mappedIndices == "undefined") {
mappedIndices = []
}
let pair = {}
pair.first = i
pair.second = j
mappedIndices.push(pair)
sumsMap[sum] = mappedIndices
}
}
var maxD = Number.MIN_SAFE_INTEGER
for (var k = 0; k < arr.length; k++) {
for (var l = 0; l < arr.length; l++) {
mappedIndices = sumsMap[arr[l] - arr[k]]
if (mappedIndices != undefined) {
// in the worst case, 4 pairs of indices may contain k or l but the fifth one won't as numbers in the array are unique and hence the same index can occur only twice
var steps = Math.min(5, mappedIndices.length)
for (var s = 0; s < steps; s++) {
var pair = mappedIndices[s]
if (pair.first != k && pair.first != l && pair.second != k && pair.second != l) {
maxD = Math.max(maxD, arr[l])
}
}
}
}
}
if (maxD == Number.MIN_VALUE) {
return -1
} else {
return maxD
}
}
document.write(solve([-100,-1,0,7,101] ))
document.write("<br>")
document.write(solve([-93,-30,-31,-32] ))

I translated the function Renaldo suggested from https://www.geeksforgeeks.org/find-largest-d-in-array-such-that-a-b-c-d/ to JavaScript for you.
function findLargestd(S, n){
var found = false;
// sort the array in
// ascending order
S.sort((a, b) => a - b);
// iterating from backwards to
// find the required largest d
for(var i = n - 1; i >= 0; i--){
for(var j = 0; j < n; j++){
// since all four a, b, c,
// d should be distinct
if(i == j){
continue;
}
for(var k = j + 1; k < n; k++){
if(i == k){
continue;
}
for(var l = k + 1; l < n; l++){
if(i == l){
continue;
}
// if the current combination
// of j, k, l in the set is
// equal to S[i] return this
// value as this would be the
// largest d since we are
// iterating in descending order
if(S[i] == S[j] + S[k] + S[l]){
found = true;
return S[i];
}
}
}
}
}
//if not found, return 0
if(found === false){
return 0;
}
}

Related

Fill matrix with snake pattern using javascript

I want to fill in a 2D array of numbers with snake pattern, I tried this algorithm but the result it's not the expected:
function fill2d(c,l) {
var arr = new Array[l][c];
let counter = 0;
for (let col = 0; col < arr.l; col++) {
if (col % 2 == 0) {
for (let row = 0; row < arr.l; row++) {
arr[row][col] = counter++;
}
} else {
for (let row = arr.length - 1; row >= 0; row--) {
arr[row][col] = counter++;
}
}
}
return arr;
}
fill2d(4,4)
some thing like that :
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13
Okay so basically all you need is to traverse row-by-row but alternating between left-to-right and right-to-left. Here's my solution:
function fill2d(c, l) {
let arr = new Array(l);
for (var i = 0; i < l; i++) {
arr[i] = new Array(c);
}
let count = 1;
for (let i = 0; i < l; i++) {
console.log("i: ", i);
let right_to_left = i % 2;
for (let j = (right_to_left * (l - 1));
(right_to_left ? (j >= 0) : (j < c)); j += (right_to_left ? -1 : 1)) {
console.log("j: ", j);
arr[i][j] = count++;
}
}
return arr;
}
console.log(fill2d(4, 4));
Also, you weren't allocating a 2d array properly, you need to allocate a 1d array first and then allocate an array for each of the elements of that array.
Note: I added logs for each i and j so that you can see how the array is traversed.

Why these two loops return different results?

Problem statement
Given an array arr, find element pairs whose sum equal the second
argument arg and return the sum of their indices.
Disclaimer, I am not asking for the solution of this problem statement, but about the confusion between the following two loops I tried creating, whose functionality is almost exactly similar but consoling different outputs.
First Loop
function pairwise(arr, arg) {
const indexOfPair = []
for ( let i = 0; i < arr.length -1; i++){
for (let j = i + 1; j < arr.length -1; j++ ){
let sum = arr[i] + arr[j]
if ( sum === arg){
indexOfPair.push(arr.indexOf(arr[i]), arr.indexOf(arr[j]))
}
else {
continue
}
}
}
console.log(indexOfPair)
console.log(indexOfPair.reduce((a, b) => a + b, 0))
}
pairwise([1,4,2,3,0,5], 7);
Console Output:[1,3] & 4
Second Loop
function pairwise(arr, arg) {
const indexOfPair = []
for ( let i = arr.length - 1; i >= 0 ; i--){
for (let j = i -1; j >= 0; j--){
let sum = arr[i] + arr[j]
if ( sum === arg){
indexOfPair.push(arr.indexOf(arr[i]), arr.indexOf(arr[j]))
}
}
}
console.log(indexOfPair)
console.log(indexOfPair.reduce((a, b) => a + b, 0))
}
pairwise([1,4,2,3,0,5], 7);
Console output: [5,2,3,1] & 11 -> This is the expected output and I am not getting why these two loops are returning different outcomes.
You're not getting to the last entry in arr.
for ( let i = 0; i < arr.length - 1; i++){
for (let j = i + 1; j < arr.length - 1; j++ )
should be
for ( let i = 0; i <= arr.length - 1; i++){
for (let j = i + 1; j <= arr.length - 1; j++ )

Multiple array intersection in javascript

How to write in javascript(w/wth JQuery) to find values that intersect between arrays?
It should be like
var a = [1,2,3]
var b = [2,4,5]
var c = [2,3,6]
and the intersect function should returns array with value {2}. If possible it could applicable for any number of arrays.
Thanks
There are many ways to achieve this.
Since you are using jQuery I will suggest use grep function to filter the value that are present in all three array.
var a = [1, 2, 3]
var b = [2, 4, 5]
var c = [2, 3, 6]
var result = $.grep(a, function(value, index) {
return b.indexOf(value) > -1 && c.indexOf(value) > -1;
})
console.log(result)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Explanation: Loop over any array and filter out the values that are present in other array.
Update (for multimidensional array):
Concept - flatten the multidimensional array that is transform [[1,2],3,4] to [1,2,3,4] and then use the same logic used for single dimensional array.
Example:
var a = [
[1, 4], 2, 3
]
var b = [2, 4, 5]
var c = [2, 3, 6, [4, 7]]
//flatten the array's
//[1,4,2,3]
var aFlattened = $.map(a, function(n) {
return n;
})
//[2,4,5]
var bFlattened = $.map(b, function(n) {
return n;
})
//[2,3,6,4,7]
var cFlattened = $.map(c, function(n) {
return n;
})
var result = $.grep(aFlattened, function(value) {
return (bFlattened.indexOf(value) > -1 && cFlattened.indexOf(value) > -1);
});
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
// First this is how you declare an array
var a = [1,2,3];
var b = [2,4,5];
var c = [2,3,6];
// Second, this function should handle undetermined number of parameters (so arguments should be used)
function intersect(){
var args = arguments;
// if no array is passed then return empty array
if(args.length == 0) return [];
// for optimisation lets find the smallest array
var imin = 0;
for(var i = 1; i < args.length; i++)
if(args[i].length < args[imin].length) imin = i;
var smallest = Array.prototype.splice.call(args, imin, 1)[0];
return smallest.reduce(function(a, e){
for(var i = 0; i < args.length; i++)
if(args[i].indexOf(e) == -1) return a;
a.push(e);
return a;
}, []);
}
console.log(intersect(a, b, c));
First of all '{}' means Object in JavaScript.
Here is my suggestion.(this is another way of doing it)
// declarations
var a = [1,2,3];
var b = [2,4,5];
var c = [2,3,6];
// filter property of array
a.filter(function(val) {
if (b.indexOf(val) > -1 && c.indexOf(val) > -1)
return val;
});
what it does is it checks for each element in array 'a' and checks if that value is present in array 'b' and array 'c'. If it is true it returns the value. Simple!!!. The above code should work for String as well but it wouldn't work for IE < 9, so be careful.
// Intersecting 2 ordered lists of length n and m is O(n+m)
// This can be sped up by skipping elements
// The stepsize is determined by the ratio of lengths of the lists
// The skipped elements need to be checked after skipping some elements:
// In the case of step size 2 : Check the previous element
// In case step size>2 : Binary search the previously skipped range
// This results in the best case complexity of O(n+n), if n<m
// or the more propable complexity of O(n+n+n*log2(m/n)), if n<m
function binarySearch(array, value, start = 0, end = array.length) {
var j = start,
length = end;
while (j < length) {
var i = (length + j - 1) >> 1; // move the pointer to
if (value > array[i])
j = i + 1;
else if (value < array[i])
length = i;
else
return i;
}
return -1;
}
function intersect2OrderedSets(a, b) {
var j = 0;
var k = 0;
var ratio = ~~(b.length / a.length) - 1 || 1;
var result = [];
var index;
switch (ratio) {
case 1:
while (j < a.length) {
if (a[j] === b[k]) {
result.push(a[j]);
j++;
k++;
} else if (a[j] < b[k]) {
while (a[j] < b[k]) j++;
} else {
while (b[k] < a[j]) k++;
if (k >= b.length) break;
}
}
break;
case 2:
while (j < a.length) {
if (a[j] === b[k]) {
result.push(a[j]);
j++;
k++;
} else if (a[j] < b[k]) {
while (a[j] < b[k]) j++;
} else {
while (b[k] < a[j]) k += 2;
if (k - 1 >= b.length) break;
if (a[j] <= b[k - 1]) k--;
}
}
break;
default:
while (j < a.length) {
if (a[j] === b[k]) {
result.push(a[j]);
j++;
k++;
} else if (a[j] < b[k]) {
while (a[j] < b[k]) j++;
} else {
while (b[k] < a[j]) k += ratio;
index = binarySearch(b, a[j], k - ratio + 1, k + 1 < b.length ? k + 1 : b.length - 1);
if (index > -1) {
result.push(a[j]);
j++;
k = index + 1;
} else {
j++;
k = k - ratio + 1;
}
if (k >= b.length) break;
}
}
}
return result;
}
function intersectOrderedSets() {
var shortest = 0;
for (var i = 1; i < arguments.length; i++)
if (arguments[i].length < arguments[shortest].length) shortest = i;
var result = arguments[shortest];
for (var i = 0, a, b, j, k, ratio, index; i < arguments.length; i++) {
if (result.length === 0) return result;
if (i === shortest) continue;
a = result;
b = arguments[i];
result = intersect2OrderedSets(a, b);
}
return result;
}
How to use:
intersectOrderedSets(a,b,c);

finding prime numbers in an array from 1-200

A math problem describes a list of numbers from 1-200, you must skip the number 1, and then for each number that follows, remove all multiples of that number from the list. Do this until you have reached the end of the list.
Here's what I have so far.
var x = []; // creating an array called x with zero numbers
for ( var i = 1; i <= 200; i++ ){
x.push(i);
};
// x now should have an array that contains the intergers from 1-200.
//looping through the array.
for ( var i = 0; i <= x.length; i++ ){ //going from 1-200
if (x[i] == 1){
continue; // skipping 1
} else {
for ( var n = i+1; n <= i; n++){ // take the number 1 index bigger than x[i]
if ( n % i == 0){ //find if the modulus of x[n] and x[i] is zeor, meaning it is divisible by x[i]
x.shift(); //remove that number
console.log(x[n]);
} else {
continue;
}
}
}
};
Instead of adding number 1 to 200 and then removing non prime numbers, try only putting prime numbers into that list. Since this is a school problem (I'm guessing) I don't want to give you the answer, but if you have more questions I can answer.
Also your nested loop will never run, go over that logic again.
Another version (a minute too late, as always ;-), one with comments
// lil' helper
function nextSet(a,n){
while(a[n] == 0) n++;
return n;
}
function setPrimes(a,n){
var k, j, r;
n = n + 1;
k = n;
while(k--)a[k] = 1;
a[0] = 0; // number 0
a[1] = 0; // number 1
// get rid of all even numbers
for(k = 4; k < n; k += 2) {
a[k] = 0;
}
// we don't need to check all of the numbers
// because sqrt(x)^2 = x
r = Math.floor(Math.sqrt(n));
k = 0;
while(k < n){
k = nextSet(a,k+1);
// a test if we had them all
if(k > r){
break;
}
// unmark all composites
for(j = k * k; j < n; j += 2*k){
a[j] = 0;
}
}
return a;
}
function getPrimes(n){
// we know the size of the input
var primearray = new Array(n);
// we don't know the size of the output
// prime-counting is still an unsolved problem
var output = [];
setPrimes(primearray, n);
for(var i = 0; i < n; i++){
if(primearray[i] == 1){
output.push(i);
}
}
return output;
}
getPrimes(200);
You can go through a full implementation of that algorithm at another primesieve.
Here is, I believe, a working example of what you want:
function isPrime(num){
if(num < 2){
return false;
}
for(var i=2,l=Math.sqrt(num); i<=l; i++){
if(num % i === 0){
return false;
}
}
return true;
}
function range(f, t){
for(var i=f,r=[]; i<=t; i++){
r.push(i);
}
return r;
}
function primeRange(from, to){
var a = range(from, to), r = [];
for(var i=0,l=a.length; i<l; i++){
var v = a[i];
if(isPrime(v)){
r.push(v);
}
}
return r;
}
var prmRng = primeRange(1, 200);
console.log(prmRng);
I solved it this way:
let numbers = new Array();
for (let i = 1; i <= 200; i++) {
numbers.push(i);
}
let primeNumbers = (num) => {
let prime = new Array();
for(let i = 0; i < num.length; i++) {
let count = 0;
for (let p = 2; p <= num[i]; p++) {
if(num[i] % p === 0 && num[i] !== 2) {
count++;
} else {
if(num[i] === 2 || count === 0 && num[i]-1 === p) {
prime[i] = num[i];
}
}
}
}
return prime.filter(Boolean);
}
console.log(primeNumbers(numbers));

Universal function for getting all unique pairs, trebles etc from an array in javascript

I am looking to create a function in javascript, which would allow me to pass a long array, together with one argument.
what I'm looking for is something like this:
var ar = [1,2,3,4];
var pairs = superAwesomeFunction(ar,2) //=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]];
var trebles = superAwesomeFunction(ar,3) //=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]
ideally, the function would have no limit on the folding argument.
I wrote a piece of code that looks like this, which is working fine, but it's not really useful as it isn't universal, and I would need a lot of such functions, which seems silly.
getAll2Folds: function (ar) {
var combinations = [],
numOdds = ar.length;
for (var i = 0; i < numOdds; i++) {
for (var j = i + 1; j < numOdds; j++) {
combinations.push([ar[i], ar[j]]);
}
}
return combinations;
},
getAll3Folds: function (ar) {
var combinations = [],
numOdds = ar.length;
for (var i = 0; i < numOdds; i++) {
for (var j = i + 1; j < numOdds; j++) {
for (var k = j + 1; k < numOdds; k++) {
combinations.push([ar[i], ar[j], ar[k]]);
}
}
}
return combinations;
};
},
... (not so great :|)
getAll8Folds: function (ar) {
var combinations = [],
numOdds = ar.length;
for (var i = 0; i < numOdds; i++) {
for (var j = i + 1; j < numOdds; j++) {
for (var k = j + 1; k < numOdds; k++) {
for (var l = k + 1; l < numOdds; l++) {
for (var m = l + 1; m < numOdds; m++) {
for (var n = m + 1; n < numOdds; n++) {
for (var o = n + 1; o < numOdds; o++) {
for (var p = o + 1; p < numOdds; p++) {
combinations.push([ar[i], ar[j], ar[k], ar[l], ar[m], ar[n], ar[o], ar[p]]);
}
}
}
}
}
}
}
}
return combinations;
}
I'm free to use underscore, jquery or whatever tool i want, but can't find an elegant solution, which would also be performant. ideas?
Thanks
Basically combine() takes an array with the values to combine and a size of the wanted combination results sets.
The inner function c() takes an array of previously made combinations and a start value as index of the original array for combination. The return is an array with all made combinations.
The first call is allways c([], 0), because of an empty result array and a start index of 0.
var arr = [1, 2, 3, 4, 5, 6, 7];
function combine(a, size) {
function c(part, start) {
var result = [], i, l, p;
for (i = start, l = arr.length; i < l; i++) {
// get a copy of part
p = part.slice(0);
// add the iterated element to p
p.push(a[i]);
// test if recursion can go on
if (p.length < size) {
// true: call c again and concat it to the result
result = result.concat(c(p, i + 1));
} else {
// false: push p to the result, stop recursion
result.push(p);
}
}
return result;
}
return c([], 0);
}
out(JSON.stringify(combine(arr, 2), null, 4), true);
out(JSON.stringify(combine(arr, 3), null, 4), true);
out(JSON.stringify(combine(arr, 4), null, 4), true);
out(JSON.stringify(combine(arr, 5), null, 4), true);
out(JSON.stringify(combine(arr, 6), null, 4), true);
// just for displaying the result
function out(s, pre) {
var descriptionNode = document.createElement('div');
descriptionNode.className = 'description';
if (pre) {
var preNode = document.createElement('pre');
preNode.innerHTML = s + '<br>';
descriptionNode.appendChild(preNode);
} else {
descriptionNode.innerHTML = s + '<br>';
}
document.getElementById('out').appendChild(descriptionNode);
}
<div id="out"></div>

Categories

Resources