Next coding challenge..

59 views
Skip to first unread message

Ben Hutchison

unread,
Feb 28, 2012, 9:57:42 PM2/28/12
to scala...@googlegroups.com
This one is based on something Eric Torreborre tweeted a few years
back. It will sharpen your Scala Sollections Fu:

You have a finite Seq[Int], unordered and may contain duplicates.
Write a function, Seq[Int] => Seq[(Int, Int)], that converts into an
interval representation, where each contiguous series of integers is
represented by an interval tuple (start, end), and the tuples are
ordered in ascending order.

For example:

In: Seq(4, 1, 4, 2, 5, 8, 2, 6)

Out: Seq((1, 2), (4, 6), (8, 8))

This can be done in a few of lines of Scala, so perhaps wait on
posting solutions until friday?

-Ben

etorreborre

unread,
Feb 28, 2012, 10:18:34 PM2/28/12
to scala...@googlegroups.com
That's funny because I indeed remember the problem which was "compressing" a long list of ids into just a few ranges but I don't remember how I did it :-).

Eric.

Ken Scambler

unread,
Feb 28, 2012, 10:21:58 PM2/28/12
to scala...@googlegroups.com

The collections classes have sprouted a lot of nifty functionality since then too, so the solution might be even more concise now!

--
You received this message because you are subscribed to the Google Groups "Melbourne Scala User Group" group.
To view this discussion on the web, visit https://groups.google.com/d/msg/scala-melb/-/uZp5sPtWu4cJ.
To post to this group, send an email to scala...@googlegroups.com.
To unsubscribe from this group, send email to scala-melb+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/scala-melb?hl=en-GB.

Jem Mawson

unread,
Feb 29, 2012, 6:06:57 PM2/29/12
to scala...@googlegroups.com
Let me rephrase the challenge:

def ranges(ints: Seq[Int]): Seq[(Int, Int)]

assert(ranges(Seq()) == Seq()) // empty
assert(ranges(Seq(1)) == Seq((1,1))) // single value
assert(ranges(Seq(1,2,3)) == Seq((1,3))) // single range
assert(ranges(Seq(1,2,3,9)) == Seq((1,3),(9,9))) // 1 range, 1 value
assert(ranges(Seq(1,2,3,7,8,9)) == Seq((1,3),(7,9))) // two ranges
assert(ranges(Seq(5,7,3)) == Seq((3,3),(5,5),(7,7))) // distinct values unordered
assert(ranges(Seq(6,4,5)) == Seq((4,6))) // range unordered

I look forward to seeing some interesting answers. Especially a succinct one from Ben.

Cheers
Jem
Reply all
Reply to author
Forward
0 new messages