2012-09-27 83 views
0
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 

我想要做的就是稱呼其爲comb(10,20)並得到同樣的結果。我試圖用rr替換cc,除了在簽名中,但它不起作用。組合:更改參數順序

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 

回答

1

你會需要更改子調用的順序:

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 
} 

這給了預期的結果:

comb(10, 20) // 184756 
+0

can你需要發佈整個功能嗎? – Andrew

1

我想補充,不害怕本地化:

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