How to create a sorted unique list from a matrix in Ruby

1 Answer

0 votes
#
#   Create a sorted unique array (arr) from a matrix (arr of arr).
#   Steps:
#     1. Flatten matrix into arr
#     2. Sort arr
#     3. Remove duplicates (uniq)
#

def make_sorted_unique_arr(mat)
  # Flatten matrix into arr
  arr = mat.flatten

  # Sort arr and remove duplicates
  arr = arr.sort.uniq

  arr
end

mat = [
  [5, 1, 17, 3, 8, 2, 1, 9],
  [3, 5, 7, 4, 2, 3, 4, 1],
  [9, 1, 8, 2, 3, 88, 17, 5]
]

arr = make_sorted_unique_arr(mat)

arr.each { |x| print "#{x} " }



=begin
run:

1 2 3 4 5 7 8 9 17 88

=end

 



answered 6 days ago by avibootz
...