The problem is as below:
Two archery teams A and B compete with the same number of members. If the score of team A[i] is higher than that of team B[i], the total score of team A will be +1, so given team A and B with any number of members, please calculate how total score of team A will be the highest value and write down the best order of team A members.
Input: A = [2,7,11,15]; B = [1,10,4,11];
Output: [2,11,7,15]
This is the question asked in a group, I don't know other test cases. So I change the order of team A, B to test my code.
Here is my code:
function sortTeam(a, b){
let result = [];
const asort = a.slice().sort((a,b) => a - b);
for (let i = 0; i < b.length; i++){
let bi = b[i];
for (let j = 0; j < asort.length; j++){
let aj = asort[j];
if (!result.includes(aj) && aj > bi){
result.push(aj);
break;
}
}
}
//console.log('result', result);
return result;
}
Here is the version of using splice
to reduce complexity:
function sortTeam(a, b){
let result = [];
const asort = a.slice().sort((a,b) => a - b);
for (let i = 0; i < b.length; i++){
let bi = b[i];
for (let j = 0; j < asort.length; j++){
let aj = asort[j];
if (aj > bi){
result.push(aj);
asort.splice(j, 1);
break;
}
}
}
//console.log('result', result);
return result;
}
My questions are:
- Is there a way that I can reduce the complexity of this code?
- I can remove the
includes
check by usingsplice
on asort but it's still 2 loops. And splice mutates the array -> should I use it? (I'm not into FP in anyway, just asking in general) - As for FP, I was trying to using
forEach
but it doesn't let me usingbreak
, so if you guys have a FP version, please let me know (reduce is kind of a normal for-loop to me, I mean the look doesn't clean as other high order functions) - What kind of problem is this? (I want to know the pattern or name so that I can find more similar problems to practice)