본문 바로가기
Ocaml

[99 Problems in OCaml] 11번, 12번, 13번 문제

by seungh2 2021. 9. 23.

99 Problems in OCaml

https://ocaml.org/learn/tutorials/99problems.html

 

99 problems – OCaml

Your Help is Needed Many of the solutions below have been written by Victor Nicollet. Please contribute more solutions or improve the existing ones. 99 Problems (solved) in OCaml This section is inspired by Ninety-Nine Lisp Problems which in turn was based

ocaml.org

 

11번 문제

  • encode
    • encode list
    • list에 대해 run-length encoding을 수행한 결과를 담은 list를 반환한다.

 

내가 구현한 코드

if문을 이용해서 run length encoding을 수행하였다.

 

정답 코드

정답 코드는 encode_sol함수 안에 원소의 개수에 따라 One 또는 Many를 반환하는 함수와 리스트의 원소를 보며 정답 리스트를 반환하는 함수 2개를 사용하였다.

 

test 결과

 

12번 문제

  • decode
    • decode list
    • run length encoding된 원소가 들은 list에 대해  decoding한 결과를 담은 list를 반환한다.

 

내가 구현한 코드

list의 원소가 One 타입인 경우에는 ::를 한번 수행하면 되지만 Many 타입인 경우에는 튜플의 첫번째 원소의 수만큼 ::를 수행해야하기 때문에 이를 수행하는 repeat함수를 만들어서 사용하였다.

 

test 결과

13번 문제

  • encode
    • encode list
    • list에 대해 run-length encoding을 수행한 결과를 담은 list를 반환한다.

사실 이 문제는 11번 문제와 뭐가 다른지 모르겠어서 정답을 봤다.

 

정답 코드

test 결과

 

728x90

댓글