javascript least amount of elements from an integer array that can be used to get to a total value - javascript

please can somebody help?
If i have a total or a sum for instance 91
How can I create an array of the least amount of elements needed to get to the total value?
[50, 20, 10 , 5, 3, 2, 1] totaling this array will provide 91.
I know how to perform the opposite function using reduce or like so:
<script>
var numbers = [65, 44, 12, 4];
function getSum(total, num) {
return total + num;
}
function myFunction(item) {
document.getElementById("demo").innerHTML = numbers.reduce(getSum);
}
</script>

Greedy algorithm
Here is a solution using greedy algorithm. Note that this solution will work correctly in case when all the smaller numbers are divisors of all the bigger numbers such as in case [50, 10, 5, 1]. (see dynamic algorithm below this one for solution that can handle any input)
50 mod 10 = 0
50 mod 5 = 0
50 mod 1 = 0
10 mod 5 = 0
10 mod 1 = 0
5 mod 1 = 0
const sum = xs => xs.reduce((acc, v) => acc + v, 0);
function pickSubset(options, total, currentPick) {
if (sum(currentPick) === total) { return currentPick; }
if (options.length === 0) { return null; }
const firstVal = options[0];
let res = null;
if (sum(currentPick) + firstVal > total) {
res = pickSubset(options.slice(1), total, currentPick);
} else {
let opt1 = pickSubset(options, total, currentPick.concat(options[0]));
let opt2 = pickSubset(options.slice(1), total, currentPick.concat(options[0]));
if (opt1 && opt2) {
opt1.length < opt2.length ? res = opt1 : res = opt2
} else if (opt1) {
res = opt1;
} else {
res = opt2;
}
}
return res;
}
const total = 73;
const options = [50, 25, 10, 5, 2, 1];
console.log(pickSubset(options, total, []));
To handle unsorted input you can wrap it in another function and sort it prior to passing it to the main function.
const sum = xs => xs.reduce((acc, v) => acc + v, 0);
function pickSubset(options, total, currentPick) {
const sortedOptions = options.sort((a, b) => b - a);
function _pickSubset(options, total, currentPick) {
if (sum(currentPick) === total) { return currentPick; }
if (options.length === 0) { return null; }
const firstVal = options[0];
let res = null;
if (sum(currentPick) + firstVal > total) {
res = pickSubset(options.slice(1), total, currentPick);
} else {
let opt1 = pickSubset(options, total, currentPick.concat(options[0]));
let opt2 = pickSubset(options.slice(1), total, currentPick.concat(options[0]));
if (opt1 && opt2) {
opt1.length < opt2.length ? res = opt1 : res = opt2
} else if (opt1) {
res = opt1;
} else {
res = opt2;
}
}
return res;
}
return _pickSubset(sortedOptions, total, currentPick);
}
const total = 73;
const options = [50, 25, 10, 5, 2, 1].reverse();
console.log(pickSubset(options, total, []));
Dynamic programming (bottom-up natural ordering approach)
This solution works correctly for any type of input.
function pickSubset(options, total) {
function _pickSubset(options, change, minNums, numsUsed) {
for (let i = 0; i < change + 1; i++) {
let count = i;
let newNum = 1;
let arr = options.filter(v => v <= i);
for (let j of arr) {
if (minNums[i - j] + 1 < count) {
count = minNums[i - j] + 1;
newNum = j;
}
}
minNums[i] = count;
numsUsed[i] = newNum;
}
return minNums[change];
}
function printNums(numsUsed, change) {
const res = [];
let num = change;
while (num > 0) {
let thisNum = numsUsed[num];
res.push(thisNum);
num = num - thisNum;
}
return res;
}
const numsUsed = [];
const numsCount = [];
_pickSubset(options, total, numsCount, numsUsed);
return printNums(numsUsed, total);
}
const options = [50, 10, 5, 2, 1];
console.log(pickSubset(options, 73));
Dynamic programming (top-down memoization approach)
// helper function that generates all the possible solutions
// meaning, all the possible ways in which we can pay the provided amount
// and caches those solutions;
// returns the number of possible solutions but that is not neccessary
// in this case
const _pickSubset = (toPay, options, currentPick, cache) => {
if (toPay < 0) { return 0; }
if (toPay === 0) {
cache.add(currentPick);
return 1;
}
if (options.length === 0) { return 0; }
return _pickSubset(toPay - options[0], options, currentPick.concat(options[0]), cache)
+ _pickSubset(toPay, options.slice(1), currentPick, cache);
};
// memoize only with respect to the first two arguments - toPay, bills
// the other two are not necessary in this case
const memoizeFirstTwoArgs = fn => {
const cache = new Map();
return (...args) => {
const key = JSON.stringify(args.slice(0, 2));
if (cache.has(key)) { return cache.get(key); }
const res = fn(...args);
cache.set(key, res);
return res;
};
};
// uses memoized version of makeChange and provides cache to that function;
// after cache has been populated, by executing memoized version of makeChange,
// find the option with smallest length and return it
const pickSubset = (toPay, options) => {
const cache = new Set();
const memoizedPickSubset = memoizeFirstTwoArgs(_pickSubset);
memoizedPickSubset(toPay, options, [], cache);
let minLength = Infinity;
let resValues;
for (const value of cache) {
if (value.length < minLength) {
minLength = value.length;
resValues = value;
}
}
return resValues;
}
const options = [50, 25, 10, 5, 2, 1];
const toPay = 73;
console.log(pickSubset(toPay, options));

