Andrew
Andrew

Reputation: 6404

Combination: Change parameter order

def comb(c: Int, r: Int): Int = {
      if(r == 1) c
      else if(r < c) comb(c-1, r-1) + comb(c-1, r)
      else 1
}
comb(20,10) //184,756

What I'd like to do is to call it as comb(10,20) and get the same result. I tried to replace c with r and r with c except in the signature, but it doesn't work.

  def comb(c: Int, r: Int): Int = {
  if(c == 1) r
  else if(c < r) comb(r-1, c-1) + comb(r-1, c)
  else 1
  } 
  comb(10,20) //2 -> not right

Upvotes: 0

Views: 100

Answers (2)

som-snytt
som-snytt

Reputation: 39587

I would add, don't be afraid of local defs:

scala> def comb(c: Int, r: Int): Int = {
 |       if(r == 1) c
 |       else if(r < c) comb(c-1, r-1) + comb(c-1, r)
 |       else 1
 | }
comb: (c: Int, r: Int)Int

scala> comb(20,10) //184,756
res0: Int = 184756

scala> def cc(c: Int, r: Int): Int = {
     | def cc2(c: Int, r: Int): Int = {
     | if(r == 1) c
     | else if(r < c) comb(c-1, r-1) + comb(c-1, r)
     |  else 1
     | }
     | if (c < r) cc2(r,c) else cc2(c,r)
     | }
cc: (c: Int, r: Int)Int

scala> cc(20,10)
res1: Int = 184756

scala> cc(10,20)
res2: Int = 184756

Upvotes: 1

dhg
dhg

Reputation: 52691

You would also need to change the order in the sub-calls:

def comb(c: Int, r: Int): Int = {
  if (c == 1) r
  else if (c < r) comb(c - 1, r - 1) + comb(c, r - 1)
  else 1
}

This gives the expected result:

comb(10, 20)  // 184756

Upvotes: 1

Related Questions