joelibaceta
5/22/2016 - 4:48 PM

find_the_one_repetition.rb

ar = Array.new

(0..1000000).map{|i| ar[i] = i} # Fill the Array
ar[rand(1000000)]=ar[rand(1000000)] # Randomise the repetition
beginning_time = Time.now 

repeated = ar.each_with_index.map{|v, i| ar[(ar[i]).abs] < 0 ? ((puts "#{ar[i].abs}"); break;) : ((ar[(ar[i]).abs]= - ar[(ar[i]).abs]))}

end_time = Time.now 
puts "Time elapsed #{(end_time - beginning_time)*1000} milliseconds"

# result 
# 709622
# Time elapsed 287.64 milliseconds
ar = "DDDDDDDAAAEEEEEEEFDAS" 
beginning_time = Time.now

(0..(ar.length)).map{|i| ar[i] != ar[i+1] && ar[i+1] != ar[i+2] ? ((puts "#{ar[i+1]}"); break;) : nil }

end_time = Time.now
puts "Time elapsed #{(end_time - beginning_time)*1000} milliseconds"

# Result
# F
# Time elapsed 0.045000000000000005 milliseconds
ar = Array.new(10000000) { rand(10000000) }
beginning_time = Time.now  

repeated = ar.each_with_index.map{|v, i| ar[(ar[i]).abs] < 0 ? ar[i].abs : ((ar[(ar[i]).abs]= - ar[(ar[i]).abs]); nil;)}

end_time = Time.now
p repeated.uniq.concat # Print friendly
puts "Time elapsed #{(end_time - beginning_time)*1000} milliseconds"

# Result
# [8061337, 6926934, .... 9459101, 3987560, 9004865, 9201491, 1213422, 4694285, 3870924, 9807815, 8664477, 2854240, 5056727, 5299871, 1145937, 8289400, 3276793, 3269626, 8887885, 3320762, 7923913, 8285601, 606133, 7266128, 1480427, 8126772, 2610130, 4911355, 5665657, 2899664, 2025334, 8244512, 1344242, 6323858, 1951516, 9526197, 9313120, 5132774, 7392751, 7246381, 821350, 8012118, 1498968, 3162623, 4739614, 3561167, 3917621, 40800, 4154732, 862593, 76260, 2100733, 4268195, 6297805, 2408327, 5168329, 9158507, 7566083, 3481042, 8851769, 4123660, 821279, 9085225, 9636661, 5920015, 4433949, 663218, 1398396, 4686523, 7323807, 145119, 4747472, 3763457, 5104604, 187511, 562911, 8154887, 1085324, 2802839, 6440119, 8319577, 1525305, 6872615, 9873673, 8752416, 7422250, 6381197, 4953022, 1621923, 973323, 7411765, 8298107, 7072547, 212576, 896737, 4303402, 2221870, 4370181, 4139865, 2306812, 6418684, 9501378, 4168265, 2923669, 5225241, 8216290, 9883624, 6355463, 2305308, 114087, 7084842, 1242130, 2110518, 1735796, 6980641, 4625905, 3180747, 2737905, 5911995, 9986110, 7488533, 3664714, 7010324, 1373053, 2326578, 5055546, 38754, 3067134]
# Time elapsed 4831.093 milliseconds