Related

Inconsistency, when returning index of duplicate values

I'm trying to create an algorithm to find duplicate values in a list and return their respective indexes, but the script only returns the correct value, when I have 2 equal elements:
array = [1,2,0,5,0]
result -> (2) [2,4]
Like the example below:
array = [0,0,2,7,0];
result -> (6) [0, 1, 0, 1, 0, 4]
The expected result would be [0,1,4]
Current code:
const numbers = [1,2,0,5,0];
const checkATie = avgList => {
let averages, tie, n_loop, currentAverage;
averages = [... avgList];
tie = [];
n_loop = 0;
for(let n = 0; n <= averages.length; n++) {
currentAverage = parseInt(averages.shift());
n_loop++
for(let avg of averages) {
if(avg === currentAverage) {
tie.push(numbers.indexOf(avg),numbers.indexOf(avg,n_loop))
};
};
};
return tie;
}
console.log(checkATie(numbers));
if possible I would like to know some way to make this code more concise and simple
Use a Set
return [...new Set(tie)]
const numbers1 = [1,2,0,5,0];
const numbers2 = [0,0,2,7,0];
const checkATie = avgList => {
let averages, tie, n_loop, currentAverage;
averages = [... avgList];
tie = [];
n_loop = 0;
for(let n = 0; n <= averages.length; n++) {
currentAverage = parseInt(averages.shift());
n_loop++
for(let avg of averages) {
if(avg === currentAverage) {
tie.push(avgList.indexOf(avg),avgList.indexOf(avg,n_loop))
};
};
};
return [...new Set(tie)]
}
console.log(checkATie(numbers1));
console.log(checkATie(numbers2));
I hope this help you.you can use foreach function to check each item of array
var array = [0,0,2,7,0];
var result = [] ;
array.forEach((item , index)=>{
if(array.findIndex((el , i )=> item === el && index !== i ) > -1 ){
result.push(index)
}
})
console.log(result);
//duplicate entries as an object
checkDuplicateEntries = (array) => {
const duplicates = {};
for (let i = 0; i < array.length; i++) {
if (duplicates.hasOwnProperty(array[i])) {
duplicates[array[i]].push(i);
} else if (array.lastIndexOf(array[i]) !== i) {
duplicates[array[i]] = [i];
}
}
console.log(duplicates);
}
checkDuplicateEntries([1,2,0,5,0]);
// hope this will help
Create a lookup object with value and their indexes and then filter all the values which occurred more than once and then merge all indexes and generate a new array.
const array = [1, 2, 0, 5, 0, 1, 0, 2],
result = Object.values(array.reduce((r, v, i) => {
r[v] = r[v] || [];
r[v].push(i);
return r;
}, {}))
.filter((indexes) => indexes.length > 1)
.flatMap(x => x);
console.log(result);

