I need to find the highest possible sum of numbers in an array passed to a function that can be divided with no remainder.
I am struggling to think of a way of iterating through an array of elements adding up all the possibilities and dividing by the parameter k which is the number for the division.
I thought of using a for loop and then passing the result to a variable on each iteration.
The part I can't get my head around is how to add all the possible combinations of the numbers in the array. As I can add them sequentially from the start of the array to the last element but not in all combinations such as element at index 0, element at index 3 etc.
I am fairly new to coding, explanations of how you could tackle the iteration challenge I have would be much appreciated.
function luckyCandies(prizes, k) {
let sum = 0;
let remainder = 0;
let maxCandies = 0;
let highestNumber = 0;
prizes.sort(function(a, b) {
return b - a;
});
for (let i = 0; i < prizes.length; i++) {
sum = sum + prizes[i];
}
for (let i = 0; i < prizes.length; i++) {
if (sum % k == 0) {
sum = sum - prizes[i];
}
}
console.log(sum);
return sum;
}
Implemented this solution for your use case based on the answers in this.
In the given link the solutions are for the highest possible sum of numbers given the divisible 3 but it won't be a problem since there is a proper in detailed explanation.
const maxSumDivByNo = (A, no) => {
const K = Array(no).fill().map((v,i) => 0);
for (let x of A) {
let pre = [...K]; // create current from previous 🤔
for (let y of pre)
K[(x + y) % no] = Math.max(K[(x + y) % no], x + y); // add A[i] (ie. x) onto each previous bucket and update each current bucket to max of itself and the current sum (x + y)
}
return K[0]; // max sum of all N items of A which is evenly divisible by no 🎯
};
const A = [1, 2, 3, 4, 5];
const no = 5;
console.log(maxSumDivByNo(A, no)); // --> 15
const A1 = [1, 6, 2, 9, 5];
const no1 = 8
console.log(maxSumDivByNo(A1, no1)); // --> 16
My approach to this problem is most likely flawed, but I'm so close to finishing the solution. Given the numbers 2 and 10, I must find the least common multiple of the two numbers, plus the numbers within their range.
(2,3,4,5,6,7,8,9,10)
I've created a function that is used to return the prime factors of every number, and push them into an array. This is where I'm lost. I don't know how to reduce/filter out the excessive prime numbers.
I should end up multiplying 2*2*2*3*3*5*7, but filtering unique numbers would result me with 2*3*5*7, or 2*3*2*5*2*3*7*2*3*2*5 if I filtered the numbers before the array was flattened.
function smallestCommons(arr) {
// factorize a number function
function factorization(num) {
let primesArr = [];
// i is what we will divide the number with
for (let i = 2; i <= Math.sqrt(num); i++) {
// if number is divisible by i (with no remainder)
if (num % i === 0) {
// begin while loop that lasts as long as num is divisible by i
while (num % i === 0) {
// change the value of num to be it divided by i
num = num / i;
// push the prime number used to divide num
primesArr.push(i);
}
}
}
// if num is not the number 1 after the for loop
// push num to the array because it is also a prime number
if (num != 1) {
primesArr.push(num);
}
return primesArr;
}
// sort from lowest to highest
arr.sort((a,b) => a - b);
let range = [];
let primeFacts = [];
// push range of numbers to fullArr
for (let i = arr[0]; i <= arr[1]; i++) {
range.push(i);
}
console.log(range); // [2,3,4,5,6,7,8,9,10]
// loop for iterating through range numbers
for (let i = 0; i < range.length; i++) {
// push the prime factors of each range number
primeFacts.push(factorization(range[i]));
}
console.log(primeFacts);
// flatten the array, then return the product of numbers
return primeFacts
.reduce((newArray, arr) => newArray = [...newArray,...arr] ,[])
.reduce((product, num) => product *= num);
};
console.log(smallestCommons([2,10]));
OUTPUT
[ 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
[ [ 2 ],[ 3 ],[ 2, 2 ],[ 5 ],[ 2, 3 ],[ 7 ],[ 2, 2, 2 ],[ 3, 3 ],[ 2, 5 ] ]
3628800
How do I emulate this and add it in my code? ->
Example of Table I want to emulate
Take this as a table of prime factors and their degrees:
2 3 5 7
2 1
3 1
4 2
5 1
6 2 2
7 1
8 3
9 2
10 1 1
For the LCM, take the largest degree in each column:
3 2 1 1
Multiply those powers together; that's your answer:
2^3 * 3^2 * 5^1 * 7^1
EXTENSION
To get the GCD, take the smallest degree in each column (including 0).
Do you have to use prime factorization, or do you just need the lowest common multiples? Because there is another, much more efficient algorithm for it, called the Euclidean algorithm. You can read up on it here:
http://www.programming-algorithms.net/article/42865/Least-common-multiple
http://www.programming-algorithms.net/article/43434/Greatest-common-divisor
(note: calculating the LCM via the Euclidean algorithm requires the GCD, but there's a Euclidean algorithm for that too)
Now, the above mentioned algorithm works for two numbers, but I think (haven't mathematically verified it tho, so you need to check this yourself) you can just use left reduction.
The end result would look something like this:
var getLCM = (a, b) => {
// Implement Euclidean LCM algorithm here...
};
var getTotalLCM = (numbers) => {
return numbers.reduce((totalLCM, next) => getLCM(totalLCM, next), 1);
}
var result = getTotalLCM([ 2, 3, 4, 5, 6, 7, 8, 9, 10 ]);
What getTotalLCM will do here, is it will calculate the LCM of 1 and 2 (1 because that's the initial accumulator value we passed to reduce()), which is of course 2. Then it calculates the LCM of 2 and 3, which is 6; then 6 and 4, which is 12, then 12 and 5, which is 60, then 6 and 60, which is still 60, and so on. I think this is what you're looking for?
More on how reduce() works here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
Solution I found. The factorization function now returns an object instead with prime key exponent value pairs. Through for in loops, and the reduce method, the LCM is outputted.
function smallestCommons(arr) {
// factorize a number function
function factorization(num) {
let primesObj = {};
// i is what we will divide the number with
for (let i = 2; i <= Math.sqrt(num); i++) {
// if number is divisible by i (with no remainder)
if (num % i === 0) {
let exponent = 0;
// begin while loop that lasts as long as num is divisible by i
while (num % i === 0) {
// change the value of num to be it divided by i
num = num / i;
exponent++;
// create key value pair where exponent is the value
primesObj[i] = exponent;
}
}
}
// if num is not the number 1 after the for loop
// push num to the array because it is also a prime number
if (num != 1) {
primesObj[num] = 1;
}
return primesObj;
}
// sort from lowest to highest
arr.sort((a,b) => a - b);
let range = [];
let primeFacts = [];
// push range of numbers to fullArr
for (let i = arr[0]; i <= arr[1]; i++) {
range.push(i);
}
console.log(range); // [2,3,4,5,6,7,8,9,10]
// loop for iterating through range numbers
for (let i = 0; i < range.length; i++) {
// push the prime factors of each range number
primeFacts.push(factorization(range[i]));
}
console.log(primeFacts);
// create a filtered object with only the largest key value pairs
let primeExponents = primeFacts.reduce((newObj,currObj)=> {
for (let prime in currObj) {
// create new key value pair when key value pair does not exist
if (newObj[prime] === undefined) {
newObj[prime] = currObj[prime];
}
// overwrite key value pair when current Object value is larger
else if (newObj[prime] < currObj[prime]) {
newObj[prime] = currObj[prime];
}
}
return newObj;
},{});
let finalArr = [];
// push appropriate amount of primes to arr according to exponent
for (let prime in primeExponents) {
for (let i = 1; i <= primeExponents[prime]; i++) {
finalArr.push(parseInt([prime]));
}
}
return finalArr.reduce((product, num) => product *= num);
};
console.log(smallestCommons([2,10]));
To go from the prime factorizations to the LCM, you need to count how many of each prime are needed at maximum. So for each factorization I would create a map of primes to counts. And I'd keep track of the highest number of each factor needed:
function lcm(primeFacts){
var maxPrimes = {}; // stores the highest number of each prime factor required
for(var i = 0; i < primeFacts.length; i++){
var map = {};
var factors = primeFacts[i];
for(var j = 0; j < factors.length; j++){
// check to see whether the factor already exists in the map
if(map[factors[j]]) map[factors[j]]++;
else map[factors[j]] = 1;
// check to make sure the max count exists
if(!maxPrimes[factors[j]]) maxPrimes[factors[j]] = 1;
if(maxPrimes[factors[j]] < map[factors[j]])
maxPrimes[factors[j]] = map[factors[j]];
}
}
Then once we have all the counts for each factor, we just multiply them out:
var multiple = 1;
for(var prime in maxPrimes){
multiple *= prime ^ maxPrimes[prime];
}
}
eg. here are two arrays
a = [1, 3]
b = [2, 4, 5]
I used while loop to sort it
var a=[1,3,6,7], b = [2, 4, 5];
var result = [];
var aPointer = 0;
var bPointer = 0;
while (aPointer < a.length || bPointer < b.length) {
if (bPointer == b.length ) {
result.push(... a.slice(aPointer));
break;
}
if (aPointer == a.length ) {
result.push(... b.slice(aPointer));
break;
}
if (a[aPointer] < b[bPointer]) {
result.push(a[aPointer]);
aPointer++;
} else {
result.push(b[bPointer]);
bPointer++;
}
}
console.log(result);
I think the time complexity should be O(n + m) = O(n), space complexity is O(m + n + m + n) = O(2(m+n)) = O(2n). Is there better way to concat sorted array?
The code is not completely correct. When all elements from b have been added to the result, and a still has values, then the else block will be executed, resulting in an endless loop of adding undefined to the result array.
Corrected code with different while condition and final concatenation of the remaining "rest" from one of the two input arrays:
var a = [1, 3, 6, 7], b = [2, 4, 5];
var result = [];
var aPointer = 0;
var bPointer = 0;
while (aPointer < a.length && bPointer < b.length) {
if (a[aPointer] < b[bPointer]) {
result.push(a[aPointer]);
aPointer++;
} else {
result.push(b[bPointer]);
bPointer++;
}
}
result = result.concat(a.slice(aPointer), b.slice(bPointer))
console.log(result);
The time complexity is O(n+m), as each iteration of the loop pushes one value to the result, and the result will in the end have n + m values. The final concat and slice is just a short way to do the same for the remainder of one of the two input arrays. So the time complexity is not influenced by it.
The space complexity is usually expressed only in the extra space used, so not including the space used by the input. So apart from some constant space used by atomic variables (such as aPointer), there is the result array, which takes O(n+m) space.
I want to loop through an array and then add each value to each other (except itself + itself) and if the sum of the two values that were looped through equals the second argument in my function, and the pair of values hasn't been encountered before, then remember their indices and, at the end, return the full sum of all remembered indices.
In other words, the problem statement is: given an array A of integers and a second value s that is a desired sum, find all pairs of values from array A at indexes i, j such that i < j and A[i] + A[j] = s, and return the sum of all indexes of these pairs, with the following restriction:
don't reuse value pairs, i.e. if two index pairs i, j and k, l satisfying the above conditions are found and if A[i] == A[k] and A[j] == A[l] or A[i] == A[l] and A[j] == A[k], then ignore the pair with the higher index sum.
Example
For example, functionName([1, 4, 2, 3, 0, 5], 7) should return 11 because values 4, 2, 3 and 5 can be paired with each other to equal 7 and the 11 comes from adding the indices of them to get to 11 where:
4 + 3 = 7
5 + 2 = 7
4 [index: 1]
2 [index: 2]
3 [index: 3]
5 [index: 5]
1 + 2 + 3 + 5 = 11
Example #2
functionName([1, 3, 2, 4], 4) would only equal 1, because only the first two elements can be paired to equal 4, and the first element has an index of 0 and the second 1
1 + 3 = 4
1 [index: 0]
3 [index: 1]
0 + 1 = 1
This is what I have so far:
function functionName(arr, arg) {
var newArr = [];
for(var i = 0; i < arr.length; i++){
for(var j = i + 1; j < arr.length; j++) {
if((arr[i] + arr[j]) === arg ) {
newArr.push(i , j);
}
}
}
if(newArr.length === 0) {
return console.log(0);
}
return console.log(newArr.reduce(function(a,b){return a + b}));
}
functionName([1, 4, 2, 3, 0, 5], 7);
The problem I have is that it all works but I have the issue that once it finds a pair that equals the second argument, then it's not supposed to use the same value pairs again but mine does, e.g.:
if the array is [1,1,1] and the second argument is 2, the loop will go through and find the answer but it continues to search after it finds the sum and I only want it to use the pair [1, 1] once, so if it finds a pair like this at indexes [0, 1] then it should not include any other pair that contains the value 1.
I was thinking that i could remove the rest of the values that are the same if more than 2 are found using filter leaving me with only 2 of the same value if there is in an array thus not having to worry about the loop finding a 1 + 1 twice but is this the best way to go about doing it?
I'm still new to this but looking forward to your comments
PS I'm planning on doing this using pure JavaScript and no libraries
Link to a JS fiddle that might make things easier to see what I have.
https://jsfiddle.net/ToreanJoel/xmumv3qt/
This is more complicated than it initially looks. In fact, making a loop inside a loop causes the algorithm to have quadratic time complexity with regard to the size of the array. In other words, for large arrays of numbers, it will take a very long time to complete.
Another way to handle this problem is to notice that you actually have to use each unique value in the array only once (or twice, if s is even and you have two s/2 values somewhere in the array). Otherwise, you would have non-unique pairs. This works because if you need pairs of numbers x and y such that x + y = s, if you know x, then y is determined -- it must be equal s - x.
So you can actually solve the problem in linear time complexity (to be fair, it's sometimes n*log(n) if all values in A are unique, because we have to sort them once).
The steps of the algorithm are as follows:
Make a map whose keys are values in array A, and values are sorted lists of indexes these values appear at in A.
Move through all unique values in A (you collected them when you solved step 1) in ascending order. For each such value:
Assume it's the lower value of the searched pair of values.
Calculate the higher value (it's equal to s - lower)
Check if the higher value also existed in A (you're doing it in constant time thanks to the map created in step 1).
If it does, add the lowest indexes of both the lower and the higher value to the result.
Return the result.
Here's the full code:
function findSumOfUniquePairs(numbers, sum) {
// First, make a map from values to lists of indexes with this value:
var indexesByValue = {},
values = [];
numbers.forEach(function (value, index) {
var indexes = indexesByValue[value];
if (!indexes) {
indexes = indexesByValue[value] = [];
values.push(value);
}
indexes.push(index);
});
values.sort();
var result = 0;
for (var i = 0, maxI = values.length; i < maxI; ++i) {
var lowerValue = values[i],
higherValue = sum - lowerValue;
if (lowerValue > higherValue) {
// We don't have to check symmetrical situations, so let's quit early:
break;
}
var lowerValueIndexes = indexesByValue[lowerValue];
if (lowerValue === higherValue) {
if (lowerValueIndexes.length >= 2) {
result += lowerValueIndexes[0] + lowerValueIndexes[1];
}
} else {
var higherValueIndexes = indexesByValue[higherValue];
if (higherValueIndexes) {
result += lowerValueIndexes[0] + higherValueIndexes[0];
}
}
}
return result;
}
document.write(findSumOfUniquePairs([1, 4, 2, 3, 0, 5], 7) + '<br>'); // 11;
document.write(findSumOfUniquePairs([1, 3, 2, 4], 4) + '<br>'); // 1
document.write(findSumOfUniquePairs([1, 1, 1], 2) + '<br>'); // 1
document.write(findSumOfUniquePairs([1, 1, 1, 1], 2) + '<br>'); // 1
document.write(findSumOfUniquePairs([1, 2, 3, 1, 2, 3, 1], 4) + '<br>'); // 7
document.write(findSumOfUniquePairs([5, 5, 1, 1, 1], 6) + '<br>'); // 2
document.write(findSumOfUniquePairs([0, 5, 0, 5, 1, 1, 1], 6) + '<br>'); // 5
This works, but it mucks up the initial array.
function functionName(arr, arg) {
var newArr = [];
for(var i = 0; i < arr.length; i++){
for(var j = i + 1; j < arr.length; j++) {
if((arr[i] + arr[j]) === arg ) {
newArr.push(i , j);
arr[i] = null;
arr[j] = null;
}
}
}
if(newArr.length === 0) {
return console.log(0);
}
return console.log(newArr.reduce(function(a,b){return a + b}));
}
Solution with loops with restart, if a sum is found. the found summands are stored in usedNumbers and later sorted and used to get the index for summing the index.
The sorting and the last index provides the correct start position for the Array.prototype.indexOf.
Edit:
what about [1,1,1,1], 2 ... should that be 6 or 1? – Jaromanda X 21
#JaromandaX that should be 1, after the pair is found with the values then it shouldn't look for a pair with the same values again – Torean
This version takes care of the requirement.
function f(array, sum) {
var arrayCopy = array.slice(0),
usedNumbers = [],
index = 0,
indexA = 0,
indexB,
a, b;
while (indexA < arrayCopy.length) {
indexB = indexA + 1;
while (indexB < arrayCopy.length) {
a = arrayCopy[indexA];
b = arrayCopy[indexB];
if (a + b === sum) {
usedNumbers.push(a, b);
arrayCopy = arrayCopy.filter(function (i) { return a !== i && b !== i; });
indexA--; // correction to keep the index
break;
}
indexB++;
}
indexA++;
}
return usedNumbers.sort().reduce(function (r, a, i) {
index = array.indexOf(a, i === 0 || a !== usedNumbers[i - 1] ? 0 : index + 1);
return r + index;
}, 0);
}
document.write(f([1, 4, 2, 3, 0, 5], 7) + '<br>'); // 11
document.write(f([1, 1, 1], 2) + '<br>'); // 1
document.write(f([5, 5, 1, 1, 1], 6) + '<br>'); // 2
document.write(f([0, 5, 0, 5, 1, 1, 1], 6) + '<br>'); // 5
document.write(f([1, 1, 1, 1], 2) + '<br>'); // 1
The solution below is very compact. It avoids unnecessary checks and loops only through the relevant elements. You can check the working codepen here:
http://codepen.io/PiotrBerebecki/pen/RRGaBZ.
function pairwise(arr, arg) {
var sum = 0;
for (var i=0; i<arr.length-1; i++) {
for (var j=i+1; j<arr.length; j++) {
if (arr[i] <= arg && arr[j] <= arg && arr[i] + arr[j] == arg) {
sum += i+j;
arr[i] = arr[j] = NaN;
}
}
}
return sum;
}
console.log( pairwise([1, 1, 0, 2], 2) ) // should return 6
Under the hood:
Start looping from the element with index (i) = 0.
Add a second loop only for the elements which are later in the array. Their index j is always higher than i as we are adding 1 to i.
If both elements (numbers) are less than or equal to to the arg, check if their sum equals to the arg. This avoids checking the sum if either of the numbers are greater than the arg.
If the pair has been found then change their values to NaN to avoid further checks and duplication.
This solution should have a time complexity of 0(n) or linear
Much faster than two nested for-loops. This function will give you the two indices that add up to the target number. It can easily be modified to solve any other configuration of this problem.
var twoSum = function(nums, target) {
const hash = {}
for(let i = 0; i < nums.length; i++) {
hash[nums[i]] = i
}
for(let j = 0; j < nums.length; j++) {
let numToFind = target - nums[j]
if(numToFind in hash && hash[numToFind] !== j) {
return [hash[numToFind], j]
}
}
return false
};
console.log(twoSum([1,2,3,5,7], 5))
In Python:
def twoSum(self, nums: List[int], target: int) -> List[int]:
myMap = {}
for i in range(len(nums)):
myMap[nums[i]] = i
for j in range(len(nums)):
numToFind = target - nums[j]
if numToFind in myMap and myMap[numToFind] != j:
return [myMap[numToFind], j]
print(twoSum([1,2,3,5,7], 5))
In Java:
import java.util.*;
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for(Integer i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for(Integer j = 0; j < nums.length; j++) {
Integer numToFind = target - nums[j];
Integer myInt = map.get(numToFind);
if(map.containsKey(numToFind) && myInt != j) {
return new int[] {myInt , j};
}
}
return new int[] {0, 0};
}
}
System.out.println(twoSum([1,2,3,5,7], 5))