1. Date, Calendar 클래스

이전 포스팅을 보자

jino-dev-diary.tistory.com/entry/Java-Date-Calendar-%ED%81%B4%EB%9E%98%EC%8A%A4?category=941695

요약하자면, Date 클래스와 Calendar 클래스는 문제점이 많아서 대부분 다른 오픈소스 라이브러리를 사용했었다.

이를 보완하기위해 JDK 1.8부터 Time 패키지를 제공한다.


2. Time 패키지

2.1 특징

Time 패키지의 클래스들은 Date나 Calendar 클래스와 다르게 Immutable이다. 즉 날짜나 시간을 변경하면 기존의 객체가 변경되는 것이 아니라, 새로운 객체를 반환한다. (String 과 비슷함) 그러므로 멀티쓰레드 환경에서 안전하다.

2.2 핵심 클래스

LocalTime - 시간을 표현할 때 사용

LocalDate - 날짜를 표현할 때 사용

LocalDateTime - 모두 표현할 때 사용

ZonedDateTime - 시간대(time zone)까지 표현할 때 사용

2.3 객체 생성

Calendar의 경우 - Calendar.getInstance();

Date의 경우 - new Date();

Time 클래스의 경우 - now()of()를 이용

//Calendar
Calendar cal = Calendar.getInstance();
//Date
Date date = new Date();

//localDate
LocalDate dateNow = LocalDate.now();
LocalDate dateOf = Localdate.of(2020, 11, 11);
//localTime
LocalTime timeNow = LocalTime.now();
LocalTime timeOf = LocalTime.of(18, 30, 0);
//LocalDateTime
LocalDateTime dateTimeNow = LocalDateTime.now();
LocalDateTime dateTimeOf = LocalDateTime.of(dateNow, timeNow);
//ZonedDateTime
ZonedDateTime zonedDateTimeNow = ZonedDateTime.now();
ZonedDateTime zonedDateTimeOf = ZonedDateTime.of(dateOf, timeOf, ZoneId.of("Asia/Seoul"));

2.4 필드 값 가져오기

get~() 메서드 사용

클래스 리턴 타입 메서드 설명
LocalDate
LocalDateTime
ZonedDateTime
int getYear()
Month getMonth() Month값
int getMonthValue()
int getDayOfYear() 일년 중 몇 번째 일
int getDayOfMonth() 월 중 몇 번째 일
DayOfWeek getDayOfWeek() 요일
boolean isLeapYear() 윤년 여부
LocalTime
LocalDateTime
ZonedDateTime
int getHour() 시간
int getMinute()
int getSecond()
int getNano() 나노초
ZonedDateTime ZoneId getZone() Asia/Seoul 등..
ZoneOffset getOffset() UTC와의 시차 리턴

예시 코드

public class TimeTest {

  public static void localDateTimeTest() {
    LocalDateTime dateTime = LocalDateTime.now();
    //date
    int month = dateTime.getMonthValue();
    int year = dateTime.getYear();
    int day = dateTime.getDayOfMonth();
    String dayOfWeek = dateTime.getDayOfWeek().name();

    //time
    int hour = dateTime.getHour();
    int minute = dateTime.getMinute();
    int second = dateTime.getSecond();
  }
}

2.5 필드 변경

with~(long ), plus~(long ), minus~(long )사용하여 년, 월, 주, 일, 시간, 분, 초, 나노초를 더하거나 뺄 수 고, 변경할 수 있다.

클래스 리턴 타입 메서드(매개 변수 타입) 설명
LocalDate
LocalDateTime
ZonedDateTime
LocalDate
LocalDateTime
ZonedDateTime
with/plus/minusYears(long) 년 변경
with/plus/minusMonths(long) 월 변경
with/plus/minusWeeks(long) 주 변경
with/plus/minusDays(long) 일 변경
LocalTime
LocalDateTime
ZonedDateTime
LocalTime
LocalDateTime
ZonedDateTime
with/plus/minusHours(long) 시간 변경
with/plus/minusMinutes(long) 분 변경
with/plus/minusSeconds(long) 초 변경
with/plus/minusNanos(long) 나노초 변경

