Skip to content

Instantly share code, notes, and snippets.

@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
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 / haml_cheatsheet.haml
Created March 25, 2012 08:39
haml cheatsheet
!!! strict
!!! XML
%html
-# Self closing tags
%img{:src => "happy.jpg"}/
%div.myclass
.myclass1
@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
@them0nk
them0nk / rspec_rails_cheetsheet.rb
Created March 23, 2012 03:39
Rspec Rails cheatsheet (include capybara matchers)
#Model
@user.should have(1).error_on(:username) # Checks whether there is an error in username
@user.errors[:username].should include("can't be blank") # check for the error message
#Rendering
response.should render_template(:index)
#Redirecting
response.should redirect_to(movies_path)
@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"
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 / 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
@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]