Home > front end >  How to write Combination and Permutation from 2 numbers n and k in Ruby/Python?
How to write Combination and Permutation from 2 numbers n and k in Ruby/Python?

Time:11-26

For example, if I have 100 distinguishable dogs and I want to randomly pick 3 of them. With a pocket-size calculator, I would do 100C3 or something similar. How can I do this in Ruby and Python?

CodePudding user response:

Ruby's Array methods combination, repeated_combination, permutation and repeated_permutation all return Enumerators. Enumerators have a size method, which returns the size of the enumerator, or nil if it can't be calculated lazily. Happily in these cases they can, for example:

#How many ways to take 12 random dogs out of 1000 :
puts (1..1000).to_a.combination(12).size # 1953840414726664053684327000

CodePudding user response:

Ruby has combination (and permutation):

(0...100).to_a.combination(3).to_a
(0...100).to_a.permutation(3).to_a

But if you randomly want to pick 3 dogs from that array, there is sample:

(0...100).to_a.sample(3)

CodePudding user response:

You would do this in python:

from math import comb

n_combinations = comb(100, 3)

Similarly, for permutations:

from math import perm

n_permutations = perm(100, 3)

perm and comb can be used only with python > 3.8. For older versions of python please use these functions:

from math import factorial

def comb(n, k):
    return factorial(n) // factorial(k) // factorial(n - k)

def perm(n, k=None):
    return factorial(n) // factorial(n - (k or n))

CodePudding user response:

Selecting 3 random dogs out of 100 without replacement in python:

Assuming this pre-existing list:

dogs = [f'dog{i 1}' for i in range(100)]
# ['dog1', 'dog2', 'dog3', ..., 'dog100']

You could use random.sample

import random
random.sample(dogs, k=3)

possible output: ['dog56', 'dog13', 'dog59']

  • Related