결과값은 항상 새로운 객체를 생성해서 반환하기 때문에 대입연산자 이용해야한다

with(TemporalAdjusters adjuster) 메서드를 통해 현자 날짜를 기준으로 년도의 첫 번째 일, 마지막 일, 돌아오는 요일 등 상대적인 날짜로 변경할 수 있다.

TemporalAdjusters 메서드(매개 변수) 설명
firstDayOfYear() 이번 해의 첫 번째 일
lastDayOfYear() 이번 해의 마지막 일
firstDayOfNextYear() 다음 해의 첫 번째 일
firstDayOfMonth() 이번 달의 첫 번째 일
lastDayOfMonth() 이번 달의 마지막 일
firstDayOfNextMonth() 다음 달의 첫 번째 일
firstInMonth(DayOfWeek) 이번 달의 첫 번째 요일
lastInMonth(DayOfWeek) 이번 달의 마지막 요일
next(DayOfWeek) 다음 요일
nextOrSame(DayOfWeek) 다음 요일 (오늘 포함)
previous(DayOfWeek) 저번 요일
previousOrSame(DayOfWeek) 저번 요일 (오늘 포함)

예시코드

public class TimeTest {

  public static void localDateTimeTest() {
    LocalDateTime dateTime = LocalDateTime.now();
    dateTime = dateTime.plusWeeks(2);
    dateTime = dateTime.minusWeeks(2).plusHours(3);
    dateTime = dateTime.plusMinutes(30);
    dateTime = dateTime.withMonth(5);

    //작성 기준 오늘이 수요일인데 nextOrSame인 경우 오늘이다. next인 경우는 다음주 수요일
    LocalDateTime dateTime2 = dateTime.with(TemporalAdjusters.nextOrSame(DayOfWeek.WEDNESDAY));

  }
}

2.5 날짜와 시간 비교

LocalDate, LocalDateTime, ZonedDateTime의 isAfter(ChronoLocalDate ohter), isBefore(ChronoLocalDate ohter), isEqual(ChronoLocalDate other) 메서드 이용하여 날짜를 비교할 수 있다. 리턴 타입은 boolean이다.

또한 LocalTime은 isAfter(LocalTime other), isBefore(LocalTime other) 메서드를 이용해 시간을 비교할 수 있다. 리턴 타입은 역시 boolean

클래스 리턴 타입 매서드(매개 변수) 설명
LocalDate
LocalDateTime
ZonedDateTime
boolean isAfter(ChronoLocalDate) 이후 날짜인지 비교
isBefore(ChronoLocalDate) 이전 날짜인지 비교
isEqual(ChrononoLocalDate) 같은 날짜인지 비교
LocalTime boolean isAfter(LocalTime) 이후 시간인지 비교
isBefore(LocalTime) 이전 시간인지 비교

예시 코드

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.Test;

public class DateTimeTest {

  @Test
  public void testCompareDate() {
    LocalDate localDate = LocalDate.now();
    LocalDateTime localDateTime = LocalDateTime.now();
    ZonedDateTime zonedDateTime = ZonedDateTime.now();

    LocalDate past = LocalDate.of(2018, 11, 11);
    LocalDateTime future = LocalDateTime.of(2022, 12, 25, 12, 0, 0);
    ZonedDateTime now = ZonedDateTime.now();

    assertTrue(localDate.isAfter(past));       
    assertFalse(localDateTime.isAfter(future));
    assertTrue(zonedDateTime.isEqual(now));
    assertTrue(localDate.isBefore(future)); //컴파일 오류 : 같은 클래스끼리 비교가능
    assertTrue(localDate.isEqual(now));     //컴파일 오류 : 같은 클래스끼리 비교가능
  }

  @Test
  public void testCompareTime() {
    LocalTime localTime = LocalTime.now();

    LocalTime past = LocalTime.of(12, 0, 0);

    assertTrue(localTime.isAfter(past));
  }
}

2.6 날짜와 시간 차이 계산하기

