How would you display an array of integers as a set of ranges? (algorithm)

后端 未结 16 2892
我在风中等你
我在风中等你 2021-02-15 18:04

Given an array of integers, what is the simplest way to iterate over it and figure out all the ranges it covers? for example, for an array such as:

$numbers = ar         


        
16条回答
  •  走了就别回头了
    2021-02-15 18:07

    module Main where
    
    ranges :: [Int] -> [[Int]]
    ranges [] = []
    ranges list@(x:xs) = let adj = adjacent list in
                 let len = length adj in
                     if length adj == 1
                    then [[x]] ++ ranges xs
                    else [[x,(last adj)]] ++ ranges (drop ((length adj) - 1) xs)
        where adjacent [] = []
              adjacent (x:xs) = if (xs /= []) && (x + 1) == head xs
                 then [x] ++ adjacent (xs)
                 else [x]
    
    main = do putStrLn $ show $ ranges [1,2,3,4,5,6,8,11,12,14,15,16]
    
    -- Output: [[1,6],[8],[11,12],[14,16]]
    

    Here's my best shot in Haskell.

提交回复
热议问题