Created
March 10, 2014 04:28
-
-
Save gregkrsak/9459495 to your computer and use it in GitHub Desktop.
Finding duplicate elements in an array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# Problem: Find the duplicate values in a 1..n array | |
# CREATE THE PROBLEM | |
# Size of the data set | |
dataset_size = 100 | |
# The data set: This will become an array of numbers | |
numbers = [] | |
# Initialize the array of numbers | |
(1..dataset_size).each do |n| | |
numbers[n] = n | |
end | |
# Including some duplicate numbers | |
numbers[50] = 15 | |
numbers[52] = 12 | |
# SOLVE THE PROBLEM | |
# This array will hold a boolean flag for each number | |
discovered = [] | |
# Holds any results (numbers determined to be duplicates) | |
results = [] | |
# Create an array of false values, where each index can be set to | |
# true if its associated number has been found | |
discovered.fill(false, 1..dataset_size) | |
# Loop through all numbers in the ideal dataset | |
(1..dataset_size).each do |n| | |
# If this number has previously been discovered | |
if discovered[numbers[n]] | |
# then it is a duplicate | |
results << numbers[n] | |
end | |
# Either way, flag this number as discovered | |
discovered[numbers[n]] = true | |
end | |
# DISPLAY RESULTS | |
puts "Results:" | |
results.each do |n| | |
puts n | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment