It is pretty simple: Given 2 lists of numbers and a maximum, find the maximum sum of a number from list2 that is smaller or equal to the given maximum as well as the number of occurrences.
This is the first attempt of what I had, with what I understood as the requirements
// Given 2 lists of numbers and a maximum, find the maximum of sum of a number from
// list1 + a number from list2 that is smaller or equal to the given maximum, as
// well as the number of occurrences.
function find(list1, list2, max){
let resultsArr = [];
// we will filter list2 for nums that are small or equal to given max
list2.filter((x) => {
return x <= max
})
// we will then use the filtered list and get a sum of each
.map((filteredNum) => {
list1.forEach((num) => {
resultsArr.push(num + filteredNum);
})
})
console.log(resultsArr.length)
console.log(Math.max(...resultsArr))
}
let list1 = [5,10,15]
let list2 = [1,2,3]
find(list1, list2, 2);
It works and does as expected, but upon re-reading the requirements again. I decided to do another one. This is the second attempt of what I had, with revised understanding of requirements
// Given 2 lists of numbers and a maximum, find the maximum of sum of a number from
// list1 + a number from list2 that is smaller or equal to the given maximum, as
// well as the number of occurrences.
function find(list1, list2, max){
const results = []
list1.map((num1) => {
list2.forEach((num2) => {
const num = num1 + num2;
if (num <= max){
results.push(num);
}
})
})
const maxResult = Math.max(...results);
const finalResult = results.filter((num) => {
return num == maxResult;
})
console.log('The list of sums: ' + results);
console.log('The largest sum less than or equal to ' + max + ' is ' + maxResult);
console.log('The # of occurrences for the largest sum is ' + finalResult.length);
}
let list1 = [13,13,15]
let list2 = [1,2,3]
find(list1, list2, 15);
Tested it and it works!
The list of sums: 14,15,14,15
The largest sum less than or equal to 15 is 15
The # of occurrences for the largest sum is 2
Further tweaks I could do, would be to have a variable to hold the max value for the current iteration and have a counter that will track, instead of pushing to an array and then doing all the work at the end
No comments:
Post a Comment