Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

home / study / engineering / computer science / computer science questions and a

ID: 3751404 • Letter: H

Question

home / study / engineering / computer science / computer science questions and answers / Haskell Question Make A Function That Calculates The Number Of Combinations Of Choosing K Things ...

Your question has been answered

Let us know if you got a helpful answer. Rate this answer

Question: Haskell Question Make a function that calculates the number of combinations of choosing k things ...

Haskell Question

Make a function that calculates the number of combinations of choosing k things from a set of n distinct items.

Use the recursive relation C(n,k) = C(n-1,k-1) + C(n-1,k) for 0 < k < n.

Regarding input, you can assume that n is a positive integer, and 0 <= k <= n.

Example output:

> choose 4 0

1

> choose 4 1

4

> choose 4 2

6

Thanks

Explanation / Answer

The recursive function for the above question would be-

public int Calculate(int a, int b)

{

if(b==0 || a==b )

return 1;

else

return Calculate(a-1,b-1)+Calculate(a-1,b);

}

I'm also writing the whole program that I used for this below (in JAVA). You can refer to it for help-

import java.io.*;

public class Combinations

{

public static void main(String args[])throws IOException

{

int n,k;

BufferedReader pm=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter the total number of things");

n=Integer.parseInt(pm.readLine());

System.out.println("Enter the value of k");

k=Integer.parseInt(pm.readLine());

Combinations obj=new Combinations();

System.out.println(obj.Calculate(n,k));

}

public int Calculate(int a, int b)

{

if(b==0 || a==b )

return 1;

else

return Calculate(a-1,b-1)+Calculate(a-1,b);

}

}