Why is there a space before * in ' *'? Thanks,

-----Original Message-----
From: "Dan Bron" <[email protected]>
Sent: ‎7/‎22/‎2013 7:54 PM
To: "'J Programming'" <[email protected]>
Subject: [Jprogramming] Code golf: approximate pi

There's a code golf challenge on StackOverflow [1] which asks us to generate
an approximation of a circle in ASCII (i.e. using integral Cartesian
coordinates) and a corresponding estimation of pi.

For example, the 8th order circle in ASCII has 15 rows and 8 columns and
gives an approximate value of pi of 3.125.  The detailed specifications of
input, output, and edge cases can be found at
http://stackoverflow.com/questions/2440314/code-golf-day/ but the general
concept is take positive integer as an input, and output the circle with its
corresponding estimate of pi. Like this:

           c 8
            *******    
         ************* 
        ***************
        ***************
        ***************
        ***************
         ************* 
            *******    
        3.125          

This is a code golf challenge. Most common programming languages can get it
down to ~100 characters.  The shortest solution, outside of J, is written in
bc (the command-line calculator) and weighs in at 88 characters.

Without too much effort, I put together a J solution of 47 characters (a
little over half the length of the previous champion)*.

Uncompressed, the verb might look like this:

        c =: verb define
                pythag   =. y > | j./~ i:y-1    NB.  r^2 > x^2 + y^2
                squished =. _2 {.\ pythag       NB.  Odd rows only
                piApx    =. (2 * +/ , squished) %  y*y
                (squished { ' *') , ": piApx
        )

Here it is in its compressed form:

        c=:*:({&' *'@],&":2%(%+/@,))_2{.\]>|@j./~@i:@<: 

Can you pare it down at all? Perhaps using a different approach?

Note also that there is extra credit available for a solution which handles
odd inputs (i.e. odd numbers) appropriately, which this version doesn't.

-Dan

* The 47 characters includes the assignment to a name, so the function can
be reused. 
  

----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to