The Mod Out System

June 23, 2009

Over at The Daily WTF, Alex Papadimoulis catalogs some insanely bad programming practices. The Mod Out System is one of the best … worst … absolutely sickening … no boss, I would never do such a thing … well, you get the point.

The hero of the story, Gary, must write a function to expand a list of ranges like 1-6,9,13-19 into a list without ranges like 1,2,3,4,5,6,9,13,14,15,16,17,18,19.

Your task is to write that function. When you are finished, you are welcome to read or run a suggested solution, or to post your solution or discuss the exercise in the comments below.

Pages: 1 2

7 Responses to “The Mod Out System”

  1. […] Praxis – The Mod Out System By Remco Niemeijer Today’s Programming Praxis problem is an easy one: all we have to do is convert a string that contains […]

  2. Remco Niemeijer said

    My Haskell solution (see http://bonsaicode.wordpress.com/2009/06/23/programming-praxis-the-mod-out-system/ for a version with comments):

    import Data.List.Split
    
    modOut :: String -> [Int]
    modOut = concatMap ((\(a:b:_) -> [a..b]) .
        cycle . map read . sepBy "-") . sepBy ","
    
    main :: IO ()
    main = print $ modOut "1-6,9,13-19"
    
  3. liesen said

    In Scala:

    object ModOutSystem {
    def modOut(s: String) =
    s split “,” flatMap { _ split “-” match {
    case Array(single) => List(single.toInt)
    case Array(from, to) => List.range(from.toInt, to.toInt + 1)
    } }

    def main(args: Array[String]) = println(modOut(“1-6,9,13-19”).deepToString) // Array(1, 2, 3, 4, 5, 6, 9, 13, 14, 15, 16, 17, 18, 19)
    }

  4. Mary said

    Pretty nice post. I just came by your blog and wanted to say
    that I have really enjoyed reading your posts. Any way
    I’ll be subscribing to your feed and I hope you post again soon!

  5. Barry said

    In Python2.x:

    def combineranges(a):
    b = [[int(j) for j in i.split(“-“)] for i in a.split(“,”)]
    c = []
    [c.extend(range(b[i][0],b[i][len(b[i])-1]+1)) for i in range(len(b))]
    return c

    print combineranges(“1-6,9,13-19”)

  6. Connochaetes said

    In Ruby:

    def expand(s)
    s.inject {|x,y| x..y}.to_a
    end

    def mod_out(mod_string)
    mod_string.split(“,”).collect {|x| x.split(“-“)}.collect {|x| expand(x)}.join(“,”)
    end

    puts mod_out “1-6,9,13-19”

  7. A quick hack in Common Lisp.

    (defun mod-out (ranges)
    (flatten
    (loop for range in ranges
    collect (if (consp range)
    (loop for i from (car range) to (cdr range) collect i)
    range))))

    ;; usage
    (mod-out ‘((1 . 6) 9 (13 . 19)))

    Take FLATTEN from your favorite utility library or write it yourself.

Leave a comment