Jump to content

Combinations: Difference between revisions

m
→‎{{header|Haskell}}: Added type signature, improved aesthetics
(Added Haskell example)
m (→‎{{header|Haskell}}: Added type signature, improved aesthetics)
Line 25:
Straightforward, unoptimized implementation with divide-and-conquer:
 
<pre>
comb 0 _ = [[]]
comb _:: Int -> [a] =-> [[a]]
comb m0 (x:xs)_ = comb m xs ++ map (x:) (comb (m-1)= xs)[[]]
comb 0 _ [] = [[]]
comb m (x:xs) = comb m xs ++ map (x:) (comb (m-1) xs)
</pre>
 
In the induction step, either ''x'' is not in the result and the recursion proceeds with the rest of the list ''xs'', or it is in the result and then we only need ''m-1'' elements.
Line 33 ⟶ 36:
To generate combinations of integers between 0 and ''n-1'', use
 
comb1comb0 m n = comb m [0..n-1]
 
Similar, for integers between 1 and ''n'', use
 
comb2comb1 m n = comb m [1..n]
 
=={{header|J}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.