facebook careers puzzle – Hoppity Hop! – in Ruby

https://www.facebook.com/careers/puzzles.php?puzzle_id=7

A pretty simple puzzle just to get things started. Hoppity Hop!

def hoppity_hop
	#fetch the file name from the command prompt input
	file_name = ARGV[0]
	#read the contents from the file and convert to integer
	file_content = File.read(file_name).to_i
 
	#run loop from 1 to the number in file
	1.upto(file_content) do |i|
		if i % 3 == 0 && i % 5 == 0
			puts "Hop\n"
		else
			puts "Hoppity\n" if i % 3 == 0
			puts "Hophop\n" if i % 5 == 0
		end
 
	end
end
 
hoppity_hop

Binary Search – Ruby Programming Language

Binary Search, takes in sorted array and search the key element and returns the index of the key element.

def binarySearch(sortedArray, first, last, key) 
   until first > last do
       mid = (first + last)/2
       if (key > sortedArray[mid])
           first = mid + 1;
           binarySearch(sortedArray, first, last, key)
       elsif (key < sortedArray[mid])
           last = mid - 1;
           binarySearch(sortedArray, first, last, key)
       else
           return mid;
      end
   end
   return -1;
end
 
sorted_array = [1, 5, 6, 18, 19, 25, 46, 78, 102, 114]
p binarySearch(sorted_array, 0, sorted_array.length-1, 6)

Another attempt, optimized binary search without while or any loop. There is no loop. Let me know your view point on this

def binarySearch(sortedArray, first, last, key) 
   if first < last
       mid = (first + last)/2
       if (key == sortedArray[mid])
          return mid
       else
         if(key > sortedArray[mid])
           first = mid + 1
         else
           last = mid - 1
         end
       end
       return binarySearch(sortedArray, first, last, key)
   end
   return -1;
end
 
sorted_array = [1, 5, 6, 18, 19, 25, 46, 78, 102, 114]
p binarySearch(sorted_array, 0, sorted_array.length-1, 50)

Astrix (*) Patterns in Ruby

This simple program shows the astrix in diamond structure. It takes input from the user and displays a diamond structure astrix. This program is made using Ruby Language. I used Ruby 1.8.7 but it should work on all Ruby versions.

def patterns n
	1.upto(n) do |i|
		space = ''
		astrix = ''
		i.upto(n-1) { space=space+' '; }
		1.upto(i) { astrix=astrix+'*'; }
		2.upto(i) { astrix=astrix+'*'; }
		puts space+astrix
	end
	i= n-1
	until i < 1 do
		space = ''
		astrix = ''
		i.upto(n-1) { space=space+' '; }
		1.upto(i) { astrix=astrix+'*'; }
		2.upto(i) { astrix=astrix+'*'; }
		puts space+astrix
		i=i-1
	end
end
 
puts "Enter Number of Iterations"
a = gets.chomp.to_i
 
patterns a

Output:

Ruby Program for Astrix Pattern