Posts

Showing posts from April, 2015

Binary Search implementation in Ruby

def binary_search(array, value, from=0, to=nil)    to = array.count - 1 unless to     mid = (from + to) / 2    if value < array[mid]      return binary_search(array, value, from, mid - 1)    elsif value > array[mid]      return binary_search(array, value, mid + 1, to)    else      return mid    endend
puts binary_search([1,2,3,4,5,7,8,9,10,12,15,16,17,18], 15)

Program to perform divison operation of two numbers without using /, %, and modules operator

def devide(divisor, dividend)
  quotient = 0
  until(dividend < divisor) do
    dividend -= divisor
    quotient += 1
  end
  quotient
end
puts devide(15, 100)

Ruby Count, Length & Size

These methods can be applied on Arrays, Hashes or Objects.  Here I'm just trying to illustrate the difference between count, length and size. Array#length Basically length method returns number of elements in the array.
Example, suppose we have array arr as, arr = [1,2,3,4,5] Calling Array#length method on array will give result as, arr.length => 5 Array#size Array#size is just an alias to the Array#length method. This method executes same as that of Array#length method internally.
Example, arr.size => 5 Array#count It has more functionalities than length or size. This method can be used for getting number of elements based on some condition. Unlike length/size, we can pass block or an argument to count. This can be called in three ways: Array#count => without condition, Returns number of elements in Array Array#count(n) => passing value, Returns number of elements having value n in Array Array#count{|i| i.zero?} => passing block, Returns count based on cond…