Skip to content

Instantly share code, notes, and snippets.

@evidanary
Created June 16, 2017 22:00
Show Gist options
  • Save evidanary/08a1361b4a5c5904619e4fa09ef16f79 to your computer and use it in GitHub Desktop.
Save evidanary/08a1361b4a5c5904619e4fa09ef16f79 to your computer and use it in GitHub Desktop.
############################
Rubyisms
############################
To get nth bit of a number you can do a = 5; a[0] == 1; 5.downto(0).map { |n| a[n] }.join #"000101"
To average 2 positive integers: (x&y)+((x^y)>>1)
Sum 2 positive integers: (x+y) == (x&y)+(x|y)
PriorityQueue API 'pqueue' : http://www.rubydoc.info/gems/pqueue/PQueue
Multithreaded example
require 'thread'
work_q = Queue.new
(0..50).to_a.each{|x| work_q.push x }
workers = (0...4).map do
Thread.new do
begin
while x = work_q.pop(true)
50.times{print [128000+x].pack "U*"}
end
rescue ThreadError
end
end
end; "ok"
workers.map(&:join); "ok"
Get ascii value of a character
'a'.ord #97
Opposite : 97.chr
All FixNums are default 8bytes ie. 64 bit ints e.g. 0.size # 8
For permutations you can do [1,2,3].permutations(2) # returns 6 possibilities
or if k>n for n permute k you can do [1,2,3].repeated_permutations(5) # returns 243
eval("+1-22") = -21
In ruby
a = [1,2]
b = [4,5,6]
ary = a.map.with_index{ |m,i| m + b[i].to_i }
=> [5, 7]
# IN ruby for set operations you have to "require 'set'"
# For md5 you have to "require 'digest/md5'; Digest::MD5.hexdigest(my_string)
# to initialize an M X N array - THIS IS BAD idea as arrays are going to point to the same instance,
# fill works only with literals -DONT DO IT
1. [].fill([].fill(0, 0...N),0...M)
2. Preferred Method: (0...M).each {|m| arr[m] ||= []; (0...N).each {|n| arr[m][n] = 0 }}
# http://stackoverflow.com/questions/7310015/ruby-array-internals
Stack: push/pop i.e. stack operations are O(1) in ruby
Queue: enq(push) is O(1) and deq(shift) is O(1)
Iterate over an array with set increments
(10..100).step(10) do |n|
# n = 10
# n = 20
# n = 30
# ...
end
String to bits
"a".to_i(2) # binary
"a".to_i(16) # hex
To get all possible combinations of [1.0] in array of n elements i.e. on and off each one
[0,1].repeated_permutation(10).to_a
# when you want to get index of elements that satisfy certain condition
arr.size.times.select {|i| arr[i] == 'x'} # => [0, 2, 6]
To get index of min/max element
ary = [2,3,4,5,1] # => [2,3,4,5,1]
ary.each_with_index.min # => [1, 4]
# To store objects as keys in hash you need to override the eql? method like this, then
you can do fancy things such as keys within range lookups which will return the object
that has key in the range - see http://javieracero.com/blog/the-key-to-ruby-hashes-is-eql-hash
def eql?(key)
obj_range.include? (key)
end
# For adding binary numbers
base = sum(a,b) % 2 + base
carry = sum(a,b)/ 2;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment