Discussion
· Jan 10, 2021

Code Golf: Diamonds

To start the year let's have a round of CodeGolf!

You know the drill. Shortest solution wins.

Print a size ascending range of Diamonds using the numbers 1 to 9, ranging from size 1 to size N, each diamond separated by a blank line.

A size 1 diamond should look like this, a single centered 1:

         1

With the size N=9 diamond looking like this:

         1
        121
       12321
      1234321
     123454321
    12345654321
   1234567654321
  123456787654321
 12345678987654321
  123456787654321
   1234567654321
    12345654321
     123454321
      1234321
       12321
        121
         1

Bonus Level: For N>9 you can either reuse 1-9 or supply arbitrary characters.

Discussion (19)2
Log in or sign up to continue

Maybe there are shorter solutions, but somebody must start the game... (I hope, class- and method name does not count)

Class DC.CodeGolf Extends %RegisteredObject
{ 
/// Diamonds from 1 thru 9 (max)
ClassMethod Diamond9(n)
{
  f n=1:1:n f i=1:1:n-1,n,n-1:-1:1 {s a=$e(1234567890,1,i-1) w ?n-i,a,i,$re(a),!} w !
} 

/// Diamonds from 1 thru 16 (max)
ClassMethod Diamond16(n)
{
   f n=1:1:n f i=1:1:n-1,n,n-1:-1:1 {s a=$e("1234567890abcdef",1,i) w ?n-i,a,$re($e(a,1,*-1)),!} w !
} 

}

@Sergei.Shutov   $e(112345678) prevents you to pass N>9

           1
          121
         12321
        1234321
       123454321
      12345654321
     1234567654321
    123456787654321
   12345678987654321
  123456781087654321
 123456781187654321
123456781287654321
 123456781187654321
  123456781087654321
   12345678987654321
    123456787654321
     1234567654321
      12345654321
       123454321
        1234321
         12321
          121
           1
 


@Julius Kavay    similar issue, but limit is 16

My interpretation was N>9  is any number >9

OK, you want it short and endless? You can get it!

Diamond() works from 0 thru 10 using 63 chars

Infinite() works from 0 thru Cache's maxint and has 66 chars of source code.

ClassMethod Diamond(n)
{
   f n=1:1:n w ! f j=1:1:n,n-1:-1:1 w !?n-j f i=1:1:2*j-1 w i#-j+j
}

ClassMethod Infinite(n)
{
   f n=1:1:n w ! f j=1:1:n,n-1:-1:1 w !?n-j f i=1:1:2*j-1 w i#-j+j#10
}
 
Some output

I see right now,  cut-and-paste without looking-and-checking isn't good! Sorry, for some stupid reason, I copied the wrong lines. The correct ones are:

ClassMethod Diamond(n)
{
   f n=1:1:n w ! f j=1:1:n,n-1:-1:1 w !?n-j f i=1:1:j,j-1:-1:1 w i
}

ClassMethod Infinite(n)
{
   f n=1:1:n w ! f j=1:1:n,n-1:-1:1 w !?n-j f i=1:1:j,j-1:-1:1 w i#10
}

Also, Dimond() works from 0 thru 9 (and not thru 10). The line lengths (with 63 and 66 chars) were correct. Finally, the correct output:

do ##class(DC.CodeGolf).Diamond(3)

1

 1
121
 1

  1
 121
12321
 121
  1

UTC: 2021-01-10 21:39:34

N<=9 :   73 chr

f i=1:1:N w ! f j=1:1:i,i-1:-1:1 w !?N-j f l=1:1:j {w l} f r=l-1:-1:1 w r

N>9 : 78 chr

f i=1:1:N w ! f j=1:1:i,i-1:-1:1 w !?N-j f l=1:1:j {w l#10} f r=l-1:-1:1 w r#10
 
eg: N=14