how to improve this algorithm for combinations?

I have this problem, I need to find a combination with specific numbers, and the sum of the numbers should be a other specific amount, i think that you can understand me with the code.
function get4() {
function iter(temp) {
return function (v) {
var t = temp.concat(v);
if (t.length === 4) {
if (t.reduce(add) === 10) {
result.push(t);
}
return;
}
values.forEach(iter(t));
};
}
const
add = (a, b) => a + b,
values = [1, 2, 3, 4],
result = [];
values.forEach(iter([]));
return result;
}
console.log(get4().map(a => a.join(' ')));
with this code I can find a 4 digits that his sum is 10, with little numbers works, but if a try with bigger numbers, the function crash, I mean, the browser not execute it.
my problema is with this data
length = 493
the sum is = 42990
and the values are = [500,400,300,200,100,90,80,70,60,50,40,30,20,10,5]
how can I improve this code? if you have another solution in other language, it would also help me.
You could:
// comments removed for simplicity
function combinationSumRecursive(
candidates,
remainingSum,
finalCombinations = [],
currentCombination = [],
startFrom = 0,
) {
if (remainingSum < 0) {
return finalCombinations;
}
if (remainingSum === 0) {
finalCombinations.push(currentCombination.slice());
return finalCombinations;
}
for (let candidateIndex = startFrom; candidateIndex < candidates.length; candidateIndex += 1) {
const currentCandidate = candidates[candidateIndex];
currentCombination.push(currentCandidate);
combinationSumRecursive(
candidates,
remainingSum - currentCandidate,
finalCombinations,
currentCombination,
candidateIndex,
);
currentCombination.pop();
}
return finalCombinations;
}
function removesDuplicatesAndNon4Length(arr) {
return arr.map(x => [...new Set(x)]).filter(x => x.length === 4);
}
const tempResp = combinationSumRecursive([1, 2, 3, 4], 10);
const resp = removesDuplicatesAndNon4Length(tempResp);
console.log(resp);
Note: This is a Combination Sum Problem version modificated for this specific program.

How to convert string to array with ranges JavaScript

