Skip to content

Instantly share code, notes, and snippets.

View sevenmaxis's full-sized avatar

Serhii Hopkalo sevenmaxis

  • Intetics
  • Ukraine, Kiev
View GitHub Profile
@sevenmaxis
sevenmaxis / storage.rb
Created February 7, 2012 20:34
Storage
customer = { <id> => { :sex => <sex>, :height => <height>, :age => <age>, :sum => <sum>, :index => <index> } }
class Storage
def initialize
h = Hash.new{|hash,key| hash[key]=[]}
@storage = { :sex => h.dup, :height => h.dup, :age => h.dup, :sum => h.dup, :index => h.dup }
end
def add_customer( expr)
# it should return id of customer
end
def find( search_expr)
@sevenmaxis
sevenmaxis / heapsort.rb
Created February 13, 2012 13:00
heapsort
class Array
def get_max(index,start)
index = 2*index + 1 - start
self[index] > self[index+1] ? index : index+1
end
def heapsort
0.upto(length-3) do |start|
@sevenmaxis
sevenmaxis / benchmark.rb
Created February 18, 2012 07:26
benchmark
def bench(repetitions=100, &block)
require 'benchmark'
Benchmark.bmbm do |b|
b.report{ repetitions.times &block }
end
nil
end
@sevenmaxis
sevenmaxis / trie.rb
Created February 20, 2012 10:23
Trie
class Trie
def initilize
@trie = Hash.new
end
def build(str)
node = @trie
str.each_char do |ch|
prev_node = node
node = prev_node[ch] = Hash.new unless node[ch]
end
@sevenmaxis
sevenmaxis / webrick_server.rb
Created February 23, 2012 01:34
Webrick server in one line
ruby -rwebrick -e 'WEBrick::HTTPServer.new(:Port=>8000,:DocumentRoot=>".").start'
@sevenmaxis
sevenmaxis / functional_style.rb
Created March 4, 2012 08:35
functional style
a = [{:amount => "500.0", :when => "2012-03-13"},
{:amount => "500.0", :when => "2012-03-24"},
{:amount => "100.0", :when => "2012-04-14"},
{:amount => "100.0", :when => "2012-04-16"}]
compressed = a.group_by{|hash| hash[:when][0,7]}
.map{|k,v| {:when=>k,:amount=>v.reduce{|sum,hash| sum+hash[:amount].to_i}}}
[ {:when => "2012-03", :amount => 1000},
{:when => "2012-04", :amount => 200}]
#user.rb
class User < SmartDB
rename_table_to :Customer
attr_accessor :address, :rename_to => :location
end
#After running rake smart task, the table, class, file and attribute will be modified to this
#customer.rb
class Customer < SmartDB
class Array
def partition3
Array.new(3){|_| []}.tap{|a| each{|x| a[yield(x)] << x }}
end
def qsort
return self.dup if size < 2
central, left, right = partition3{|x| first <=> x}
left.qsort + central + right.qsort
end
end
a = [
{"player_id":1 , "matches":2, "goals": 5},
{"player_id":2 , "matches":4, "goals": 10}
]
a.reduce([0,0]){|sum,h|[sum.first+h["goals"],sum.last+h["matches"]]}.reduce{|sum,m|sum.to_f/m}
@sevenmaxis
sevenmaxis / absent_numbers.rb
Created March 13, 2012 20:58
Looking for two absent numbers in array of numbers
def absent_numbers(array)
[array.each, array.reverse_each].each_with_object([]) do |result, iterator|
iterator.reduce do |prev_, next_|
if (prev_ - next_).abs > 1
result << (prev_ > next_ ? prev_ - 1 : next_ - 1)
break
end
next_ # it's very important
end
end