Haskell程式實現nCr(r組合)


本教程討論了在Haskell程式語言中編寫程式以執行nCr組合。

nCr用於查詢從n個專案中選擇r個專案的方法數,前提是順序無關緊要。nCr定義為n!/(r!(n-r)!)。例如,從5個專案中選擇3個專案的方法數為5!/(3!(5-3)!),即10種方法。

在本教程中,我們將看到:

  • 查詢數字階乘的程式(查詢nCr組合的輔助函式)。
  • 查詢nCr組合的程式。

演算法步驟

  • 輸入或初始化變數n和r。
  • 實現計算nCr組合的邏輯。
  • 列印或顯示輸出。

示例1

查詢數字階乘的程式。

-- function declaration
factorial :: Int -> Int

-- function definition
factorial n = product [1..n]
main :: IO()
main = do
-- declaring and initializing variable
   let n = 5
-- computing factorial of variable n
   let fact = factorial n
-- printing the output
   print ("The factorial of the number " ++ show n ++ " is:")
   print(fact)

輸出

"The factorial of the number 5 is:"
120

在上面的程式中,我們聲明瞭一個名為factorial的函式,它接受一個整數作為引數並返回一個整數。在其函式定義中,接受一個整數引數n。此函式透過呼叫product函式並傳遞一個從1到n的整數列表作為引數來計算數字的階乘。product函式接受一個數字輸入列表作為引數,並返回列表中所有元素的乘積。該列表是使用“..”運算子生成的。從a到b建立列表的語法為a..b,其中a必須小於或等於b。連續元素的差值為1。此函式返回計算出的階乘。在主函式中,我們宣告並初始化了一個變數n,該變數需要計算其階乘。我們呼叫factorial函式並將n作為引數傳遞,並將返回的輸出載入到變數fact中。最後,使用print函式列印計算出的數字n的階乘。

注意 - show函式接受一個數字作為引數,並返回該數字的解析字串。“++”是Haskell中用於連線字串的運算子。

示例2

查詢nCr組合的程式。

-- function declaration
factorial :: Int -> Int

-- function definition
factorial n = product [1..n]

-- function declaration
findCombinations :: Int->Int->Int

-- function definition
findCombinations n r = div (factorial n) ((factorial r) * (factorial (n-r)))
main :: IO()
main = do
-- declaring and initializing variable
   let n = 5
   let r = 3
-- computing the nCr combinations
   let output = findCombinations n r
-- printing the output
   print ("The number of ways in which " ++ show r ++ " items can be selected from " ++ show n ++ " items is:")
   print(output)

輸出

"The number of ways in which 3 items can be selected from 5 items is:"
10

在上面的程式中,我們宣告並定義了一個名為factorial的函式,與前一個程式一樣,它是一個輔助函式,用於查詢nCr組合。我們聲明瞭一個名為findCombinations的函式,它接受兩個整數引數並返回一個整數。在其函式定義中,接受兩個整數引數n和r。nCr是使用邏輯n!/(r!(n-r)!)計算的。factorial函式被呼叫以計算數字的階乘。並返回計算出的組合。在主函式中,宣告並初始化了兩個整數引數(n和r)。findCombinations函式被呼叫,並將n和r作為引數傳遞。返回的輸出被載入到變數output中。最後,使用print函式列印輸出。

結論

在本教程中,我們討論了在Haskell程式語言中實現一個程式以執行nCr組合。

更新於: 2022年12月14日

352次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.