Sorting: Comparator

Sort by

recency

|

505 Discussions

|

  • + 0 comments

    Java #

    public int compare(Player a, Player b) {
           
        int ageComarator = Integer.valueOf(b.score).compareTo(a.score);
         if (ageComarator != 0) {
            return ageComarator;
         } else {
           return a.name.compareTo(b.name);
         }
        }
    
  • + 0 comments

    I do think that the prompt is very confunsing, it says a checker is being called, but you have to implement the checker yourself, and that the Comparator interface exists? It was really confusing.

  • + 0 comments

    my JS solution - with class

    function processData(input) {
      //Enter your code here
    
      const scores = [];
    
      const inputAr = input.split('\n');
      inputAr.shift();
    
      for (let score of inputAr) {
        scores.push(new Score(score.split(' ')));
      }
    
      scores.sort((a, b) => a.compare(b));
    
      const ranking = scores.map((score) => score.toString());
    
      console.log(ranking.join('\n'));
    }
    
    class Score {
      player = '';
      score = 0;
    
      constructor([player, score] = playerScore) {
        this.player = player;
        this.score = +score;
      }
    
      compare(playerB) {
        return this.score < playerB.score
          ? 0
          : this.score === playerB.score
          ? this.player.localeCompare(playerB.player)
          : -1;
      }
    
      toString() {
        return this.player + ' ' + this.score;
      }
    }
    
  • + 0 comments

    JS

    function processData(input) {
        //Enter your code here
    
        const data = input.split('\n');
    
        const arr = []
    
        for (let i = 1; i < data.length; i++) {
            const [name, scores] = data[i].split(' ');
            arr.push([name, scores])
        }
    
    
        const rr = obj.sort((a, b) => {
            if (b[1] !== a[1]) {
                return b[1] - a[1];
            }
            return a[0].localeCompare(b[0]);
        });
    
        const result = rr.map(r => r.join(' ')).join(' \n')
    
        console.log(result);
    
    }
    
  • + 0 comments

    Javascipt

    function processData(input) {
        //Enter your code here
        const arr = input.split("\n")
        const result = []
        for (let i = 1; i < arr.length; i++) {
            result.push(arr[i].split(" "))
        }
        result.sort((a, b) => {
            return b[1] - a[1];
        });
    
        result.sort((a, b) => {
            if (b[1] === a[1] && b[0] > a[0]) {
                return -1;
            }
        });
        console.log(result.join("\n").replaceAll(",", " "));
    
    }