Skip to content

Instantly share code, notes, and snippets.

@them0nk
them0nk / inversion.rb
Created March 15, 2012 01:49
Method to count the number of inversion in an array of numbers
def count_inversion arr
def count_and_merge arr1, arr2
arr = []
j = 0
i = 0
count = 0
while (i != arr1.size) && (j != arr2.size)
if arr1[i] < arr2[j]
@them0nk
them0nk / bitcount.rb
Created March 17, 2012 04:52
2's Compliment Solution (InterviewStreet CodeSprint Fall 2011)
class Numeric
def find_last_bit
r = 0
n = self
32.times do
n >>= 1
break if n==0
r = r+1
end
return r
def mergesort arr
def merge arr1, arr2
arr = []
j = 0
i = 0
while (i != arr1.size) && (j != arr2.size)
if arr1[i] < arr2[j]
arr << arr1[i]
@them0nk
them0nk / reverse_words.rb
Created March 18, 2012 16:41
Ruby snippets
def reverse_word str
str.split(" ").reverse.join(" ")
end
reverse_word "This is really awesome"
@them0nk
them0nk / rails_model.rb
Created March 23, 2012 06:45
Rails Model
#To get a column from a Model
Movie.all # Returns all row from the table Movies
Movie.select(:title).map { |m| m.title } # Returns array of title from the Model movie
Movie.select(:title).map(&:title) # Returns array of title from the Model movie
def closestpair points
px = points
def euclid_distance pt1, pt2
Math.sqrt ((pt1[0] - pt2[0])**2 + (pt1[1] - pt2[1])**2)
end
def closestsplitpair pts, minpt, dist
@them0nk
them0nk / quicksort.rb
Created April 2, 2012 02:48
Quicksort Algorithm (In Place) and returns the number of comparisons done.
def quicksort arr,startpos,endpos
def choose_pivot arr,startpos,endpos
#THis is for selecting median of three , you can return a random number as well.
if ((arr[startpos] < arr[endpos]) and (arr[startpos] > arr[startpos+ (endpos-startpos)/2])) or ((arr[startpos] > arr[endpos]) and (arr[startpos] < arr[startpos+ (endpos-startpos)/2]))
return startpos
elsif ((arr[endpos] < arr[startpos]) and (arr[endpos] > arr[startpos+ (endpos-startpos)/2])) or ((arr[endpos] > arr[startpos]) and (arr[endpos] < arr[startpos+ (endpos-startpos)/2]))
return endpos
@them0nk
them0nk / two_sum.rb
Created April 26, 2012 01:59
Given an array find the combination of two numbers in the array which makes the given sum
require 'set'
def twosum arr,sum_arr
a = Set.new(arr)
sum_arr.each do |sum|
count = 0
arr.each do |elem|
puts("#{sum} = #{elem} + #{sum-elem}") if a.include? (sum-elem)
end
@them0nk
them0nk / second_smallest.rb
Created April 26, 2012 01:50
second smallest number in an array
def second_smallest arr
min_arr = []
arr.each_slice(2) do |x,y|
if y.nil? or x < y
min_arr << x
else
min_arr << y
end
@them0nk
them0nk / heapds.rb
Created April 26, 2012 02:06
heap datastruture
class Heap
def initialize arr, type=:min
@heap = arr
self.class.class_eval { alias_method "get#{type.to_s}", :getroot }
if type == :min
@op = :<
else
@op = :>
end