LocalDate는 until(ChronoLocalDate endDateExclusive) 메서드를 통해 날짜 차이를 계산할 수 있다. 리턴 타임은 java.time.Period 이다. Period 클래스의 getYears(), getMonths(), getDays() 메서드를 통해 년, 월, 일의 차이를 계산할 수 있다.

또한 Period 클래스의 between(LocalDate startDateInclusive, LocalDate endDateInclusive) 메서드를 사용해서도 날짜 차이를 구할 수 있다. 리턴 타입은 Period 이다.

클래스 리턴 타입 메서드(매개 변수) 설명
LocalDate Period until(ChronoLocalDate) 날짜 차이
Period between(LocalDate, LocalDate)

예시 코드

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.Test;

public class DateTimeTest {

  @Test
  public void testCalculateDifferenceOfDate() {
    LocalDate localDate = LocalDate.now();

    LocalDate past = LocalDate.of(2017, 8, 15);
    LocalDate future = LocalDate.of(2020, 12, 25);

    //LocalDate의 until() 사용
    Period differences = localDate.until(past);
    assertThat(differences.getYears(), is(-3));
    assertThat(differences.getMonths(), is(-2));
    assertThat(differences.getDays(), is(-27));

    //Period의 between() 사용
    differences = Period.between(localDate, past);
    assertThat(differences.getYears(), is(-3));
    assertThat(differences.getMonths(), is(-2));
    assertThat(differences.getDays(), is(-27));

    //LocalDate의 until() 사용
    differences = localDate.until(future);
    assertThat(differences.getYears(), is(0));
    assertThat(differences.getMonths(), is(1));
    assertThat(differences.getDays(), is(14));

    //Period의 between() 사용
    differences = Period.between(localDate, future);
    assertThat(differences.getYears(), is(0));
    assertThat(differences.getMonths(), is(1));
    assertThat(differences.getDays(), is(14));
  }
}

그런데 이 경우에는 전체 시간을 기준으로 계산할 수가 없다. 2020-11-11과 2020-12-25는 1개월 14일 차이나지만 44일 차이나기도 한다. 44를 구하기 위해서 ChronoUnit.DAYS의 between(Temporal temporal1Inclusive, Temporal temporal2Exclusive) 메서드를 사용한다.

ChronoUnit 설명
ChronoUnit.YEARS 전체 년 차이
ChronoUnit.MONTHS 전체 월 차이
ChronoUnit.DAYS 전체 일 차이
ChronoUnit.HOURS 전체 시간 차이
ChronoUnit.MINUTES 전체 분 차이
ChronoUnit.SECONDS 전체 초 차이

예시 코드

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.Test;

public class DateTimeTest {

  @Test
  public void testCalculateDifferenceOfDate() {
    LocalDate localDate = LocalDate.now();

    LocalDate past = LocalDate.of(2017, 8, 15);
    LocalDate future = LocalDate.of(2020, 12, 25);

    assertThat(ChronoUnit.YEARS.between(localDate,future), is(0L));
    assertThat(ChronoUnit.MONTHS.between(localDate,future), is(1L));
    assertThat(ChronoUnit.DAYS.between(localDate,future), is(44L));
    //until(Temporal endExclusive, TemporalUnit unit)을 사용해도 됨
    assertThat(localDate.until(future, ChronoUnit.DAYS), is(44L));
  }
}

시간 차이는 LocalTime, LocalDateTime, ZonedDateTime의 until(Temporal endExclusive, TemporalUnit unit)메서드를 통해 구할 수 있다. 리턴 타입은 long이다. TemporalUnit 인터페이스의 구현테인 ChronoUnit을 이용하면 된다.

또 다른 방법으로 java.time.Duration 클래스의 between(Temporal startInclusive, Temporal endExclusive) 메서드를 이용해서 시간 차이를 구할 수 있다. 리턴 타입은 Duration이다.

클래스 리턴 타입 메서드(매개 변수) 설명
LocalTime
LocalDateTime
ZonedDateTime
long until(Temporal, TemporalUnit) 시간 차이
Duration Duration between(Temporal, Temporal)

예시 코드

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.Test;

public class DateTimeTest {

