[プログラマー]コードテスト練習-図5級部屋の数



Solution.java

import java.util.*;

class Solution {    
    public int solution(int[] arrows) {
        int answer = 0;
        
        int[][] d = { { 0, 1 }, { 1, 1 }, { 1, 0 }, { 1, -1 }, { 0, -1 }, { -1, -1 }, { -1, 0 }, { -1, 1 } };
        
        HashSet<Coordinate> hs1 = new HashSet<>();
        HashSet<Edge> hs2 = new HashSet<>(); 
        
        int x = 0;
        int y = 0;
        hs1.add(new Coordinate(x, y));
        for (int arrow : arrows) {
            for (int i = 0; i < 2; i++) {
                int next_x = x + d[arrow][0];
                int next_y = y + d[arrow][1];
                
                if (hs1.contains(new Coordinate(next_x, next_y)) && !hs2.contains(new Edge(new Coordinate(x, y), new Coordinate(next_x, next_y)))) {
                    answer++;
                }
                
                Coordinate tmp = new Coordinate(next_x, next_y);
                hs1.add(new Coordinate(next_x, next_y));
                hs2.add(new Edge(new Coordinate(x, y), new Coordinate(next_x, next_y)));
                hs2.add(new Edge(new Coordinate(next_x, next_y), new Coordinate(x, y)));
                
                x = next_x;
                y = next_y;
            }
        }
        
        return answer;
    }
}

class Coordinate {
    int x, y;
    
    Coordinate(int x, int y) {
        this.x = x;
        this.y = y;
    }
    
    public boolean equals(Object o) {
        Coordinate c = (Coordinate) o;
        return this.x == c.x && this.y == c.y;
    }
    
    public int hashCode() {
        int result = x;
        result = 31 * result + y;
        return result;
    }
}

class Edge {
    Coordinate from, to;
    
    Edge(Coordinate from, Coordinate to) {
        this.from = from;
        this.to = to;
    }
    
    public boolean equals(Object o) {
        Edge e = (Edge) o;
        return this.from.x == e.from.x && this.from.y == e.from.y && this.to.x == e.to.x && this.to.y == e.to.y;
    }
    
    public int hashCode() {
        int result = from.x;
        result = 31 * result + from.y;
        result = 31 * result + to.x;
        result = 31 * result + to.y;
        return result;
    }
}
人の解答を見て、いくつかの考えが出た.
equalsとhashCodeを過剰に使う方法を学びました.
出典:プログラマーコードテスト練習、https://programmers.co.kr/learn/challenges