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. 참고자료

  • 자바의 정석

사실 여행이라기 보다 걍 친구집 놀러간건데

우테코 자소서 제출하고 나서

친구가 대구가자고 꼬드기길래 갈까 말까 하다가 에라 모르겠다 하고 갔다 ㅋㅋㅋㅋ

대구 가는길.. 타고나서 아 가지말걸 후회 쥰내했다 ㅋㅋㅋㅋ
서문시장? 거기 국수가 맛있다길래 먹어봄. 
사실 시장이라 위생이 좋진않다 걍 싼마이인듯
꺼억
3개 시켜도 다 먹는다고 시켰는데 남음

 

친구 방 너무 춥다..
경대 근처 육회집인데 너무 맛있어서 술을 너무 많이 먹음

 

사진을 너무 안찍었는데.. 재밌었다 일단

근데 노트북을 들고가서 하루에 한 문제라도 풀걸그랬다. 개백수인데 너무 놀기만하니까 올라와서 현타가 존나왔음..

다시 열공.. 취준합시다..

'일상' 카테고리의 다른 글

201030. Github Page와 동시운영..  (0) 2020.10.30

1. 문제

programmers.co.kr/learn/courses/30/lessons/17681

 

코딩테스트 연습 - [1차] 비밀지도

비밀지도 네오는 평소 프로도가 비상금을 숨겨놓는 장소를 알려줄 비밀지도를 손에 넣었다. 그런데 이 비밀지도는 숫자로 암호화되어 있어 위치를 확인하기 위해서는 암호를 해독해야 한다. 다

programmers.co.kr

문제 설명

네오는 평소 프로도가 비상금을 숨겨놓는 장소를 알려줄 비밀지도를 손에 넣었다. 그런데 이 비밀지도는 숫자로 암호화되어 있어 위치를 확인하기 위해서는 암호를 해독해야 한다. 다행히 지도 암호를 해독할 방법을 적어놓은 메모도 함께 발견했다.

  1. 지도는 한 변의 길이가n인 정사각형 배열 형태로, 각 칸은공백(" ") 또는 벽("#") 두 종류로 이루어져 있다.
  2. 전체 지도는 두 장의 지도를 겹쳐서 얻을 수 있다. 각각지도 1과지도 2라고 하자. 지도 1 또는 지도 2 중 어느 하나라도 벽인 부분은 전체 지도에서도 벽이다. 지도 1과 지도 2에서 모두 공백인 부분은 전체 지도에서도 공백이다.
  3. 지도 1과지도 2는 각각 정수 배열로 암호화되어 있다.
  4. 암호화된 배열은 지도의 각 가로줄에서 벽 부분을1, 공백 부분을0으로 부호화했을 때 얻어지는 이진수에 해당하는 값의 배열이다.

네오가 프로도의 비상금을 손에 넣을 수 있도록, 비밀지도의 암호를 해독하는 작업을 도와줄 프로그램을 작성하라.

제한 사항

입력 형식

입력으로 지도의 한 변 크기 n 과 2개의 정수 배열arr1,arr2가 들어온다.

  • 1 ≦n≦ 16

  • arr1,arr2는 길이n인 정수 배열로 주어진다.

  • 정수 배열의 각 원소 x를 이진수로 변환했을 때의 길이는n이하이다. 즉, 0 ≦x≦ 2n- 1을 만족한다.

출력 형식

원래의 비밀지도를 해독하여'#',공백(" ")으로 구성된 문자열 배열로 출력하라.

입출력 예

매개 변수
n 5
arr1 [9, 20, 28, 18, 11]
arr2 [30, 1, 21, 17, 28]
출력 ["#####", "# # #", "### #", "#  ##", "#####"]

