Archive for the 'Golf' Category

isPrime in One Line of Perl

Tuesday, July 17th, 2007

As a follow up to Finding the first 20 terms in the Fibonacci Series, next in the 3Monkey Golf series — Determining if a number is prime. The following is a fairly simple Perl one liner to do the trick. I’m interested in seeing implementations in other languages. I will be posting follow ups with the best submissions from both Golf challenges at the end of the week.

Perl Code

perl -wle'print(1)if(1xtarget_number)!~/^1?$|^(11+?)\1+$/'

Character count = 36

Golf Rules:

  • Only pure source characters are counted, that is, in my example the characters “perl -wle'” and trailing “‘” do not count.
  • For this challenge, the meta variable target_number counts as a single character, butshould be able to be replaced with any reasonable number.
  • Output must be of the form 0, 1, Y, N, true, false, or some other easily recognizable indication of Yes or No.
  • Please note that use og characters such as > and < require escaping as & lt; and & gt;
    If you have difficulty posting your solution please email me the solution at stacy (at) 3monkeyweb (period) com and I will make sure it gets posted.

    Good luck, and until next time.

    -3Monkeys

    Fibonacci Series in One Line of Perl

    Thursday, July 12th, 2007

    Not ground breaking but here are the first 20 terms in the Fibonacci Series.

    Code
    perl -e'@p=(0,1);until($#p>20){print"$p[-2]\n";push @p,$p[-2]+$p[-1]}'
    Output

    0
    1
    1
    2
    3
    5
    8
    13
    21
    34
    55
    89
    144
    233
    377
    610
    987
    1597
    2584
    4181

    Can you do better? What about different languages?

    Update: it has been suggested that for languages such as Java and C to be included in this experiment, that only the total number of pure source characters be included in the count. Therefore my perl solution in the comments below has 56 pure source characters.

    For more information on the Fibonacci Series see http://en.wikipedia.org/wiki/Fibonacci_number

    -3Monkeys