Tuesday, August 23, 2011

Puzzle is that there is a bar which can contain n marbles. But one of the marble is heavier than others. Write a program to get heaviest marble.

Ruby 1.9:

def numeric?(object)
true if Float(object) rescue false
end

def enter_heavy_weight(j)
print "Enter weight of marble #{j}: "
@weights << enter_numeric(gets)
end

def enter_numeric(value)
if numeric?(value)
value.to_f
else
print "Please enter integer value: "
enter_numeric(gets)
end
end

def heavy_weight
print "Please Enter Total Number of Marbles: "
n = enter_numeric(gets)
@weights = []
for i in 1..n
enter_heavy_weight(i)
end

heaviest_marble_position = @weights.each_with_index.max[1]

puts "Heaviest Marble is at position: #{heaviest_marble_position + 1} Having Weight: #{@weights[heaviest_marble_position]}"

end

heavy_weight

No comments:

Post a Comment