2. 어떻게 풀까?

  • 입력으로 int 배열을 주니까 배열 element를 binary로 만들어서 두 binary를 다시 Integer나 Long으로 만들어서 합치고, 각 bit가 1 혹은 2면 "#"으로 치환, 0이면 공백(" ")으로 치환하면 되겠다.
    • 예를 들면, 9는 1001이고, 30은 11110이니까 합치면 12111이고 치환하면 "#####"이 된다.
  • 그런데 입력 조건에서 bit 길이가 1~16인데 길이가 16인 binary는 Integer나 Long으로 만들 수 없으니 두 binary를 합치는 것은 불가능한 것 같다.
    • 100101010101101 + 10101001010101000101의 길이는 Integer, Long으로 표현할 수 없음
  • 그러면 binary를 Integer나 Long으로 만들어서 더하지 말고, 그냥 각 binary의 bit끼리 더해서 0이 아니면 "#", 0이면 공백(" ")으로 치환하자.
  • 각 binary가 자릿수가 다를 수 있다.
    • 입력 n값이 6이어도, int 배열의 element가 9, 1, 14면 1001, 1, 1110인데 길이가 6이 아니기 때문에 앞에 0을 붙여줘야 한다.

3. 코드

실제 코드만 첨부

실제 코드

public class Solution {

  public String[] solution(int n, int[] arr1, int[] arr2) {
    String[] result = new String[n];
    for (int i = 0; i < result.length; i++) {
      String[] digits = new String[n];
      String temp1 = getBinaryString(n, arr1[i]);
      String temp2 = getBinaryString(n, arr2[i]);
      for (int j = 0; j < digits.length; j++) {
        digits[j] = "" + (Character.getNumericValue(temp1.charAt(j))
            + Character.getNumericValue(temp2.charAt(j)));
      }
      result[i] = String.join("", digits).replaceAll("[1-9]", "#").replaceAll("0", " ");
    }
    return result;
  }

  private String getBinaryString(int length, int number) {
    StringBuilder binary = new StringBuilder(Integer.toBinaryString(number));
    while (binary.length() < length) {
      binary.insert(0, "0");
    }
    return binary.toString();
  }

}

toBinaryString()을 이용해서 binary로 바꾼 후 자릿수를 맞춰주는 작업을 하기 위해 getBinaryString() 메서드를 만들었고, 두 bit를 합쳐서 0이면 공백(" "), 0이 아니면 "#"으로 치환했다.


4. 느낀 점

  • 문제를 풀고 나니까 코드가 많이 더럽다. temp1, temp2 뭐 이상한 변수명을 사용한 것도 그렇고, 위 방법 말고 더 간단한 방법이 분명히 있는데, 그냥 "문제 풀었다!"라는 생각에 바로 제출했다.
  • 생각해보면 굳이 합치지 않고, 각 bianry의 bit가 모두 0이면 공백, 0이 아니면 "#"으로 만들어줘도 됐을 텐데
  • 다른 풀이를 보니까 각 int 배열의 element를 or연산('|')을 이용했다. 이 방법이 훨씬 가독성이 좋은 것 같다. (코드는 따로 안 올림.. 나중에 다시 풀어보기 위해)

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://www.codewars.com/kata/557f6437bf8dcdd135000010

 

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

 

문제 설명

n mathematics, the factorial of integer n is written as n!. It is equal to the product of n and every integer preceding it. For example: 5! = 1 x 2 x 3 x 4 x 5 = 120

Your mission is simple: write a function that takes an integer n and returns the value of n!.

You are guaranteed an integer argument. For any values outside the non-negative range, return null, nil or None (return an empty string "" in C and C++). For non-negative numbers a full length number is expected for example, return 25! = "15511210043330985984000000" as a string.

For more on factorials, see http://en.wikipedia.org/wiki/Factorial

NOTES:

  • The use of BigInteger or BigNumber functions has been disabled, this requires a complex solution

  • I have removed the use of require in the javascript language.

입출력 예

1! 👉 "1"

5! 👉 "120"

9! 👉 "362880"

15! 👉 "1307674368000"

25! 👉 "15511210043330985984000000"

 


