Two sum: Difference between revisions

Content added Content deleted
(→‎Haskell – Returning all matches: (Perhaps a little cleaner in terms of >>= ?))
(→‎Haskell Returning all matches: Dropped imports, simplified in terms of >>=, adjusted type signature)
Line 314: Line 314:


====Returning all matches====
====Returning all matches====
Using sequence (for a cartesian product) and nubBy, and listing multiple solutions when they exist:
Listing multiple solutions when they exist:


<lang haskell>import Data.List (elem, elemIndices, nubBy)
<lang haskell>sumTo :: Int -> [Int] -> [(Int, Int)]
sumTo n ns =

let ixs = zip [0 ..] ns
summingPairIndices :: Int -> [Int] -> [[Int]]
in ixs >>=
summingPairIndices n xs =
(>>= (`elemIndices` xs)) <$>
(\(i, x) ->
ixs >>=
nubBy
(\xy zs -> and ((`elem` zs) <$> xy))
\(j, y) ->
(sequence [xs, xs] >>=
[ (i, j)
(\[x, y] ->
| (i < j) && (x + y) == n ])
[ [x, y]
| x /= y && x + y == n ]))


main :: IO ()
main :: IO ()
main = print $ summingPairIndices 21 [0, 2, 11, 19, 90, 10]</lang>
main = print $ sumTo 21 [0, 2, 11, 19, 90, 10]</lang>
{{Out}}
{{Out}}
<pre>[[1,3],[2,5]]</pre>
<pre>[(1,3),(2,5)]</pre>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==