Created
February 25, 2013 03:53
-
-
Save thomasbiddle/5027464 to your computer and use it in GitHub Desktop.
CodingForInterviews.com Feb 20, 2013 Article
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Binary Search | |
def search array, num, first, last | |
middle = (first+last)/2 | |
if (first or last) == middle | |
return -1 | |
end | |
if num == array[middle] | |
return middle | |
elsif num > array[middle] | |
search(array, num, middle, last) | |
elsif num < array[middle] | |
search(array, num, first, middle) | |
end | |
end | |
array = [-10, -2, 1, 5, 5, 8, 20] | |
result = search(array, 5, 0, array.length) | |
puts result | |
# Singleton Implementation. | |
class MySingleton | |
attr_accessor :lock_enabled | |
def initialize | |
@lock_enabled = false | |
end | |
# Class Variable | |
@@singleton = MySingleton.new | |
def self.instance | |
return @@singleton | |
end | |
# Ensure we the user can't call new themselves. | |
private_class_method :new | |
end | |
# Very basic example of how we could use a Singleton | |
# class. | |
class MySuperAwesomeProject | |
def writeStuff | |
unless MySingleton.instance.lock_enabled | |
MySingleton.instance.lock_enabled = true | |
return true # We can write stuff! | |
else | |
return false # We can't write stuff :-( | |
end | |
end | |
def doneWritingStuff | |
MySingleton.instance.lock_enabled = false | |
end | |
end | |
ap = MySuperAwesomeProject.new | |
puts ap.writeStuff # True | |
puts ap.writeStuff # False | |
ap.doneWritingStuff | |
puts ap.writeStuff # True | |
# TJ Biddle | |
# biddle.thomas at gmail dot com | |
# SF, CA |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment