Generating all possible combinations of numbers in a triple?

Say, for example, I want to build a triplet using each combination of numbers from 1..100 in a triplet; i.e:

[(0,0,0),(0,0,1),(0,1,1),(1,1,1),(0,0,2),(0,1,2),(0,2,2),(1,2,2)] 

.. etc. etc. right up to the given border (i.e. 100: gives us the final triplet (100 100 100)); is there any reasonable way to do this inside haskell, or is it best for me to write a method that briefly holds the border pointer and recursively increments each number until it is equal to the number on the right?

+2
source share
2 answers

I think your description is best for comprehending the list in order to express what you want to do:

 [(a, b, c) | c <- [0..100], b <- [0..c], a <- [0..b] ] 
+5
source

You say you want the numbers 1..100, but mention 0 in the examples. Also, you say β€œevery combination,” but don't mention (1,0,0) .

 [(a,b,c) | m<-[0..100], a<-[0..m], b<-[0..m], c<-[0..m] ] 

to avoid duplication, list them in order of their total amount:

 let l = 100; in [(a,b,c) | m<-[0..3*l], a<-[0..l], b<-[0..l], c<-[0..l], a+b+c == m ] 

The calculation can be accelerated (keeping the same result), narrowing the possible ranges:

 let l = 100; in [(a,b,mab) | m<-[0..3*l], a<-[(max 0 (m-2*l))..(min lm)], b<-[(max 0 (mal))..(min l (ma))] ] 
+1
source

All Articles