tag:blogger.com,1999:blog-76465252949879726222017-07-06T18:47:40.388+09:00Guillaume Nargeot's Technical BlogGuillaume Nargeothttp://www.blogger.com/profile/10404155037936154892noreply@blogger.comBlogger8125tag:blogger.com,1999:blog-7646525294987972622.post-33849721216978314662009-10-03T00:21:00.000+09:002009-10-18T23:32:37.236+09:00On solving Project Euler - Part 3In the first two parts of this post (<a href="http://guillaume-nargeot.blogspot.com/2009/09/on-solving-project-euler-part-1.html">first one</a>, <a href="http://guillaume-nargeot.blogspot.com/2009/09/on-solving-project-euler-part-2.html">second one</a>), we focused on <a href="http://projecteuler.net/">Project Euler</a> problems that could easily be solved using naive algorithms and adequate programming language. But this is just a small part of the problems available on the website. Fortunately, far more interesting problems are waiting for you in Project Euler challenges database, and you will need more mathematical and technical skills to solve them.<br /><br />This time, I would like to focus on a category of problems almost as simple as the previous ones, but for which you will have to resort to <a href="http://en.wikipedia.org/wiki/Dynamic_programming">dynamic programming</a> in order to solve them. If you do not know what dynamic programming is, here's the definition from Wikipedia:<br /><blockquote>In mathematics and computer science, dynamic programming is a method of solving complex problems by breaking them down into simpler steps. It is applicable to problems that exhibit the properties of overlapping subproblems and optimal substructure.</blockquote><blockquote></blockquote>Let's take the simple example of the <a href="http://en.wikipedia.org/wiki/Fibonacci_number">Fibonacci numbers</a>. The n<sup>th</sup> number of Fibonacci, is defined by the recurring function F<sub>n</sub> = F<sub>n-1</sub> + F<sub>n-2</sub>, with F<sub>0</sub> = 0 and F<sub>1</sub> = 1. Implementing such a function is very simple in any language, but unfortunately it is impractical due to performance issues. Indeed, the complexity of this algorithm is exponential. Thus, trying to compute values after F<sub>30</sub> starts to take a lot of time...<br />By writing on paper the process to compute a small Fibonacci number such as the 5<sup>th</sup> one, you would quickly notice that intermediate values are computed several times, which is a loss of time. This is where dynamic programming comes to our help!<br /><br />A first approach, the <span style="font-style: italic;">bottom-top</span> one, would be to always remember F<sub>n-1</sub> and F<sub>n-2</sub>, starting with 0 and 1. Then, we would compute the next value, and store it as the new F<sub>n-1</sub>, and shift the previous F<sub>n-1</sub> in F<sub>n-2</sub>. Repeating this process until F<sub>n</sub> would give us its value in time complexity O(n), which is far better than the <a href="http://stackoverflow.com/questions/360748/computational-complexity-of-fibonacci-sequence">exponential complexity</a> of the naive implementation we saw before. Here's how you could implement this approach using <a href="http://clojure.org/">Clojure</a> lazy infinite sequence:<br /><br /><script src="http://gist.github.com/190943.js"></script>Now that we have an efficient implementation of the Fibonacci sequence, the solution to <a href="http://projecteuler.net/index.php?section=problems&id=2">problem 2</a> is straightforward:<br /><br /><script src="http://gist.github.com/190944.js"></script>Another approach to the Fibonacci function implementation is the <span style="font-style: italic;">top-bottom</span> one. This approach basically consist in <a href="http://en.wikipedia.org/wiki/Memoization">memoizing</a> intermediate results so that they can be reused in later steps of the computation. Language such as <a href="http://www.factorcode.org/">Factor</a> make this really easy, by providing native support of memoization with the keyword <span style="font-style: italic;">MEMO:</span>, as you can see in the following code:<br /><br /><script src="http://gist.github.com/190960.js"></script>We can now make use of this function in order to solve <a href="http://projecteuler.net/index.php?section=problems&id=25">problem 25</a> with the following code:<br /><br /><script src="http://gist.github.com/190962.js"></script>Now that we saw how dynamic programming could be used to solve trivial problems related to recursively defined number such as Fibonacci numbers, let's take a more interesting example with the <a href="http://projecteuler.net/index.php?section=problems&id=81">problem 81</a>, explained as follows:<br /><blockquote><p>In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by only moving to the right and down, is indicated in bold red and is equal to 2427.</p><div style="text-align: center;"><img style="width: 182px; height: 130px;" src="http://4.bp.blogspot.com/_ogQUBTgNBDs/SsGSLW0npfI/AAAAAAAALik/6HONi54s4Bc/s320/euler81.png" alt="" id="BLOGGER_PHOTO_ID_5386747353114322418" border="0" /></div><p>Find the minimal path sum, in <a href="http://projecteuler.net/project/matrix.txt">matrix.txt</a>, a 31K text file containing a 80 by 80 matrix, from the top left to the bottom right by only moving right and down.</p></blockquote>Considering the previous matrix as a graph, each cell being a node, and each possible right or down move being the edges, this problem becomes a <a href="http://en.wikipedia.org/wiki/Shortest_path_problem">shortest-path problem</a>.<br />A naive approach would be to try every single path... and if you already solved the <a href="http://projecteuler.net/index.php?section=problems&id=15">problem 15</a>, you would know that there are 160!/(80!80!) of them! For information, it is a <a href="http://www.wolframalpha.com/input/?i=160%21%2F%2880%2180%21%29">47-digit number</a>.<br />Obviously using this naive algorithm is a wrong way, as it doesn't scale at all.<br />But again, this is a field where dynamic programming can help us a lot, with <a href="http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm">Dijkstra's algorithm</a>. This algorithm is a form a dynamic programming, as it calculates the shortest path from an intermediate node to another node reusing the previously calculated shortest path from the start node to this intermediate node.<br />Having the graph data as a matrix stored in a variable <span style="font-style: italic;">m</span>, the implementation is quite obvious in <a href="http://www.ruby-lang.org/en/">Ruby</a>:<br /><br /><script src="http://gist.github.com/191812.js"></script>Finally, the shortest path is given by the accumulated value in most the bottom right cell (<span style="font-style: italic;">m[79][79]</span>).<br /><br />We saw in this post how dynamic programming can radically improve the performance of certain type of algorithms, which wouldn't scale at all on large data sets. This method can be applied to several Project Euler challenges, as we saw in problems 2, 25 and 81. The basic way of proceeding is to find sub-problems which can reuse intermediate results leading naturally to the final result.<br />In the next post, I will introduce other general approach that can be used to solve Project Euler challenges.Guillaume Nargeothttp://www.blogger.com/profile/10404155037936154892noreply@blogger.com35tag:blogger.com,1999:blog-7646525294987972622.post-37569160196900087992009-09-27T19:02:00.000+09:002009-09-28T12:17:35.134+09:00On solving Project Euler - Part 2In the <a href="http://guillaume-nargeot.blogspot.com/2009/09/on-solving-project-euler-part-1.html">previous post</a>, we saw that some of the <a href="http://projecteuler.net/">Project Euler</a> challenges could be solved using naive brute-force algorithms directly transcribed from their description. Today, I would like to introduce another category of problems, which is an extension to the previous one: problems that can be easily solved using mathematical software.<br /><br />Some of the Project Euler challenges target mathematical fields using very large numbers: for example factorials. As you might know, in programming languages such as C, all the built-in mathematical operations can only be performed on a limited set of numbers: int, long, etc. In order to perform operations on bigger numbers, you will have to rely on specific libraries such as <a href="http://gmplib.org/">GNU MP Bignum</a>, and use a different syntax (no more "+" or "*" operators). This results in ugly code, and more trouble only to write simple algorithms.<br /><br />For this category of problems, if you still want to implement naive algorithms, you should choose a programming language which naturally handles big numbers. Actually, most of the "recent" programming languages like <a href="http://www.ruby-lang.org/en/">Ruby</a>, <a href="http://clojure.org/">Clojure</a> and <a href="http://www.factorcode.org/">Factor</a> can handle them without you notice it.<br /><br />Let's take the <a href="http://projecteuler.net/index.php?section=problems&id=16">problem 16</a> as a first example:<br /><blockquote><div class="problem_content"> <p>2<sup>15</sup> = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.</p> <p>What is the sum of the digits of the number 2<sup>1000</sup>?</p> </div></blockquote>One can imagine that 2 raised to the 1000<sup>th</sup> power is a very large number: indeed, it actually has 603 digits! This is far more that what standard the standard long type can handle in C: 2<sup>32</sup> -1 (4,294,967,295).<br />Fortunately, it is a peace of cake for Ruby to handle these numbers. As you will see in the source code below, no special syntax is required to perform operations like additions on large numbers, you can use the usual operator "+":<br /><br /><script src="http://gist.github.com/190168.js"></script>I would like to give a special mention to the <a href="http://www.jsoftware.com/">J programming language</a> which, apart from handling large numbers as easily as Ruby, also provides a very concise syntax when it comes to number processing, as shown in the following code (solution to the previous problem):<br /><script src="http://gist.github.com/190169.js"></script><br /><br />Another problem that can be solved easily with languages that naturally handle large number is the <a href="http://projecteuler.net/index.php?section=problems&id=20">problem 20</a>:<br /><blockquote><div class="problem_content"> <p><i>n</i>! means <i>n</i> x (<i>n</i> - 1) x ... x 3 x 2 x 1</p> <p>Find the sum of the digits in the number 100!</p> </div></blockquote>The pattern of this challenge being the same as the 20<sup>th</sup>, the solutions in Ruby and J are quite straightforward again:<br /><br /><script src="http://gist.github.com/190170.js"></script><br /><script src="http://gist.github.com/190167.js"></script><br /><br />If you give a quick look at the challenges list, you will notice that many of them involve <a href="http://en.wikipedia.org/wiki/Prime_number">prime numbers</a>. More than large number handling, these prime numbers are a big reason to choose one language over another in order to solve certain problems. For example, J provides built-in functions to compute efficiently prime numbers. Of course, you could use libraries like <span style="font-style: italic;">mathn</span> in Ruby, or implement the functions that you need in Clojure, but it would just add some more trouble, and usually the efficiency can't be compared to the native functions provided by J, although it is not always an issue. So let's test the power of J by solving the <a href="http://projecteuler.net/index.php?section=problems&id=7">problem 7</a>:<br /><blockquote><div class="problem_content"> <p>By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6<sup>th</sup> prime is 13.</p> <p>What is the 10001<sup>st</sup> prime number?</p> </div></blockquote>J built-in function <i>p:</i> returns the n<sup>th</sup> prime number, so the solution can't be more simple than:<br /><br /><script src="http://gist.github.com/190177.js"></script>In the same field, <a href="http://en.wikipedia.org/wiki/Mathematica">Mathematica</a> is incredibly powerful too, but unfortunately it is a proprietary and quite expensive system... It also provides a built-in function to get the n<sup>th</sup> prime number, and again the following code is enough to solve the previous problem:<br /><br /><script src="http://gist.github.com/190178.js"></script>The <a href="http://projecteuler.net/index.php?section=problems&id=10">problem 10</a> is also one of those which requires prime number computation, and can be solved using a naive brute-force algorithm:<br /><br /><blockquote><p>The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.</p> <p>Find the sum of all the primes below two million.</p></blockquote>J provides the inverse function of <i>p:</i>, which is <i>p:^:_1</i> (you should read it <i>p:<sup>-1</sup></i>): the mathematical function called <a href="http://en.wikipedia.org/wiki/Prime-counting_function">pi</a>, which gives the number of primes less than a given number n. It can be used in the following way to solve this challenge:<br /><br /><script src="http://gist.github.com/190172.js"></script>Again, Mathematica provides several functions related to prime numbers, such as PrimeQ, a prime testing function, which can be used to solve the same problem in a slightly different way:<br /><br /><script src="http://gist.github.com/190176.js"></script>Mathematica useful functions are not limited to the field of prime numbers. The <a href="http://projecteuler.net/index.php?section=problems&id=65">problem 65</a>, dealing with <a href="http://en.wikipedia.org/wiki/Continued_fraction">continued fractions</a>, is another nice example showing how good Mathematica is at solving Project Euler in a clean way. Here's the self-explained <a href="http://www.wolframalpha.com/input/?i=Total[IntegerDigits[Numerator[Convergents[E%2C+100][[100]]]]]">source code</a>:<br /><br /><script src="http://gist.github.com/191763.js"></script>We saw in this post that the field related to the challenge can drive our choice of language to solve it in a very simple way, for example with the native and transparent support of big numbers, or with powerful built-in functions to deal with prime numbers and continued fractions.<br />In the next post, I would like to introduce some simple and common ways of solving problems more efficiently than naive brute-force.Guillaume Nargeothttp://www.blogger.com/profile/10404155037936154892noreply@blogger.com1tag:blogger.com,1999:blog-7646525294987972622.post-85164276980794601772009-09-20T12:57:00.000+09:002009-09-22T09:48:15.490+09:00On solving Project Euler - Part 1For those of you who have never heard about it, <a href="http://projecteuler.net/">Project Euler</a> is a website publishing almost every week new programming and mathematical challenges. It has been almost one year since I discovered it, and I must tell that I have really become addicted to it.<br />I would recommend it to any programmer who do not hate mathematics, as it can be used for several purposes: challenging your mathematical and programming skills, learning new mathematics concepts, and it is especially a good practice for learning a new programming language. Of course, it won't help you to become better at designing software, but it might help help you to improve your algorithm writing skills.<br /><br />As I said, both mathematical and programming skills are needed to solve Project Euler problems. While some of them might be solved with just a simple brute force algorithm, or on the opposite, with a clever formula, most of the problems will require to use both your mathematical and algorithm implementation skills.<br /><br />On the <a href="http://projecteuler.net/index.php?section=problems">listing page</a>, the problems are ordered by publishing date. Usually, trying to solve them in this order is better, as concepts introduced in older problems are often reused in newer problems, and it will make them easier to solve than just starting from zero.<br />The listing can also be sorted by the difficulty of the problems (you will need to register), which is determined by the number of people who solved them: indeed, once you solved a problem, you can input your answer in a form and verify if it is correct. In the case it is, you will then be able to access the forum thread of this problem, where people usually post their solution. This is a very interesting feature of Project Euler, because you can see what are the other algorithms that can be used, in several programming languages.<br /><br />We could also classify the problems in different categories based on how they can be solved, and what are the most efficient languages to solved them.<br /><br />A first category could be the one of problems which can be solved by implementing the obvious algorithm transcribed from the problem itself. An important point that I didn't mention before is that all the problems have been designed according to a "one-minute rule", meaning that there always exist an algorithm that can solve the problem in less that one minute even on modest hardware. Although this rule will usually lead you to rethink your first (slow) brute-force algorithm in order to make your solution comply to it, some problems can just be brute-forced as I said before.<br /><br /><div style="text-align: left;">The <a href="http://projecteuler.net/index.php?section=problems&id=1">problem 1</a> is a nice and simple example from this category:<br /></div><blockquote><div class="problem_content"> <p>If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.</p> <p>Find the sum of all the multiples of 3 or 5 below 1000.</p> </div></blockquote>An obvious brute-force algorithm in <a href="http://www.ruby-lang.org/en/">Ruby</a> could be:<br /><br /><script src="http://gist.github.com/190051.js"></script>This simple algorithm comply with the one-minute rule, but might not scale well for bigger values, for which we might need a better algorithm or formula. In same same naive way, the following <a href="http://clojure.org/">Clojure</a> code gives the answer to the <a href="http://projecteuler.net/index.php?section=problems&id=6">problem 6</a>:<br /><br /><script src="http://gist.github.com/190063.js"></script>This problem can also be solved with the following Factor code:<br /><br /><script src="http://gist.github.com/190670.js"></script>We will see in the next posts the other categories of challenges available on Project Euler, and the way to solve them efficiently. Indeed, implementing brute-force algorithms is not the real fun of Project Euler, and is really not what you need to improve your problem solving skills!<br /><br />As an exercise, you can try to solve the <a href="http://projecteuler.net/index.php?sectiojavascript:void%280%29n=problems&id=187">problem 187</a>, which seem simple to solve with a naive brute-force algorithm, but there is little chance that it complies with the one-minute rule!<br />A more clever algorithm can solve this problem in seconds, and a more advanced one can solve it in an instant...Guillaume Nargeothttp://www.blogger.com/profile/10404155037936154892noreply@blogger.com0tag:blogger.com,1999:blog-7646525294987972622.post-56009420220573540902009-09-12T12:06:00.001+09:002009-09-12T12:08:01.310+09:00Takeshi's Komanechi University MathematicsI suppose some of you might already know <a href="http://en.wikipedia.org/wiki/Takeshi_Kitano">Takeshi Kitano</a> as a filmmaker, who shot great movies like <a href="http://en.wikipedia.org/wiki/Sonatine">Sonatine</a> and <a href="http://en.wikipedia.org/wiki/Kikujiro">Kikujiro</a>.<br /><br />Here in Japan, he is very famous, but not for his movies. More that a filmmaker, he is popular as a comedian and appears a lot on TV, know as <span style="font-style: italic;">Beat Takeshi</span>.<br /><br />But what you might not know, even living in Japan, is the <span style="font-style: italic;">Math Kitano</span> the mathematician. Indeed, during his childhood, Takeshi's mother was very strict concerning education. He went to the renown Meiji University and usually says that he would have liked to become a mathematician if he didn't become a comedian.<br /><br />This passion for mathematics gave birth in 2006 to the TV program "Takeshi's Komanechi University Mathematics" (<a href="http://ja.wikipedia.org/wiki/%E3%81%9F%E3%81%91%E3%81%97%E3%81%AE%E3%82%B3%E3%83%9E%E3%83%8D%E3%83%81%E5%A4%A7%E5%AD%A6%E6%95%B0%E5%AD%A6%E7%A7%91">たけしのコマネチ大学数学科</a>).<br />Aired every Thursday between 25:15 and 25:45 on <a href="http://en.wikipedia.org/wiki/Fuji_Television">Fuji Television</a>, this program aims at showing the charm of mathematics while being as well an entertainment program.<br />Every week, three teams are trying to solve a problem (of university entry level): Takeshi, aka "Math Kitano", two pretty student girls from Tokyo University, and a a group of four comedians.<br /><br />Surprisingly,<span style="font-style: italic;"> Math Kitano</span> performs very well and sometimes outperforms Tokyo University students, especially in geometry related problems, which must be one of the reasons why the way he shots his movies is so geometric.<br />On the other side, the team of four comedians always use very weird but funny ways to solve problems, and it is quite enjoying to watch, even from a mathematician point of view.<br /><br />After discovering this TV program, I just became addicted, and found myself solving these problems every week. I think this is one good way to keep one's mathematics abilities, and I would recommend it to any people living in Japan.<br /><br />To give you a taste of it, here is a link the some problems on my Picasa galleries:<br /><div align="center"><table style="width:194px;"><tr><td align="center" style="height:194px;background:url(http://picasaweb.google.com/s/c/transparent_album_background.gif) no-repeat left"><a href="http://picasaweb.google.com/killy971/lqjqAG?feat=embedwebsite"><img src="http://lh6.ggpht.com/_ogQUBTgNBDs/SqsKbrfNjTE/AAAAAAAALf4/jA5BiJArMR8/s160-c/lqjqAG.jpg" width="160" height="160" style="margin:1px 0 0 4px;"></a></td></tr><tr><td style="text-align:center;font-family:arial,sans-serif;font-size:11px"><a href="http://picasaweb.google.com/killy971/lqjqAG?feat=embedwebsite" style="color:#4D4D4D;font-weight:bold;text-decoration:none;">たけしのコマネチ大学数学科</a></td></tr></table></div><br />And <a href="http://www.youtube.com/results?search_query=%E3%82%B3%E3%83%9E%E3%83%8D%E3%83%81%E5%A4%A7%E5%AD%A6%E6%95%B0%E5%AD%A6%E7%A7%91&search_type=&aq=f">here's a link</a> to a YouTube search results page.<br /><br />I hope I will find some time solve problems in the next posts.Guillaume Nargeothttp://www.blogger.com/profile/10404155037936154892noreply@blogger.com0tag:blogger.com,1999:blog-7646525294987972622.post-67476472291304154712009-08-22T15:36:00.000+09:002009-09-12T12:09:14.966+09:00Think twice before naming your new programming languageSmart people invent new programming languages, with powerful features, that perform really well. What else do we need?<br /><br />When you want to learn and use these new programming languages, you might want to buy books or to search for tutorials, code examples, blog articles, etc.<br /><br />There comes the name: you might have plenty of good reasons for choosing a certain name for your programming language, but before deciding on it please think about people who are willing to use it.<br /><br />I am one of those: recently, I am learning the <a href="http://factorcode.org/">Factor</a> and <a href="http://www.jsoftware.com/">J</a> programming languages, or I should say "I am trying to learn". I suppose that you can imagine my frustration when I try to search for information using Google, or for books using Amazon.<br /><br />Just think about what kind of results you will get when looking for something related to Factor on Google...<br /><br />Of course you could tell me that there is the Factor <a href="http://docs.factorcode.org/">documentation</a>. But I don't want to limit myself to the official documentation: I want to read books if they exist, I want to read code snippets shared by other people, I want to read blog posts, search on GitHub (Factor is <a href="http://github.com/languages">not registered yet</a>), and the reality is that I just can't. This is so frustrating, especially for language such as J, which are even more difficult to search for, and I don't need to explain you why...<br /><br />Some work have been done to make C and C++ easy to search on the internet, but nothing yet for J yet. I think the same goes for R, and if I read <a href="http://en.wikipedia.org/wiki/List_of_programming_languages">this wiki page</a>, it seems that I could quote almost the whole alphabet!<br /><br />So please, I beg you, the next time you create a great programming language such as Factor or J, think carefully about a name that will be easy to search for on the internet. Do not use a one-character or two-character name, only use characters from the Latin alphabet, do not use a common word, and just make it as unique as possible.Guillaume Nargeothttp://www.blogger.com/profile/10404155037936154892noreply@blogger.com32tag:blogger.com,1999:blog-7646525294987972622.post-47846346558866904262009-07-26T21:46:00.000+09:002009-09-21T10:37:20.872+09:00Project Euler and OCaml prime number list generatorHalf a year has passed... The main reason why I didn't write anything concerning Ruby golfing is mainly because I stopped practicing quite a while ago, so I do not have any fresh tips to write about now.<br /><br />Recently, I am mostly spending my time learning the programming languages <a href="http://clojure.org/">Clojure</a> and <a href="http://www.factorcode.org/">Factor</a>, using them to solve <a href="http://projecteuler.net/">Project Euler</a> problems. Clojure reminds of <a href="http://en.wikipedia.org/wiki/Scheme_%28programming_language%29">Scheme</a>, but I am very new to the concatenative paradigm of Factor, as I never learned Forth or any similar language.<br />Providing a fairly succinct syntax, they perform very well, which is the main reason why I'm now using them over Ruby.<br /><br />Some weeks ago, <a href="http://gmarceau.qc.ca/blog/2009/05/speed-size-and-dependability-of.html">this article</a> in which are analyzed the results of <a href="http://shootout.alioth.debian.org/">the programming language benchmarks game</a> made me want to use again the <a href="http://caml.inria.fr/">OCaml</a> language, that I had previously learned and used during my studies at the university. This analysis shows it as an almost ideal programming language in terms of code size vs performance trade-off.<br /><br />Several problems of the Project Euler deal with prime numbers, so I needed some code to generate them. Unfortunately, I couldn't find any simple prime generating code on the internet: it seems that finding OCaml code snippets is not an easy task...<br />Here is quite simple implementation of the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">Sieve of Eratosthenes</a> which is quite fast (even when running only bytecode) and should be enough for most of the problems that require to use prime numbers in the int range:<br /><br /><script src="http://gist.github.com/190016.js"></script>Which will for example produce the following result:<br /><pre># let primes = primes_upto 4000000 in<br /> List.nth primes ((List.length primes) - 1);;<br />- : int = 3999971</pre><br />For problems requiring bigger primes, but not an exhaustive list of them, using algorithms such as the <a href="http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test">Miller-Rabin primality</a> test is a better choice.Guillaume Nargeothttp://www.blogger.com/profile/10404155037936154892noreply@blogger.com2tag:blogger.com,1999:blog-7646525294987972622.post-59218582758428205592009-01-18T22:18:00.000+09:002009-09-29T13:35:27.688+09:00Code Golfing in Ruby - part 1About two years ago, while looking for some material about Ruby programming, I came across some website related to golf. If this is the first time you hear about golfing as a subject related to programming, which we can shortly define as "trying to solve a coding problem using the least number of keystrokes". I only know two golf related websites still in activity:<br /><ul><li>- <a href="http://golf.shinh.org/">anarchy golf</a>, which is quite active, where one can challenge the problems with any of the 66 supported languages,</li><li>- <a href="http://codegolf.com/">Codegolf</a>, which supports only 4 languages (Perl, PHP, Python and Ruby). Even if my golfing experience is quite short, I still would like to introduce some tips for beginners to get started in golfing. Some people might say that code golfing is a bad practice, but I think there are some useful things to learn from it.<br /></li></ul><br />When you start solving a problem, you will firstly implement an obvious algorithm, and then try to shorten your code the most you can. Then you might start to look for alternative syntax with the same meaning, for useless processing, and maybe think about another way to solve the problem, etc.<br /><br />During all this process, you will first learn a lot about the syntax of the language you are using to solve you problem. Do not misinterpret my words: I really do not recommend you to practice golfing in order to learn a new language! In this case, I would better recommend to solve problems from the Project Euler. What I am trying to say is that to solve a golfing problem, you will certainly have to explore the language syntax, and implement multiple algorithms, which is a profitable experience.<br /><br />Now let's get to the point of this post, which is to introduce these ruby golfing tips.<br /><br />In this first post, we will focus on making use of predefined variables.<br />You will find in this <a href="http://www.zenspider.com/Languages/Ruby/QuickRef.html#18">ruby language quick reference</a> page that there are a few predefined variables with a short name starting by the dollar sign. Let's have a look at the following ones:<br /><pre name="code" class="ruby">$/ # The input record separator, newline by default.<br />$* # Command line arguments given for the script sans args.<br />$$ # The process number of the Ruby running this script.<br /></pre><br />As written in this documentation, $$ is a non-assignable variable containing a number which is usually bigger than 1000. Let's say that you need to iterate over a certain large number of times, and you need the number of the current iteration. In this case, you can use this already initialized variable as follows:<br /><pre name="code" class="ruby">$$.times{|i|}<br /><br /># here's the value I have on my current irb session:<br />rb(main):001:0> p$$<br />16434<br />=> nil<br /><br />#You can also make a big range like this:<br />(0..$$)</pre><br />Then suppose than you need to write a newline character into you script, using the predefined variable $/ will be one byte shorter than "\n".<br /><pre name="code" class="ruby">irb(main):001:0> p$/<br />"\n"<br />=> nil</pre><br />The predefined non-assignable variable $*, which contains the command line argument can be used when you need an empty array and can limit the number of calls to it. The advantage of this variable is that it contains an already initialized array. In a normal case, you would need to initialize an array like this: a=[]. Even if the variable name "$*" is 2 bytes long, it can be useful if you find a way to use it without having to name it too often. Look by yourself in irb:<br /><pre name="code" class="ruby">irb(main):001:0> p$*<br />[]<br />=> nil</pre><br />It was a little short for this first part, but I hope some people will find it useful. You can look for other predefined variables, and imagine the ways you can use them properly to shorten your code length, and I am pretty sure there is still a lot to do in this field.<br /><br />See you soon for the second part of this article!Guillaume Nargeothttp://www.blogger.com/profile/10404155037936154892noreply@blogger.com1tag:blogger.com,1999:blog-7646525294987972622.post-35086359972536133032009-01-15T22:49:00.000+09:002009-01-15T22:51:54.516+09:00First postOne of my new year's resolutions is to create this blog, and share my (still short) experience in the IT field with all of you. As the language I use the most is Ruby (my favorite one), it might be the main subject of my posts. Still, as I am quite a curious person, there will surely be exceptions, and I hope I will be able to produce some useful content.<br /><br />To introduce myself in a few words, I am 24, French, currently living and working in Japan. My work consists basically in developing and maintaining a log management software in Java.Guillaume Nargeothttp://www.blogger.com/profile/10404155037936154892noreply@blogger.com0