  @Test
  public void testCalculateDifferenceOfTime() {
    LocalTime localTime = LocalTime.now();
    LocalDateTime localDateTime = LocalDateTime.now();

    LocalTime past = LocalTime.of(8, 21, 12);
    LocalDateTime future = LocalDateTime.of(LocalDate.now(), LocalTime.of(23, 59, 59));

    assertThat(localTime.until(past, ChronoUnit.HOURS), is(-13L));
    assertThat(Duration.between(localTime, past).toHours(), is(-13L));

    assertThat(localDateTime.until(future, ChronoUnit.MINUTES), is(134L));
    assertThat(Duration.between(localDateTime, future).toMinutes(), is(134L));

    Duration differences = Duration.between(localDateTime, future);
    long seconds = differences.getSeconds();
  }
}

2.7 파싱과 포맷팅

LocalDate, LocalTime, LocalDateTime, ZonedDateTime 클래스의 parse(CharSequence), parse(CharSequence, DateTimeFormatter) 메서드를 통해 문자열을 클래스로 파싱할 수 있다. DateTimeFormatter는 static 메서드인 ofPattern()을 사용한다.

parse() 메서드에서 기본 포맷은 Date는 yyyy-MM-dd이고, Time은 HH:mm:ss이다. 이외의 포맷으로 파싱을 할 경우 DateTimeFormmater를 사용한다.

클래스 리턴 타입 메서드(매개 변수)
LocalDate
LocalTime
LocalDateTime
ZonedDateTime
LocalDate
LocalTime
LocalDateTime
ZonedDateTime
parse(CharSequence)
parse(CharSequence, DateTimeFormatter)

예시 코드

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.Test;

public class DateTimeTest {

  @Test
  public void testParseStringToDateAndTime() {
    String dateNow = "2020-11-11";
    String timeNow = "21:53:00";
    LocalDate localDate = LocalDate.parse(dateNow);
    LocalTime localTime = LocalTime.parse(timeNow);
    LocalDateTime localDateTime = LocalDateTime.parse(dateNow + "T" + timeNow);

    dateNow = "201111";
    timeNow = "21-53-12";
    assertThat(LocalDate.parse(dateNow, DateTimeFormatter.ofPattern("yyMMdd")),
        is(LocalDate.of(2020, 11, 11)));
    assertThat(LocalTime.parse(timeNow, DateTimeFormatter.ofPattern("HH-mm-ss")),
        is(LocalTime.of(21, 53, 12)));
  }
}

또한 LocalDate, LocalTime, LocalDateTime, ZonedDateTime 클래스의 format(DateTimeFormatter formatter) 메서드를 사용해서 원하는 문자열로 변환할 수 있다.

클래스 리턴 타입 메서드(매개 변수)
LocalDate
LocalTime
LocalDateTime
ZonedDateTime
String format(DateFormtter)

예시 코드

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.Test;

public class DateTimeTest {

  @Test
  public void testFormatDateAndTimeToString() {
    LocalDate localDate = LocalDate.now();
    LocalTime localTime = LocalTime.now();

    String date = localDate.format(DateTimeFormatter.ofPattern("yyyy년 MM월 dd일"));
    String time = localTime.format(DateTimeFormatter.ofPattern("H시 m분"));

    assertThat(date, is("2020년 11월 12일"));
    assertThat(time, is("1시 8분"));
  }
}

3. 참고자료

  • 자바의 정석

'Java > Java' 카테고리의 다른 글

[Servlet/JSP] JSP를 서블릿으로 (Jasper)  (0) 2024.04.04
[Java] Map 사용법(1) - Map 정렬  (0) 2020.11.17
[Java] Date, Calendar 클래스  (0) 2020.10.31

1. Date 클래스

공식 문서

docs.oracle.com/javase/8/docs/api/java/util/Date.html

 

Date (Java Platform SE 8 )

The class Date represents a specific instant in time, with millisecond precision. Prior to JDK 1.1, the class Date had two additional functions. It allowed the interpretation of dates as year, month, day, hour, minute, and second values. It also allowed t

docs.oracle.com

public class Date
extends Object
implements Serializable, Cloneable, Comparable<Date>

