Created
December 29, 2012 00:06
-
-
Save styliii/4403329 to your computer and use it in GitHub Desktop.
Interview Question
This file contains 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
# Given an array of objects with people's name and age | |
# sort this array based on a person's age | |
# for a given age, do not change the order of the original array | |
people = [ | |
{:name => "Jake", :age => 33}, | |
{:name => "Larry", :age => 31}, | |
{:name => "Chhay", :age => 33}, | |
{:name => "Li", :age => 29}, | |
{:name => "Li2", :age => 32}, | |
{:name => "Li3", :age => 32}] | |
age = [] | |
sorted_people = people.inject({}) do |hash, person| | |
if hash.has_key?(person[:age]) | |
hash[person[:age]] << person | |
else | |
hash[person[:age]] = [person] | |
end | |
age << person[:age] | |
hash | |
end | |
min = age.min | |
max = age.max | |
sorted_array = [] | |
(0...max-min+1).map do |i| | |
if sorted_people.has_key?(i + min) | |
sorted_array << sorted_people[i + min] | |
end | |
end | |
puts sorted_array.flatten |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment