Skip to content

Instantly share code, notes, and snippets.

@cmar
Created July 8, 2013 21:11
Show Gist options
  • Save cmar/5952531 to your computer and use it in GitHub Desktop.
Save cmar/5952531 to your computer and use it in GitHub Desktop.
Ruby LoCo Hack Night Challenge #1
#!/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
@rhockman
Copy link

rhockman commented Jul 8, 2013

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)

@cmar
Copy link
Author

cmar commented Jul 8, 2013

a = (1..1000).to_a
b = a.reverse

@karledurante
Copy link

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

@JohnMorales
Copy link

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