The class Date represents a specific instant in time, with millisecond precision.
Prior to JDK 1.1, the class Date had two additional functions. It allowed the interpretation of dates as year, month, day, hour, minute, and second values. It also allowed the formatting and parsing of date strings. Unfortunately, the API for these functions was not amenable to internationalization. As of JDK 1.1, the Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings. The corresponding methods in Date are deprecated.

JDK 1.1 이전에는 Date 클래스를 사용했지만, 1.1에 추가된 Calendar 클래스를 사용해서 잘 사용하지 않는다.(deprecated)

그래도 써보자

import java.util.Date;
import org.junit.jupiter.api.Test;

public class DateTest {

  @Test
  public void simpleDateTest() {
    Date date = new Date();
    System.out.println(date.toString());
  }
}

//결과 : Sat Oct 31 15:34:04 KST 2020

 getTime, getDate.. 등 메서드를 사용해보려했는데 대부분 deprecated라 그냥 넘어간다.


2. Calendar 클래스

공식 문서

https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html

 

Calendar (Java Platform SE 7 )

Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields. For example, to roll the current date up by one day, you can achieve it by calling: roll(Calendar.DATE, true). When rolling on the year or Calendar.YE

docs.oracle.com

public abstract class Calendar
extends Object
implements Serializable, Cloneable, Comparable<Calendar>

The Calendar class is an abstract class that provides methods for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next week. An instant in time can be represented by a millisecond value that is an offset from the Epoch, January 1, 1970 00:00:00.000 GMT (Gregorian).

The class also provides additional fields and methods for implementing a concrete calendar system outside the package. Those fields and methods are defined as protected.

Like other locale-sensitive classes, Calendar provides a class method, getInstance, for getting a generally useful object of this type. Calendar's getInstance method returns a Calendar object whose calendar fields have been initialized with the current date and time: Calendar rightNow = Calendar.getInstance();

A Calendar object can produce all the calendar field values needed to implement the date-time formatting for a particular language and calendar style (for example, Japanese-Gregorian, Japanese-Traditional). Calendar defines the range of values returned by certain calendar fields, as well as their meaning. For example, the first month of the calendar system has value MONTH == JANUARY for all calendars. Other values are defined by the concrete subclass, such as ERA. See individual field documentation and subclass documentation for details.

static field로 year, month, date, dateOfWeek등이 있고, get() 메서드를 통해 년, 월, 일 등을 호출할 수 있다. 추상 클래스이기 때문에 new Calendar()로 선언할 수 없고, 내부 메서드인 getInstance()를 통해 선언할 수 있다.

예제

www.codewars.com/kata/56eb0be52caf798c630013c0

 

Codewars: Achieve mastery through challenge

Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.

www.codewars.com

년을 입력으로 해당 해에 13일 금요일이 몇번 있는지 계산하는 문제이다. Calendar클래스를 통해 구해보자

import java.util.Calendar;

public class Kata {

  public static int unluckyDays(int year) {
    Calendar cal = Calendar.getInstance();
   
    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.DATE, 13);
    int unluckyCount = 0;
    
    for (int month = 0; month < 12; month++) {
      cal.set(Calendar.MONTH, month);
      int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
      if(dayOfWeek == 6) {
        unluckyCount++;
      }
    }
    return unluckyCount;
  }
}

 getInstance() 메서드로 선언 후, 년과, 일을 set()메서드로 설정한다. 그 후에 반복문을 통해 month를 0~11까지 옮겨가며 13일이 금요일인지 확인하고 금요일이 맞다면 count를 1 증가시켜준다.

문제를 풀어보니 감이 오긴하는데, year과 date는 그대로 사용하는데 month는 0을 입력해야 1월, 1을 입력해야 2월... 이런식이기 때문에 좀 헷갈린다. 


3. Date, Calendar 클래스의 문제점

애매한 상수

날짜 연산을 컴파일 시점에서 오류를 확인 할 수 없다

Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONDAY, 1) // 월요일 하루를 더하는건가?

 

월 계산

위에서 본 것 처럼 Calendar 월 표기는 0이 1월, 11이 12월이다.

    /**
     * Value of the {@link #MONTH} field indicating the
     * first month of the year in the Gregorian and Julian calendars.
     */
    public final static int JANUARY = 0;

    /**
     * Value of the {@link #MONTH} field indicating the
     * second month of the year in the Gregorian and Julian calendars.
     */
    public final static int FEBRUARY = 1;

    /**
     * Value of the {@link #MONTH} field indicating the
     * third month of the year in the Gregorian and Julian calendars.
     */
    public final static int MARCH = 2;

그냥 1 빼주면 되지않나? 라고 생각할 수 도 있는데, 그걸 알지 못하고 사용하면 매우 불편함

 

불변(immutable)객체가 아니다.

set()메서드로 얼마든지 수정이 가능하다. 크게 문제가 되나? 생각할 수도 있는데 다른 코드에서도 공유한다면 한 쪽에서 변경한 값이 전체에 영향을 줄 수도 있다. 그리고 멀티쓰레드 환경에서 안전하지 못하다.

 

윤달을 고려하지않음


4. 그러면? (+ 뇌피셜)

자바에서 시간과 날짜를 계산하기 위해 제공하는 API가 있다. 대표적으로 Date와 Calendar인데, 평소에 나도 자주 사용하고, 날짜와 시간을 구할 일이 있을 때, 구글 검색을 해보면 대부분 Date, Calendar API사용에 대해 나온다. 

그런데 Date 클래스는 JDK 1.0, Calendar 클래스는 JDK 1.1부터 사용되었기 때문에 상당히 구식이고 문제점이 많다고 한다. 그래서 JDK 1.8이전에는 대부분 Joda-Time이라는 오픈소스 라이브러리를 사용한다고 한다. 

이를 잘 반영했는지 JDK 1.8부터는 Time 패키지의 LocalTime, LocalDate, LocalDateTime 등 개선된 클래스를 제공한다.

Date 클래스와 Calendar 간략하게만 알아봤는데, JDK 1.8에서 제공하는 Time 패키지를 더 공부하는게 나을것 같다. 더 간편하고 안전하다고 한다.

1. 문제

https://programmers.co.kr/learn/courses/30/lessons/67257

 

코딩테스트 연습 - 수식 최대화

IT 벤처 회사를 운영하고 있는 라이언은 매년 사내 해커톤 대회를 개최하여 우승자에게 상금을 지급하고 있습니다. 이번 대회에서는 우승자에게 지급되는 상금을 이전 대회와는 다르게 다음과

programmers.co.kr

문제 설명

IT 벤처 회사를 운영하고 있는 라이언은 매년 사내 해커톤 대회를 개최하여 우승자에게 상금을 지급하고 있습니다. 이번 대회에서는 우승자에게 지급되는 상금을 이전 대회와는 다르게 다음과 같은 방식으로 결정하려고 합니다. 해커톤 대회에 참가하는 모든 참가자들에게는 숫자들과 3가지의 연산 문자 (+, -, *) 만으로 이루어진 연산 수식이 전달되며, 참가자의 미션은 전달받은 수식에 포함된 연산자의 우선순위를 자유롭게 재정의하여 만들 수 있는 가장 큰 숫자를 제출하는 것입니다. 단, 연산자의 우선순위를 새로 정의할 때, 같은 순위의 연산자는 없어야 합니다. 즉, + > - > * 또는 - > * > + 등과 같이 연산자 우선순위를 정의할 수 있으나 +,* > - 또는 * > +,-처럼 2개 이상의 연산자가 동일한 순위를 가지도록 연산자 우선순위를 정의할 수는 없습니다. 수식에 포함된 연산자가 2개라면 정의할 수 있는 연산자 우선순위 조합은 2! = 2가지이며, 연산자가 3개라면 3! = 6가지 조합이 가능합니다. 만약 계산된 결과가 음수라면 해당 숫자의 절댓값으로 변환하여 제출하며 제출한 숫자가 가장 큰 참가자를 우승자로 선정하며, 우승자가 제출한 숫자를 우승상금으로 지급하게 됩니다.

 

예를 들어, 참가자 중 네오가 아래와 같은 수식을 전달받았다고 가정합니다.

"100-200*300-500+20"

일반적으로 수학 및 전산학에서 약속된 연산자 우선순위에 따르면 더하기와 빼기는 서로 동등하며 곱하기는 더하기, 빼기에 비해 우선순위가 높아 * > +,- 로 우선순위가 정의되어 있습니다. 대회 규칙에 따라 + > - > * 또는 - > * > + 등과 같이 연산자 우선순위를 정의할 수 있으나 +,* > - 또는 * > +,-+,-처럼 2개 이상의 연산자가 동일한 순위를 가지도록 연산자 우선순위를 정의할 수는 없습니다. 수식에 연산자가 3개 주어졌으므로 가능한 연산자 우선순위 조합은 3! = 6가지이며, 그중+ > - > * 로 연산자 우선순위를 정한다면 결괏값은 22,000원이 됩니다. 반면에 * > + > - 로 연산자 우선순위를 정한다면 수식의 결괏값은 -60,420이지만, 규칙에 따라 우승 시 상금은 절댓값인 60,420원이 됩니다.

 

참가자에게 주어진 연산 수식이 담긴 문자열 expression이 매개변수로 주어질 때, 우승 시 받을 수 있는 가장 큰 상금 금액을 return 하도록 solution 함수를 완성해주세요.

 

제한 사항

  • expression은 길이가 3이상 100 이하인 문자열이다.
  • expression은 공백문자, 괄호 문자 없이 오로지 숫자와 3가지의 연산자(+, -, *)만으로 이루어진 올바른 중위 표기법으로 표현된 연산식이다. 잘못된 연산식은 주어지지 않는다.
    • 즉, 402+-561* 같은 식은 주어지지 않는다.
    • -56+100 처럼 피연산자가 음수인 수식도 입력으로 주어지지 않는다.
  • expression은 적어도 1개 이상의 연산자를 포함한다.
  • 연산자 우선순위를 어떻게 적용하더라도, expression의 중간 계산 값과 최종 결괏값은 절댓값이 2^63 - 1 이하가 되도록 입력이 주어진다.
  • 같은 연산자끼리는 앞에 있는 것의 우선순위가 더 높다.

입출력 예

1. 100-200*300-500+20 👉 * > + > - 순으로 연산자 우선순위를 정했을 때
100-(200*300)-500+20
100-60000-(500+20)
(100-60000)-520
(-59900-520)
-60420
절댓값 60420이 가장 큰 값이다.

 

2. 50*6-3*2 👉 - > * 순으로 연산자 우선순위를 정했을 때
50*(6-3)*2
(50*3)*2
150*2
300
절댓값 300이 가장 큰 값이다.


2. 어떻게 풀까?

  • 우선 사용되는 연산자의 종류는 최소 1개 최대 3개이다. 그러면, 연산자를 1개 사용했을 때는 우선순위 경우가 한 가지뿐이고, 2개를 사용했을 때는 우선 순위 경우가 두 가지, 3개를 사용했을 때는 6가지가 나온다.
  • 일단 우선순위 list나 array를 만들어 저장한뒤 우선순위 경우에 따라 주어진 expression을 계산하고 최댓값을 찾는 방법으로 풀면 될 것 같다.
  • 우선순위 list를 만드는 거는 순열을 이용하면 금방 만들 것 같아서 바로 해결, 계산하는 과정은 고민을 좀 많이 했다. 처음에는 정규식을 이용해서 replaceAll() 메서드로 할 수 있을까? 생각해서 접근해봤는데 안돼서 포기
  • 그럼 다른 방법이 있나??? 음.. expression을 연산자와 숫자로 구분해서 list를 만든 다음에 연산자에 해당하는 숫자들을 계산하면 될 것 같다. 연산자가 현재 우선순위에 일치하면 계산을 하고 list에서 빼준다. 숫자는 계산한 값을 해당 index에 삽입하면 될 것 같다.

3. 코드

 

