본문 바로가기

프로그래밍/Scala

HW 1. Exercise 3

10월 첫째 날 기념으로 상콤하게 과제

가보자고

 

 

마지막 문제 

  /**
   * Exercise 3: Termination checker
   *
   * Find the first integer `n` which makes `pred(f^n(init))` True.
   *
   * For example, if pred(init), pred(f(init)), and pred(f(f(init))) is all False,
   *   and pred(f(f(f(init)))) gives the first True value, then return 3.
   * If pred(init) is True, return 0.
   *
   * f: repeating function
   * pred: Termination predicate. If p(n) returns True,
   * init: initial input
   *
   * We guarantee that every input in the test set will always terminate the checker if your checker is correct and efficient.
   **/
  def terminate(pred: Long => Boolean, f: Long => Long, init: Long): Long = ???

 

 

첫 번째 solution

def terminate(pred: Long => Boolean, f: Long => Long, init: Long): Long = {
  def count(pred: Long => Boolean, f: Long => Long, init: Long, num: Long = 0): Long = {
    if (pred(init)) num
    else {
      val new_init = f(init)
      val new_num = num + 1
      count(pred, f, new_init, new_num)
    }
  }

  count(pred, f, init)
}


def pred(n: Long): Boolean = n <= 1
def collatz(n: Long): Long = if (n % 2 == 0) n / 2 else 3 * n + 1

terminate(pred, collatz, 97)
terminate(pred, collatz, 77031)
terminate(pred, collatz, 989345275647L)

/*
val res0: Long = 118
val res1: Long = 350
val res2: Long = 1348
*/

 

10/2 새벽 코딩 신이 잠깐 왔나 보다

뭐지,,,,

이틀 동안 끙끙대던 문제를 2시간 만에  품

암튼 맘 편히 발 뻗고 잘 수 있겠다

행복행

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'프로그래밍 > Scala' 카테고리의 다른 글

HW 1. Exercise 1-2 보충  (1) 2022.10.02
Tail Recursion 추가 포스팅  (1) 2022.10.02
Recursion / Tail Recursion  (0) 2022.10.01
HW1. Exercise 2  (1) 2022.09.30
PART 1 - Blocks and Name Scoping (1)  (0) 2022.09.29