4 ms·
Maybe it come from the fact that you are using a non-functional language for functional stuff? In Haskell I'd do it like this: pairs[] = [] pairs(x:xs)
by reirob 15y ago
Maybe it come from the fact that you are using a non-functional language for functional stuff? In Haskell I'd do it like this:
pairs[] = []
pairs(x:xs) =
map (\ y -> (x,y)) (xs) ++ pairs xs
Tried, out in console:
*Main> pairs "ABCD"
[('A','B'),('A','C'),('A','D'),('B','C'),('B','D'),('C','D')]
It seems to do what is supposed to.
- jamwt 15y agoHaskell even has sugar for this via list comprehensions: Prelude> let pairs = "ABCD" Prelude> [(x, y) | x <- pairs, y <- pairs, x < y] [('A','B'),('A','C'),('A','D'),('B','C'),('B','D'),('C','D')]
- dpatru 15y agoThis generates the Cartesian product and filters. (x,y) where both x and y are drawn from the original list. The previous solution only generates pairs (x, y) where y is drawn from elements after x.
- FalconNL 15y agoAnd yet another short, functional solution: pairs = (>>= \ ~(x:xs) -> map ((,) x) xs) . init . tails EDIT: Or as a list comprehension: pairs xs = concat [map ((,) h) t | (h:t) <- tails xs]