728x90
package Level2.October22;
import java.util.HashSet;
public class VisitLength { //방문길이
public static void main(String[] args) {
String dirs = "ULURRDLLU";
System.out.println(solution(dirs));
}
public static int solution(String dirs) {
Coordinate coordinate = new Coordinate(0,0);
HashSet<Coordinate> hashSet = new HashSet<>();
for(int i=0; i<dirs.length();i++){
switch (dirs.charAt(i)){
case 'U':
if(coordinate.getY()+1<=5){
coordinate.update(0,1);
hashSet.add(new Coordinate(coordinate.getX(), coordinate.getY()-0.5));
}
break;
case 'D':
if(coordinate.getY()-1>=-5){
coordinate.update(0,-1);
hashSet.add(new Coordinate(coordinate.getX(), coordinate.getY()+0.5));
}
break;
case 'L':
if(coordinate.getX()-1>=-5){
coordinate.update(-1,0);
hashSet.add(new Coordinate(coordinate.getX()+0.5, coordinate.getY()));
}
break;
case 'R':
if(coordinate.getX()+1<=5){
coordinate.update(1,0);
hashSet.add(new Coordinate(coordinate.getX()-0.5, coordinate.getY()));
}
break;
}
}
return hashSet.size();
}
static class Coordinate{
double x;
double y;
public Coordinate(double x,double y){
this.x = x;
this.y = y;
}
public void update(double x, double y){
this.x+=x;
this.y+=y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Coordinate){
Coordinate coordinate = (Coordinate) obj;
return (this.x ==coordinate.x && this.y == coordinate.y);
}
return false;
}
@Override
public int hashCode() {
return (this.x+""+this.y).hashCode();
}
}
}
Coordinate라는 객체를 hashSet에 넣어 x값과 y값이 같은 중복된 좌표를 없애려고 시도하였으나 x와 y값이 같아도 중복이 제거 되지 않는 현상이 생겼다. 인터넷에 찾아본 결과 객체들끼리의 중복검사일 경우 equals()와 hascode() 구현해주어야 hashSet에 넣었을 때 중복제거가 된다는 것을 배웠다.
728x90
'Java' 카테고리의 다른 글
인터페이스와 추상클래스의 차이점 (0) | 2022.10.31 |
---|---|
list.indexOf() (0) | 2022.10.30 |
2차원배열 정렬 및 중복계산제거로 인한 알고리즘 실행시간 줄이기 (0) | 2022.10.27 |
for문 순열,XOR 연산자 (0) | 2022.10.23 |
LRU,동적계획법,메모이제이션 (0) | 2022.10.14 |