How can we efficiently get sorted sums of a sorted list?
matrixOfSums list = [[a+b | b <- list, b >= a] | a <- list]
sortedSums = foldl merge [] matrixOfSums
--A normal merge, save that we remove duplicates
merge xs [] = xs
merge [] ys = ys
merge (x:xs) (y:ys) = case compare x y of
LT -> x:(merge xs (y:ys))
EQ -> x:(merge xs (dropWhile (==x) ys))
GT -> y:(merge (x:xs) ys)
-- wide-merge does a standard merge (ala merge-sort) across an arbitrary number of lists
-- wideNubMerge does this while eliminating duplicates
wideNubMerge :: Ord a => [[a]] -> [a]
wideNubMerge ls = wideNubMerge1 $ filter (/= []) ls
wideNubMerge1 [] = []
wideNubMerge1 ls = mini:(wideNubMerge rest)
where mini = minimum $ map head ls
rest = map (dropWhile (== mini)) ls
betterSortedSums = wideNubMerge matrixOfSums
Tags: language-agnostic algorithm
Source: By Peter Burns as answer to the question
This code snippet was collected from stackoverflow, and is licensed under CC BY-SA 2.5
Related code-snippets:
- How can I get the value of in a loop?
- Function for creating color wheels.
- Why use unsigned values over signed ones?
- Generate list of all possible permutations of a string.
- How can I use combinations of sets as test data?
- What is the most efficient code for 10000 prime numbers?
- Format string to title case. Title case is a common text format in English.
- How can I make my projects international in india?
- A little diversion into floating point (im)precision, part 1 | 1 – 0 | 1 | 1 | 1 | 1 | 1 | 1 | 2 | 1 | 1 | 2 | 1 | 2 | 1 | 1 | 2 | 1 | 2 | 3 | 4 | A little diversion into floating point (im)precision, part 1 | 3 | 4 | 5 | 5 | 8 | 8 | 2 | 3 | 4 | 7 | 8 | 7 | 7 | 7 | 6 | 1 | 1 | 5 | 1
- I am using the directx x or opengl to create 100 floating cubes. Is this possible?
- "Sorting" colors by distinctiveness. Followup:
- How can I modify a.xfdl file?
- Pass by reference or pass by value?
- How can I start using Version Control and Visual Studio?
- How can I teach someone new to program?