Created
July 8, 2013 21:11
-
-
Save cmar/5952531 to your computer and use it in GitHub Desktop.
Ruby LoCo Hack Night Challenge #1
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
#!/usr/bin/env ruby | |
# | |
# Ruby LoCo Hack Night Challenge #1 | |
require 'benchmark' | |
a = [1, 2, 3, 4, 5] | |
b = [2, 5, 1, 3, 4] | |
# write a program to match indexes from a to b | |
time = Benchmark.measure do |x| | |
#do stuff here | |
# | |
expected = { 0 => 2, 1 => 0, 2 => 3, 3 => 4, 4 => 1 } | |
puts expected | |
end | |
puts '*' * 60 | |
puts time |
a = (1..1000).to_a
b = a.reverse
Declared to be the most "rubyish" way:
matches = {}
time = Benchmark.measure do |x|
matches.tap do |matches|
a.each_with_index do |el,i|
matches[i]=a.index(el)
end
end
end
puts matches
puts time
Got my solution to work:
# write a program to match indexes from a to b
time = Benchmark.measure do |x|
#do stuff here
a_bkt = {}
b_bkt = {}
expected = {}
a.each_with_index do |a_v, i|
a_hit = a_bkt[b[i]]; #index of the value b[i] in a.
b_hit = b_bkt[a_v]; #index of the value of a[i] in b.
expected[a_hit] = i if (a_hit);
expected[i] = b_bkt[a_v] if (b_hit);
a_bkt[a_v] = i;
b_bkt[b[i]] = i;
#puts "#{i}. a_bkt #{a_bkt}, b_bkt #{b_bkt}, a_v #{a_v}"
end
#expected = { 0 => 2, 1 => 0, 2 => 3, 3 => 4, 4 => 1 }
puts expected
end
took 0.003785 on my mac air
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
to generate random array of unique numbers
require 'set'
def rand_n(n, max)
randoms = Set.new
loop do
randoms << rand(max)
return randoms.to_a if randoms.size >= n
end
end
a=rand_n(1000,1000)
b=rand_n(1000,1000)