2. 어떻게 풀까?

 

간단하게 팩토리얼 구하는 함수를 구현해라는 문제인데, NOTE를 보면 BigInteger나 BigNumber를 쓰지 말라고 한다. 이러면 방법을 잘 모르겠다. 처음에는 bit별로 나누어서 list에 저장하고 bit끼리 더하면 되겠다 생각했는데 생각처럼 잘 되지 않았다. 그래서 결국 답을 봤다.

근데 답보니까 다 BigInteger를 썼는데 ㅋㅋ.. 그중에 안쓴 답이 있어서 며칠 동안 다시 풀면서 직접 코드를 짜 봤다.

 


3. 코드

 

답을 보고 내가 리팩터링 한 코드

 

테스트 코드

package doNotSolve.codewars.kyu4.largeFactorials_20201029;

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

import org.junit.Test;

public class KataTest {

  @Test
  public void test1() {
    assertThat(Kata.factorial(1), is("1"));
  }

  @Test
  public void test2() {
    assertThat(Kata.factorial(2), is("2"));
  }

  @Test
  public void test3() {
    assertThat(Kata.factorial(5), is("120"));
  }

  @Test
  public void test4() {
    assertThat(Kata.factorial(15), is("1307674368000"));
  }

  @Test
  public void test5() {
    assertThat(Kata.factorial(25), is("15511210043330985984000000"));
  }
}

 

실제 코드

package doNotSolve.codewars.kyu4.largeFactorials_20201029;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class KataAgain {

  static int carry;

  public static String factorials(int n) {
    List<Integer> digits = new ArrayList<>();
    int value = n;
    saveDigits(digits, value);

    for (value = n - 1; value > 1; value--) {
      List<Integer> targetDigits = new ArrayList<>();
      carry = 0;
      saveDigits(digits, targetDigits, value);

      saveDigits(targetDigits, carry);
      digits = targetDigits;
    }

    return getResultString(digits);
  }

  private static void saveDigits(List<Integer> digits, List<Integer> targetDigits, int value) {
    for (Integer digit : digits) {
      int product = value * digit + carry;
      targetDigits.add(product % 10);
      carry = product / 10;
    }
  }

  private static void saveDigits(List<Integer> digits, int value) {
    if (value == 0) {
      return;
    }
    while (value > 0) {
      digits.add(value % 10);
      value /= 10;
    }
  }

  private static String getResultString(List<Integer> digits) {
    String reversedDigits = digits.stream().map(String::valueOf).collect(Collectors.joining());
    return new StringBuilder(reversedDigits).reverse().toString();
  }
}

4. 느낀 점

memoization 방법으로 팩토리얼을 구현하면 타입을 long으로 해도 20! 에서 오버플로우가 발생한다. 따라서 큰 값의 팩토리얼을 구하려면 BigInteger을 사용해왔는데 새로운 방법을 알게 되었다. 팩토리얼 외에도 피보나치수열도 이 방법으로 할 수 있지 않을까? 생각이 들었다.

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발..

올해 초에 Github Page 호스팅으로 블로그를 만들었다.

5월 까지는 꾸준히 글도 올리고 코드워즈 리뷰(?)도 매일 했었는데

그러고 끝.. 크게 활용을 안했다..

다시 하려고 하는데 jekyll serve로 테스트가 안됨.. 바로 git push하고 직접 페이지에서 확인해야함..

  • 이거는 실제로 그런게 아니라 나만 안되는거 같은데.. 해결방법을 찾아보려해도 못 찾겠다 ㅜ
    리마인드 하자는 마음으로 동시 운영하기로 함. 이것도 얼마나갈지... 열심히해보자
    어짜피 둘다 마크다운 되니까 복붙만 하면될듯.. 이미지 업로드는 오히려 이게 더 편하고

'일상' 카테고리의 다른 글

11/5 ~ 11/8 대구 여행  (5) 2020.11.11

+ Recent posts