Cialis pills
Thursday, November 16th, 2006Cialis pills, A short time ago in a galaxy not so far, cialis pills, far away I came across a nice blog post: 15 Exercises for Learning a new Programming Language.
Cialis pills, One could argue if these are *really* the most appropriate 15(+) exercises to learn a new programming language - however, cialis pills, the task of answering this rather complex question is left as an exercise for the reader. Cialis pills, Instead of this I will show you their implementation in Ruby - rubyrailways.com style.
Cialis pills, Why did I bother to solve these problems (including not really trivial ones, cialis pills, like a scientific calculator with a GUI) ? Well, cialis pills, actually to learn a new programming language! I still consider myself a beginner Ruby apprentice just playing it by ear in my somewhat scarce free time, cialis pills, so I thought that systematically implementing a task list like this will mean great step forward for me compared to just coding random things at random times. Cialis pills, Fortunately I was perfectly right!
Cialis pills, Before we move onto the code, cialis pills, one last disclaimer: the fact that I am still a Ruby n00b implies that the code can be somewhat hairy/not optimal/[insert any other language than Ruby here]-ish so don’t use these snippets as a textbook solution of the problems or anything like that. Cialis pills, I would be glad if someone could suggest a bit of refactoring of the bad parts but I also hope that that there are some nice parts which you can learn from (actually I am quite sure about this since I used some magick formulas from a few Ruby (grand)masters in some cases).
Cialis pills, OK, cialis pills, enough talk for now. Cialis pills, Let’s see the stuff!
Cialis pills, 1. Cialis pills, Problem: “Display series of numbers (1, cialis pills,2, cialis pills,3, cialis pills,4, cialis pills, 5….etc) in an infinite loop. Cialis pills, The program should quit if someone hits a specific key (Say ESCAPE key).”
Cialis pills, Solution: Hmm, cialis pills, well, cialis pills, errr…uh-oh… Cialis pills, I could not solve this problem fully (what a terrific start :-)). Cialis pills, If Henry Ford would sit beside me now, cialis pills, he would say : You can hit any key to exit - so long as it’s ‘C’ - and one more advice: don’t forget to hold CTRL during this action :-). Cialis pills, More on this after the code snippet:
Cialis pills,
- i = 0
- loop { print "#{i+=1}, cialis pills, " }
Cialis pills, Comments : If anyone knows how to add code which will cause this program to stop with a specific keyhit (say ‘ESC’) please, cialis pills, please, cialis pills, please drop me a note. Cialis pills, I have been researching this for at least 10% of the time of solving all the tasks, cialis pills, nearly spitting blood when I gave up :-). Cialis pills, It seems (to me) that there is no simple (i.e. Cialis pills, no threads and similar) and clean platform-independent solution for this problem. Cialis pills, I guess (hope) the author’s idea here was different than to introduce threading or writing platform specific-code…
Cialis pills, 2. Cialis pills, Problem: “Fibonacci series, cialis pills, swapping two variables, cialis pills, finding maximum/minimum among a list of numbers.”
Cialis pills, Solution:
Cialis pills,
- #Fibonacci series
- Fib = Hash.new{ |h, cialis pills, n| n < 2 ? h[n] = n : h[n] = h[n - 1] + h[n - 2] }
- puts Fib[50]
- #Swapping two variables
- x, cialis pills,y = y, cialis pills,x
- #Finding maximum/minimum among a list of numbers
- puts [1, cialis pills,2, cialis pills,3, cialis pills,4, cialis pills,5, cialis pills,6].max
- puts [7, cialis pills,8, cialis pills,9, cialis pills,10, cialis pills,11].min
Cialis pills, Comments: The Fibonacci code was written by Andrew Johnson (found via Ruby Quiz). Cialis pills, I like it so much that I think it would be a shame to present a trivial version here. Cialis pills, I guess the rest of the code is self-explanatory.
Cialis pills, 3. Cialis pills, Problem: “Accepting series of numbers, cialis pills, strings from keyboard and sorting them ascending, cialis pills, descending order.”
Cialis pills, Solution:
Cialis pills,
- a = []
- loop { break if (c = gets.chomp) == ‘q’; a << c }
- p a.sort
- p a.sort { |a, cialis pills,b| b<=>a }
Cialis pills, Comments: This version is accepting strings - I think anybody who got to this point can adapt it to work with numbers. Cialis pills,
Cialis pills, 4. Cialis pills, Problem: “Reynolds number is calculated using formula (D*v*rho)/mu Where D = Diameter, cialis pills, V= velocity, cialis pills, rho = density mu = viscosity Write a program that will accept all values in appropriate units (Don’t worry about unit conversion) If number is < 2100, cialis pills, display Laminar flow, cialis pills, If it’s between 2100 and 4000 display 'Transient flow' and if more than '4000', cialis pills, display 'Turbulent Flow' (If, cialis pills, else, cialis pills, then...)"
Cialis pills, Solution:
Cialis pills,
- vars = %w{D V Rho Mu}
- vars.each do |var|
- print "#{var} = "
- val = gets
- eval("#{var}=#{val.chomp}")
- end
- reynolds = (D*V*Rho)/Mu.to_f
- if (reynolds < 2100)
- puts "Laminar Flow"
- elsif (reynolds > 4000)
- puts "Turbulent Flow"
- else
- puts "Transient Flow"
- end
Cialis pills, Comments: Can you spot the trick in the part which is filling up the variables? They don’t go out of scope after the loop ends because they are constants. Cialis pills, Other possibility would be to use $global variables but I guess it is usually not a very good programming practice to do that.
Cialis pills, 5. Cialis pills, Problem: “Modify the above program such that it will ask for ‘Do you want to calculate again (y/n), cialis pills, if you say ‘y’, cialis pills, it’ll again ask the parameters. Cialis pills, If ‘n’, cialis pills, it’ll exit. Cialis pills, (Do while loop) While running the program give value mu = 0. Cialis pills, See what happens. Cialis pills, Does it give ‘DIVIDE BY ZERO’ error? Does it give ‘Segmentation fault..core dump?’. Cialis pills, How to handle this situation. Cialis pills, Is there something built in the language itself? (Exception Handling)”
Cialis pills, Solution:
Cialis pills,
- vars = { "d" => nil, cialis pills, "v" => nil, cialis pills, "rho" => nil, cialis pills, "mu" => nil }
- begin
- vars.keys.each do |var|
- print "#{var} = "
- val = gets
- vars[var] = val.chomp.to_i
- end
- reynolds = (vars["d"]*vars["v"]*vars["rho"]) / vars["mu"].to_f
- puts reynolds
- if (reynolds < 2100)
- puts "Laminar Flow"
- elsif (reynolds > 4000)
- puts "Turbulent Flow"
- else
- puts "Transient Flow"
- end
- print "Do you want to calculate again (y/n)? "
- end while gets.chomp != "n"
Cialis pills,
Comments: As you can see, cialis pills, I could not use the same trick here when asking for the variables, cialis pills, because when somebody wants to calculate again, cialis pills, Ruby will complain (although by printing a warning only) that the constants have been already set up. Cialis pills, Therefore I went for the hash solution. Cialis pills, I think the do-you-want-to-calculate-again part is straightforward so I won’t analyze that here.
“While running the program give value mu = 0.”
Ruby gives a rather interesting result in this case: infinity :-).
“Is there something built in the language itself?”
Sure: exception handling. Cialis pills, Division by zero could be caught with a ZeroDivisionError rescue clause.
Cialis pills, 6. Cialis pills, Problem: “Scientific calculator supporting addition, cialis pills, subtraction, cialis pills, multiplication, cialis pills, division, cialis pills, square-root, cialis pills, square, cialis pills, cube, cialis pills, sin, cialis pills, cos, cialis pills, tan, cialis pills, Factorial, cialis pills, inverse, cialis pills, modulus”
Cialis pills,
Solution:
Since this code snippet is longer It would look ugly here - you can download it from here instead. Cialis pills,
Screenshot:
Cialis pills, If you would like to try it, cialis pills, you will need the Tk bindings for Ruby (maybe you have them already, cialis pills, here on Ubuntu I did not). Cialis pills, Also note that only the regular 0-9 keys (and of course the mouse) work, cialis pills, the numpad ones do not. Cialis pills, One more little detail: % stands for modulo, cialis pills, not percent.
Cialis pills, Comments: Phew, cialis pills, this was a real challenge, cialis pills, mostly because I never did any GUI in Ruby before. Cialis pills, I was amazed that I could code up a relatively feature rich calculator in 100+ lines of code, cialis pills, without any golfing or trying to optimize for shortness. Cialis pills, What I wanted to say with this is that the shortness does not praise my programming skills (since I did not eve try to golf) but the superb terseness of Ruby. Cialis pills, OK, cialis pills, of course there are some problems (e.g. Cialis pills, cube, cialis pills, cos, cialis pills, tan, cialis pills, inverse are not implemented) but the usability/amount of code ratio is unbelievably high.
Cialis pills, The GUI is also not the nicest since I have used Tk - wxRuby or qt-ruby would produce much nicer results, cialis pills, but since I did not code any GUI in Ruby previously, cialis pills, I have decided to try the good-old-skool Tk for the first time.
Cialis pills, 7. Cialis pills, Problem: “Printing output in different formats (say rounding up to 5 decimal places, cialis pills, truncating after 4 decimal places, cialis pills, padding zeros to the right and left, cialis pills, right and left justification)(Input output operations)”
Cialis pills, Solution:
Cialis pills,
- #rounding up to 5 decimal pleaces
- puts sprintf("%.5f", cialis pills, 124.567896)
- #truncating after 4 decimal places
- def truncate(number, cialis pills, places)
- (number * (10 ** places)).floor / (10 ** places).to_f
- end
- puts truncate(124.56789, cialis pills, 4)
- #padding zeroes to the left
- puts ‘hello’.rjust(10, cialis pills,’0‘)
- #padding zeroes to the right
- puts ‘hello’.ljust(10, cialis pills,’0‘)
- #right justification
- puts ">>#{’hello’.rjust(20)}<<"
- #left justification
- puts ">>#{’hello’.ljust(20)}<<"
Cialis pills, Comments: Amazingly lot of things can be done with sprintf() - I could solve nearly all the problems with it - but that would not really be rubyish, cialis pills, so I have decided for built-in (and one homegrown) functions. Cialis pills, However, cialis pills, mastering (s)printf() is a very handy thing, cialis pills, since nearly all big players (C (of course :-)), cialis pills, C++, cialis pills, Java, cialis pills, PHP, cialis pills, … Cialis pills, ) have it so you get a powerful function in more languages for the price of learning one). Cialis pills, As you can see, cialis pills, r/ljust is a nice one, cialis pills, too.
Cialis pills, 8. Cialis pills, Problem: “Open a text file and convert it into HTML file. Cialis pills, (File operations/Strings)”
Cialis pills, Solution: Well, cialis pills, this problem was not specified in a great detail, cialis pills, to say the least - or to put it otherwise, cialis pills, the solvers are given a great freedom to provide a solution spiced up with their fantasy. Cialis pills, This is what I came up with:
Cialis pills,