TDD 연습을 위해 간단한 테스트 코드를 먼저 작성하고, 테스트 통과를 위한 코드를 작성 👉 다른 테스트 작성, 테스트 통과하도록 수정하는 과정을 반복했다.

 

테스트코드

package programmers.level2.수식최대화_20201030;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;

import org.junit.Test;

public class SolutionTest {

  @Test
  public void testWhenOnlyOneOperation() {
    assertThat(new Solution().solution("50*6*3*2"), is(1800L));
  }

  @Test
  public void testWhenTwoOperations() {
    assertThat(new Solution().solution("50*6-3*2"), is(300L));
  }

  @Test
  public void testWhenThreeOperations() {
    assertThat(new Solution().solution("100-200*300-500+20"), is(60420L));
  }
}

 

 

실제 코드

package programmers.level2.수식최대화_20201030;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class Solution {

  Set<String> operationPrioritySet;
  boolean[] visit;

  public long solution(String expression) {
    makeOperatorPriority(expression);

    long result = 0;
    for (String operationPriority : operationPrioritySet) {
      result = Math.max(result, calculateByPriority(expression, operationPriority));
    }
    return result;
  }

  private void makeOperatorPriority(String expression) {
    String distinctOperator = Arrays.stream(
        expression.replaceAll("[\\d]", "").split(""))
        .distinct()
        .collect(Collectors.joining());
    visit = new boolean[distinctOperator.length()];
    operationPrioritySet = new HashSet<>();
    permutation("", distinctOperator);
  }

  private long calculateByPriority(String expression, String operatorPriority) {

    List<Long> numbers = makeNumbers(expression);
    List<String> operators = makeOperators(expression);
    operators.remove(0);

    for (int i = 0; i < operatorPriority.length(); i++) {
      String targetPriorityOperator = operatorPriority.charAt(i) + "";
      while (operators.contains(targetPriorityOperator)) {
        int index = operators.indexOf(targetPriorityOperator);
        calculate(numbers, index, targetPriorityOperator);
        operators.remove(index);
      }
    }

    return Math.abs(numbers.get(0));
  }

  private void calculate(List<Long> numbers, int index, String operator) {
    if (operator.equals("*")) {
      numbers.add(index, numbers.remove(index) * numbers.remove(index));
    } else if (operator.equals("+")) {
      numbers.add(index, numbers.remove(index) + numbers.remove(index));
    } else {
      numbers.add(index, numbers.remove(index) - numbers.remove(index));
    }
  }

  private List<String> makeOperators(String expression) {
    return new ArrayList<>(Arrays.asList(expression.split("\\d{1,3}")));
  }

  private List<Long> makeNumbers(String expression) {
    return new ArrayList<>(Arrays.asList(
        Arrays.stream(expression.split("\\D"))
            .mapToLong(Long::parseLong)
            .boxed()
            .toArray(Long[]::new)));
  }

  private void permutation(String current, String operations) {
    if (current.length() == operations.length()) {
      operationPrioritySet.add(current);
      return;
    }

    for (int i = 0; i < operations.length(); i++) {
      if (!visit[i]) {
        visit[i] = true;
        permutation(current + operations.charAt(i), operations);
        visit[i] = false;
      }
    }
  }
}

4. 느낀 점

 

이 문제를 풀기 전에 정규 식중 전방 일치 관련 글을 봐서 정규식을 이용해서 풀면 풀 수 있지 않을까? 고민을 좀 오래 했었다. 여러 시도를 해봤는데 잘 안돼서 접고 list에 숫자, 연산자를 담아서 계산하는 방법으로 바꿨다. 판단을 빠르게 하는 게 중요한 듯

 

카카오 인턴 지원했을 때 이 문제를 풀었는데, 통과를 못했다. 몇 개는 통과하고 몇개는 실패해서.. 그때 내가 어떻게 풀었는지 기억이 잘 안 나는데, 어쨌든 이번엔 다 통과해서 기분이 좋다.

 

그때 어떻게 풀었는지 기록해뒀으면 비교 잘했을 텐데 그건 좀 아쉽다.

 

Level 2인데 이런 문제라니.. 카카오 x발..

+ Recent posts