Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Javaで競技プログラミングする話

 Javaで競技プログラミングする話

Javaで競技プログラミングするとオブジェクト指向できて楽しい話です。

Raccoon Tech Connect #4 |3分で語りつくせ!LTラッシュ!
https://raccoon-holdings.connpass.com/event/314185/
で発表した内容です。

simodake

April 23, 2024
Tweet

More Decks by simodake

Other Decks in Technology

Transcript

  1. OOP例 import java.util.*; public class Main { public static void

    main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); List<Human> list = new ArrayList<>(); for(var i = 0; i < n; i++) { list.add(new Human(sc.nextDouble(), sc.nextDouble())); } } } class Human { public double height; public double weight; public Human(double height, double weight) { this.height = height; this.weight = weight; } } シンプルにデータを持つだけ Humanクラスをつくる
  2. OOP例 class Human implements Comparable<Human> { public double height; public

    double weight; public Human(double height, double weight) { this.height = height; this.weight = weight; } public double bmi() { return weight / (height * height); } @Override public int compareTo(Human o) { return Double.compare(this.bmi(), o.bmi()); } } ソートするには、比較する Comparableインターフェース つける
  3. OOP例 class Human implements Comparable<Human> { public double height; public

    double weight; public Human(double height, double weight) { this.height = height; this.weight = weight; } public double bmi() { return weight / (height * height); } @Override public int compareTo(Human o) { return Double.compare(this.bmi(), o.bmi()); } } インターフェースを 実装する
  4. OOP例 class Human implements Comparable<Human> { public double height; public

    double weight; public Human(double height, double weight) { this.height = height; this.weight = weight; } public double bmi() { return weight / (height * height); } @Override public int compareTo(Human o) { return Double.compare(this.bmi(), o.bmi()); } } BMIの計算ロジック書く
  5. OOP例 import java.util.*; public class Main { public static void

    main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); List<Human> list = new ArrayList<>(); for(var i = 0; i < n; i++) { list.add(new Human(sc.nextDouble(), sc.nextDouble())); } list.sort(Comparator.naturalOrder()); } } class Human implements Comparable<Human> { public double height; public double weight; public Human(double height, double weight) { this.height = height; this.weight = weight; 完成!