Thursday, 3 August 2017

CTCI Challange, DAY 11

Day 11

Problem Statement:Sorting: Comparator

Today's problem was very easy,on comparators.
i have copied the int to Integer so as to use the compareTo() functionality.

On Paper:-




Solution:-

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

class Player {
    String name;
    int score;

    Player(String name, int score) {
        this.name = name;
        this.score = score;
    }
}

class Checker implements Comparator<Player> {

    @Override    public int compare(Player o1, Player o2) {
        Integer i1 = o1.score;
        Integer i2 = o2.score;
        if (i2.compareTo(i1) == 0) {
            return o1.name.compareTo(o2.name);
        }
        return i2.compareTo(i1);
    }
}

class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();

        Player[] player = new Player[n];
        Checker checker = new Checker();

        for (int i = 0; i < n; i++) {
            player[i] = new Player(scan.next(), scan.nextInt());
        }
        scan.close();

        Arrays.sort(player, checker);
        for (int i = 0; i < player.length; i++) {
            System.out.printf("%s %s\n", player[i].name, player[i].score);
        }
    }
}

No comments:

Post a Comment

Installing Docker and Minikube

  install docker-   sudo apt install docker.io   set user to docker group:- sudo gpasswd -a   {user} docker   imp commands:- ...