Skip to content

Instantly share code, notes, and snippets.

@mauricioszabo
Forked from isa/gist:2571012
Created May 2, 2012 22:05
Show Gist options
  • Save mauricioszabo/2580923 to your computer and use it in GitHub Desktop.
Save mauricioszabo/2580923 to your computer and use it in GitHub Desktop.
Convert in less than 30 lines
val list = List(
('A', 'B', 'C'),
('A', 'C', 'E'),
('E', 'F', 'D'),
('D', 'A', 'J'),
('E', 'D', 'J')
)
val expected = List(
('A', 'B', 1),
('A', 'C', 2),
('A', 'D', 1),
('A', 'E', 1),
('A', 'J', 1),
('B', 'C', 1),
('C', 'E', 1),
('D', 'E', 2),
('D', 'F', 1),
('D', 'J', 2),
('E', 'F', 1),
('E', 'J', 1)
)
val map = list.foldLeft(Map[List[Char], Int]()) { case(map, r) =>
List(r._1, r._2, r._3, r._1).sliding(2).foldLeft(map) { case(map,e) =>
map ++ Map(e.sorted -> (map.getOrElse(e.sorted, 0) + 1))
}
}
val after = map.map { case(l, e) => (l(0),l(1),e) }.toList.sortWith { case (e1, e2) =>
val (a1,a2,_) = e1
val (b1,b2,_) = e2
a1 < b1 || a1 == b1 && a2 < b2
}
assert(expected == after, "List is not what we spected to be: "+after)
@mauricioszabo
Copy link
Author

As scala is static typed, I used a n-tuple to define the list. The code, itself, is only 9 lines long.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment