If there are no common elements between the two input arrays, return an empty array. Use clear variable names and comments to explain your code logic.
Here’s a possible implementation:
# Define function that takes in two arrays as arguments
def find_unique(array1, array2)
# Create a new set (unordered collection with no duplicates) from the first array using Set class to remove duplicates and make it faster for checking if an element is already there or not.
unique_set = Set.new(array1)
# Create an empty array to store unique elements from both arrays
unique_elements = []
# Iterate over each element of the second array (`array2`) and check if it isn't present in both arrays by comparing its presence in 'unique_set' created earlier using `include?` method and also excluding it from the first array using `exclude?` method.
array2.each do |element|
# Check if element is not present in both arrays and add it to the output array only if it isn't already there (i.e., has a frequency of occurrence of zero).
# Use `unless` to skip the current iteration if the condition is not met
next unless !unique_set.include?(element) && array1.exclude?(element)
# Add the unique element to the output array
unique_elements << element
end
# Sort the 'unique_elements' array alphabetically using `sort` method with block that sorts elements based on their ASCII values (i.e., lexicographically) and return it if it has any elements; otherwise return an empty array []
sorted_unique = unique_elements.sort { |a, b| a <=> b }
# Return the sorted output array 'sorted_unique' if it has any elements; otherwise return an empty array []
# Use ternary operator to check if the array is empty and return the appropriate value
return sorted_unique.empty? ? [] : sorted_unique
end
Explanation:
– The function `find_unique(array1, array2)` takes in two arrays as arguments (`array1` and `array2`) and returns a new array containing all elements that are not present in either of the input arrays.
First, we create a new set called ‘unique_set’ from the first array using Set class to remove duplicates and make it faster for checking if an element is already there or not.
Next, we iterate over each element of the second array (`array2`) and check if it isn’t present in both arrays by comparing its presence in ‘unique_set’ created earlier using `include?` method and also excluding it from the first array using `exclude?` method.
If an element is found that isn’t in either array, we add it to a new array called ‘unique_elements’. However, we only do this if its frequency of occurrence (i.e., how many times it appears in `array1`) is 0. This ensures that if an element appears multiple times in both input arrays, it will not be included as unique.
Finally, we sort the output array alphabetically using `sort` method with a block that sorts elements based on their ASCII values (i.e., lexicographically) and return it if it has any elements; otherwise return an empty array [].