[英]Who Has the Most Money - Codewars Challenge - JavaScript
你要和一些學生一起去旅行,你要跟蹤每個學生有多少錢。 學生定義如下:
class Student {
constructor(name, fives, tens, twenties) {
this.name = name;
this.fives = fives;
this.tens = tens;
this.twenties = twenties;
}
}
如您所知,每個學生都有一些 5、10 和 20。 你的工作是返回錢最多的學生的名字。 如果每個學生的數量相同,則返回“全部”。
筆記:
每個學生都有一個唯一的名字
總會有一個明顯的贏家:要么一個人擁有最多,要么每個人擁有相同的數量
如果只有一個學生,那么那個學生的錢最多
我試過這個:
function mostMoney(students) { //get array of totals let array = []; students.forEach((value, index) => { let total = ((5 * value.fives) + (10 * value.tens) + (20 * value.twenties)); array.push([total, value.name]); }); //sort array of totals array = array.sort((a, b) => b[0] - a[0]); console.log('array****', array); //check if all totals are equal - if they are, return 'all' if (array.every((el, i, array) => (el)[0]) === array[0][0]) { return 'all'; } else { return array[0][1]; } }
對我來說沒有意義的是,當我console.log('array****', array);
在代碼戰中它看起來像:
array**** [ [ 50, 'Eric' ],
[ 40, 'Andy' ],
[ 40, 'Stephen' ],
[ 40, 'Phil' ],
[ 30, 'David' ] ]
array**** [ [ 50, 'Eric' ],
[ 40, 'Andy' ],
[ 40, 'Stephen' ],
[ 40, 'Phil' ],
[ 30, 'Cameron' ],
[ 30, 'Geoff' ],
[ 30, 'David' ] ]
array**** [ [ 40, 'Andy' ] ]
array**** [ [ 40, 'Stephen' ] ]
array**** [ [ 30, 'Cameron' ], [ 30, 'Geoff' ] ]
為什么會這樣? 我認為排序后,我的console.log('array***', array)
應該看起來像:
array**** [ [ 50, 'Eric' ],
[ 40, 'Andy' ],
[ 40, 'Stephen' ],
[ 40, 'Phil' ],
[ 30, 'Cameron' ],
[ 30, 'Geoff' ],
[ 30, 'David' ] ]
當我最初console.log(students)
時,它看起來像一個數組:
[ Student { name: 'Andy', fives: 0, tens: 0, twenties: 2 },
Student { name: 'Stephen', fives: 0, tens: 4, twenties: 0 },
Student { name: 'Eric', fives: 8, tens: 1, twenties: 0 },
Student { name: 'David', fives: 2, tens: 0, twenties: 1 },
Student { name: 'Phil', fives: 0, tens: 2, twenties: 1 } ]
所以我試圖用我的forEach
循環收集一個數組中的所有總數,然后在循環后對該數組進行排序——這個邏輯有什么問題?
工作解決方案:)
function mostMoney(students) {
let array = [];
if (students.length === 1) {
return students[0].name;
}
students.forEach((value, index) => {
let total = ((5 * value.fives) + (10 * value.tens) + (20 * value.twenties));
array.push([total, value.name]);
});
array = array.sort((a, b) => b[0] - a[0]);
if (array.every((el, i, array) => el[0] === array[0][0])) {
return 'all';
}
else {
return array[0][1];
}
}
實際上,我的.every
存在問題 - 我正在做(el)[0])
而不是el[0]
,然后我也沒有正確檢查何時只有一個學生傳遞給mostMoney
。
感謝大家闡明console.log 問題。 Codewars 是 console.logging 多次,因為正如你們所提到的,它正在運行多個測試。
我可以建議作為解決方案:
function mostMoney(students) {
//deep copy of argument
let input = [...students];
// sort students by total descending
let sum = st => st.fives * 5 + st.tens * 10 + st.twenties * 20;
let comparator = (st1,st2) => sum(st2) - sum(st1);
input.sort(comparator);
// result
//just compare the first two students
if(input.length >=2 && sum(input[0]) == sum(input[1])){
return 'all';
}
else{
return input[0].name;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.