nTop records

node v8.11.1
version: 1.0.0
endpointsharetweet
/* Description You've been given the task of retrieving the top N high scores from players of a video game. You need to write the function top_scores(records, n_top) where records is a list of lists in the form of records = [ ["Bob", 100], ["Jane", 120], ["Alice", 10], ["Bob", 110], ["Bob", 10] ] and n_top is an integer. The function should return the top n records, where each user name can appear at most a single time. Records should be in from highest to lowest. Users with the same score should be in alphabetical order. >>> top_scores(records, 3) [["Jane", 120],["Bob", 110],["Alice", 10]] if n_top is negative or 0, the returned value should be an empty list. if n_top is greater than the total number of records, you should include as many valid records as possible. */ const records = [ ["Bob", 100], ["Jane", 120], ["Alice", 10], ["Bob", 110], ["Bob", 10], ["Machin", 140] ] /* a transformer en {Bob: 110, Jane: 120, Alice: 10} */ const getMaxScore = (player) => (records) => records.filter(elem => elem[0] === player).sort().reverse()[0][1] const cleanRecords = (rec) => rec.reduce((acc, item) => { const newRes = (item[1] === getMaxScore(item[0])(rec)) ? [...acc, [item[0], item[1]]] : acc; return newRes; }, []) const topScores = (records, nTop) => cleanRecords(records).sort((a, b) => b[1] - a[1]).slice(0, nTop) topScores(records, 2)
Loading…

no comments

    sign in to comment