Consider the following string: 7, 20, 22, 30–32, 33, 36–40, 46
I developed some code that will automatically parse said string into an array with the given ranges as follows.
Note: A typical use-case for this would be - to search for selected pages within a pdf with 100's of pages
var number_string = "7, 20, 22, 30–32, 33, 36–40, 46".toString().replace(/–/gi, '-').replace(/ /gi, '').split(',');
var new_arr = [];
$.each(number_string, function(index, value) {
if (value.match(/-/gi)) {
var range_arr = value.split('-');
var sub_arr = range(range_arr[0], range_arr[1]);
$.each(sub_arr, function(sub_index, sub_value) {
new_arr.push(parseInt(sub_value, 10));
});
} else {
new_arr.push(parseInt(value, 10));
}
});
console.log(new_arr);
function range(lowEnd, highEnd) {
var arr = [],
c = highEnd - lowEnd + 1;
while (c--) {
arr[c] = highEnd--
}
return arr;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Was there a more streamlined non jQuery method that could have been leveraged here that is also, simple, light weight and easy to read? Please no ES6 stuff as that is Greek to me.
Note: The ToInt function is just a function that returns a valid number or 0.
The jQuery.map() method acts like a flat map (returned sub arrays are flattend). In the map's callback function, use String.search() to check if there's a dash. If not convert to number with the + operator and return. If there's a dash, split, use a for loop to convert the min and max to an array, and return the array.
function convert(str) {
var arr = jQuery.map(str.split(', '), function(s) {
if(s.search('–') === -1) return +s;
var minmax = s.split('–');
var range = [];
for(var i = +minmax[0]; i <= +minmax[1]; i++) range.push(i);
return range;
});
return arr;
}
var number_string = "7, 20, 22, 30–32, 33, 36–40, 46";
var result = convert(number_string);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Using ESNext I would use Array.flatMap() instead of jQuery.map(), with String.inclues() to detect the dash, and Array.from() to generate the sub array.
const convert = (str) =>
str.split(', ')
.flatMap(s => {
if(!s.includes('–')) return +s;
const [min, max] = s.split('–');
return Array.from({ length: max - min + 1 }, (_, n) => n + +min);
});
var number_string = "7, 20, 22, 30–32, 33, 36–40, 46";
var result = convert(number_string, '–');
console.log(result);
I'd use .reduce. First split the initial string by commas. If the string being iterated over doesn't have -, then just push the number to the accumulator; otherwise, split by - to get a low and high number, then use a for loop to push all numbers from low to high to the accumulator:
const ToInt = Number;
const numArr = "7, 20, 22, 30–32, 33, 36–40, 46".split(', ');
const result = numArr.reduce((a, str) => {
if (!str.includes('–')) {
a.push(ToInt(str));
return a;
}
const [low, high] = str.split('–');
for (let i = Number(low); i <= high; i++) {
a.push(i);
}
return a;
}, []);
console.log(result);
If for some reason you don't want to use ES6, you can transform it to ES5 with Babel:
"use strict";
function _slicedToArray(arr, i) {
return (
_arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest()
);
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (
var _i = arr[Symbol.iterator](), _s;
!(_n = (_s = _i.next()).done);
_n = true
) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
var ToInt = Number;
var numArr = "7, 20, 22, 30–32, 33, 36–40, 46".split(", ");
var result = numArr.reduce(function(a, str) {
if (str.indexOf("–") === -1) {
a.push(ToInt(str));
return a;
}
var _str$split = str.split("–"),
_str$split2 = _slicedToArray(_str$split, 2),
low = _str$split2[0],
high = _str$split2[1];
for (var i = Number(low); i <= high; i++) {
a.push(i);
}
return a;
}, []);
console.log(result);
(but the ES6 version is more concise and probably a lot easier to read and understand)
I have my own implementation for this purpose
parseStringRange accepts strings like '1,2,3' and '1,2,3-5,6,7', also removes invalid chars (not numbers or , or -) and return one array with all numbers.
the function also returns the numbers ordered and removes duplicates, the user also can input unordered numbers even in range, '1-5' and '5-1' will return same output.
const parseStringRange = (range = '') =>
`${range}`
?.replace(/[^0-9,-]/g, '') //remove invalid chars
?.split(',') //convert 1,2 to [1, 2]
?.flatMap(s => { //convert 1-3 to [1,2,3]
if (!s.includes('-')) return [s]
const [min, max] = s.split('-').map(e => Number(e))
if (min > max) var i = -1
else var i = 1
const r = []
for (let p = min; p != max; p += i)
r.push(p)
r.push(max)
return r;
})
?.map(e => Number(e)) //convert all string numbers to number
?.reduce((t, e, i, a) => {
if (!t)
t = [... new Set(a)]
return t
}, null) //remove duplicates
?.sort((a, b) => a - b) //sort numbers, smallest first

How do I get Fibonacci numbers in an array?

Given input = [1,2,4] return [1,2], or if no fibonacci numbers return [], [1,1,2] should return [1,2];
I know you can check whether a number is in the fibonacci sequence with this code:
function isSquare(n) {
return n > 0 && Math.sqrt(n) % 1 === 0;
};
//Equation modified from http://www.geeksforgeeks.org/check-number-fibonacci-number/
function isFibonacci(numberToCheck)
{
// numberToCheck is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both
// is a perferct square
return isPerfectSquare(5*numberToCheck*numberToCheck + 4) ||
isPerfectSquare(5*numberToCheck*numberToCheck - 4);
}
But I don’t know how to implement it. Thanks.
Array.from(new Set(arr)) Removes duplicates from the original array
let newArr = []; Defining the new array
for ( let i = 0; i < arrD.length; i++ ) Loop every number of arrD, arrD[i] accesses a number in the array
if(fib(arrD[i])) { newArr.push(arrD[i]); } if the number is in the fibonacci sequence, fib(arrD[i]) will return true, and the number will be .pushed into the newArr
Using a for loop
let arr = [1,2,3,8,3,8];
let sqrt = (num) => { return num > 0 && Math.sqrt(num) % 1 === 0; };
let fib = (num) => { return sqrt(5 * Math.pow(num,2) + 4) || sqrt(5 * Math.pow(num,2) - 4); };
function fibArr(arr) {
arrD = Array.from(new Set(arr));
let newArr = [];
for ( let i = 0; i < arrD.length; i++ ) {
if(fib(arrD[i])) { newArr.push(arrD[i]); }
}
return newArr;
}
console.log(fibArr(arr));
OR using .filter
let arr = [1,2,3,8,3,8];
let sqrt = (num) => { return num > 0 && Math.sqrt(num) % 1 === 0; };
let fib = (num) => { return sqrt(5 * Math.pow(num,2) + 4) || sqrt(5 * Math.pow(num,2) - 4); };
function fibArr(arr) {
arrD = Array.from(new Set(arr));
let newArr = arrD.filter(function(arrD){
return fib(arrD);
})
return newArr;
}
console.log(fibArr(arr));

Finding a Single Integer in an array using Javascript

I was able to pull all single integers after 'reduce', but not working when there's all duplicates and output should be 0, not hitting my else or else if - code keeps outputting 0 vs the single integers
var singleNumber = function(nums) {
var sorted_array = nums.sort();
for (var i=0; i < sorted_array.length; i++){
var previous = sorted_array[i-1];
var next = sorted_array[i+1];
var singles = {key: 0};
var singlesArray = [];
if (sorted_array[i] !== previous && sorted_array[i] !== next){
singlesArray.push(sorted_array[i]);
singlesArray.reduce(function(singles, key){
singles.key = key;
//console.log('key', key);
return singles.key;
},{});
}
else if(singlesArray.length === 0) {
singles.key = 0;
return singles.key;
}
}
console.log('singles.key', singles.key);
return singles.key;
};
console.log(singleNumber([2,1,3,4,4]));
// tests
const n1 = [1,2,3,4,4] //[1,2,3]
const n2 = [1] //[1]
const n3 = [1,1] //0
const n4 = [1,1,1] //0
const n5 = [1,5,3,4,5] //[1,3,4]
const n6 = [1,2,3,4,5] //[1,2,3,4,5]
const n7 = [1,5,3,4,5,6,7,5] //[1,3,4,6,7]
const singleNumber = numbers => {
const reducer = (acc, val) => {
// check to see if we have this key
if (acc[val]) {
// yes, so we increment its value by one
acc[val] = acc[val] + 1
} else {
// no, so it's a new key and we assign 1 as default value
acc[val] = 1
}
// return the accumulator
return acc
}
// run the reducer to group the array into objects to track the count of array elements
const grouped = numbers.reduce(reducer, {})
const set = Object.keys(grouped)
// return only those keys where the value is 1, if it's not 1, we know its a duplicate
.filter(key => {
if (grouped[key] == 1) {
return true
}
})
// object.keys makes our keys strings, so we need run parseInt to convert the string back to integer
.map(key => parseInt(key))
// check to array length. If greater than zero, return the set. If it is zero, then all the values were duplicates
if (set.length == 0) {
return 0
} else {
// we return the set
return set
}
}
console.log(singleNumber(n7))
https://jsbin.com/sajibij/edit?js,console

Categories