How to create a common sorted unique array from 3 integer arrays in Ruby

1 Answer

0 votes
#
# Function: merge_arrays
# Purpose:  Combine three integer arrays into a single list.
#
def merge_arrays(arr_a, arr_b, arr_c)
  lst_merged = []
  
  lst_merged.concat(arr_a)
  lst_merged.concat(arr_b)
  lst_merged.concat(arr_c)
  
  lst_merged
end

#
# Function: unique_sorted
# Purpose:  Convert a list into a sorted list with unique elements.
#           Uses uniq to remove duplicates, then sorts the result.
#
def unique_sorted(lst)
  arr_unique = lst.uniq.sort
  
  arr_unique
end

# Input arrays
arr1 = [5, 1, 14, 3, 8, 9, 1, 1, 7]
arr2 = [3, 5, 7, 2, 3]
arr3 = [2, 9, 8]

# Step 1: Merge all arrays
lst_merged = merge_arrays(arr1, arr2, arr3)

# Step 2: Create sorted unique array
lst_result = unique_sorted(lst_merged)

# Step 3: Print result
print "Sorted unique array: "
lst_result.each { |x| print "#{x} " }


=begin
run:

Sorted unique array: 1 2 3 5 7 8 9 14 

=end

 



answered 6 days ago by avibootz

Related questions

...