Skip to content

Commit 02b1e52

Browse files
Added organise-duplicate-numbers-in-a-list.rb
1 parent 339f465 commit 02b1e52

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
=begin
2+
Codewars. 29/04/20. 'Organise duplicate numbers in a list'. 6kyu. Here we create
3+
a method that takes an array of integers and returns an array of arrays where each
4+
sub-array contains all duplicates of a particular number. The sub-arrays should be
5+
in the same order as the first occurrence of the numbers they contain. Here is the
6+
solution I developed to solve the challenge.
7+
1) We define our method duplicate_organiser_ms, which takes an array of integers
8+
as an argument.
9+
2) We call the group_by method, which groups the collection by the results of
10+
the block and returns a hash. By passing in the itself method as group_by's
11+
argument, we return a hash where the keys are the number from the array and
12+
the values are every incarnation of that number in the array i.e. the
13+
duplicates. The hash keys are in order of first appearance of that key's
14+
number in the array.
15+
3) Now that our duplicates are grouped together in the values of the hash, we
16+
use the hash method values to return an array populated with the values of
17+
the hash. This gives us an array of arrays where the duplicates are
18+
grouped together and everything is in order of first appearance of the
19+
number in the original array.
20+
=end
21+
22+
def duplicate_organiser_ms(arr)
23+
arr.group_by(&:itself).values
24+
end

0 commit comments

Comments
 (0)