Code Golf Asked on November 25, 2021
This question has been spreading like a virus in my office. There are quite a variety of approaches:
Print the following:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
123456787654321
1234567654321
12345654321
123454321
1234321
12321
121
1
Answers are scored in characters with fewer characters being better.
cls()function _draw()for i=1,9do for j=i-9,0do for k=-1,1,2do for l=0,1do print(i,72*l-(l-0.5)*(i-j)*8,48+k*j*6)end end end end end
Output:
Ungolfed version:
cls() //clear screen
function _draw() //keeps commandline off
for i=1,9 do //numbers
for j=i-9,0 do //position control
for k=-1,1,2 do //y axis switch
for l=0,1 do //x axis switch
print(i,72*l-(l-0.5)*(i-j)*8,48+k*j*6)
end
end
end
end
end
Answered by weatherman115 on November 25, 2021
Dim As Byte i,j,k
for i=-8 to 8 : for j=-8 to 9
k=abs(i)+abs(j)
if k > 8 then print " "; : else : ? chr(57-k);
next
?
next
Sleep
End
Answered by user3234709 on November 25, 2021
C
, 17 bytes»÷rṡF»S¦øṁ½ƛ÷⋎;øm
»÷rṡF»S - 123456789 as string
¦ - Take all the prefixes
øṁ - Vertical mirror
½ƛ÷⋎; - Halve and split, then join while removing the duplicate ends.
øm - Horizontal palindromize.
<C flag> - Center and join list by newlines
<implicit output> - Print
Answered by SjoerdPennings on November 25, 2021
-nr
, 55 bytesrange(17)-8|fabs|" "*.+"123456789"[:9-.]+"87654321"[.:]
fabs
is not supported on TIO but you can try it on https://jqplay.org/.
Alternatively try it on TIO with .*.|sqrt
instead of fabs
, for 59 bytes.
Answered by Lynn on November 25, 2021
-rn
, -6 bytes thanks to ovs and another -6 (plus -5 more indirectly) thanks to Michael Chatiskatzi
def r:range(9),7-range(8);r|[8-.-r|"(" "*.//1-.)"[:1]]|add
The -n
flag specifies that there is no input; the -r
flag outputs the result strings, each on its own line, without quotes.
def r: Define a helper function r
range(9), which generates the numbers 0 through 8, followed by
7 - range(8); the numbers 7 through 0
Main program:
r | Start with the results of r
[ For each of those numbers, put the following in a list:
8 - . - r | 8, minus the current number, minus the results of calling r again
"( For each of those numbers, interpolate the following into a string:
" " * . Try to repeat a space that many times
// and if the result is null (i.e. the number was less than 1),
1 - . subtract the number from 1 instead
)"
[:1] Take the first character of each resulting string
] | Take each resulting list of strings and
add concatenate it together
To help visualize what's going on, here's what just the r|[8-.-r]
part does:
[8,7,6,5,4,3,2,1,0,1,2,3,4,5,6,7,8]
[7,6,5,4,3,2,1,0,-1,0,1,2,3,4,5,6,7]
[6,5,4,3,2,1,0,-1,-2,-1,0,1,2,3,4,5,6]
[5,4,3,2,1,0,-1,-2,-3,-2,-1,0,1,2,3,4,5]
[4,3,2,1,0,-1,-2,-3,-4,-3,-2,-1,0,1,2,3,4]
[3,2,1,0,-1,-2,-3,-4,-5,-4,-3,-2,-1,0,1,2,3]
[2,1,0,-1,-2,-3,-4,-5,-6,-5,-4,-3,-2,-1,0,1,2]
[1,0,-1,-2,-3,-4,-5,-6,-7,-6,-5,-4,-3,-2,-1,0,1]
[0,-1,-2,-3,-4,-5,-6,-7,-8,-7,-6,-5,-4,-3,-2,-1,0]
[1,0,-1,-2,-3,-4,-5,-6,-7,-6,-5,-4,-3,-2,-1,0,1]
[2,1,0,-1,-2,-3,-4,-5,-6,-5,-4,-3,-2,-1,0,1,2]
[3,2,1,0,-1,-2,-3,-4,-5,-4,-3,-2,-1,0,1,2,3]
[4,3,2,1,0,-1,-2,-3,-4,-3,-2,-1,0,1,2,3,4]
[5,4,3,2,1,0,-1,-2,-3,-2,-1,0,1,2,3,4,5]
[6,5,4,3,2,1,0,-1,-2,-1,0,1,2,3,4,5,6]
[7,6,5,4,3,2,1,0,-1,0,1,2,3,4,5,6,7]
[8,7,6,5,4,3,2,1,0,1,2,3,4,5,6,7,8]
Any number that's greater than 0 gets turned into that many spaces (and then trimmed back to a single space). The other numbers gets subtracted from 1 (turning 0 .. -8 into 1 .. 9) and stringified.
Answered by DLosc on November 25, 2021
=CONCAT(LET(x,ABS(9-ROW(1:17)),y,9-ABS(9-COLUMN(A:R)),IFS(y>x,y-x,y," ",1,"
")))
Answered by Axuary on November 25, 2021
(( {#2-1}| {8})($3${#3+1}|1)(${#4+1}$4|)n){9}(( $6| )(${$7/10}|${$3/10})(${$8-1+1/$8*#7-1/$8}|7){#7-1}n){8}
The solution is divided into two parts, which generate the upper half of the diamond (including the center line) and the lower half, respectively. The upper half consists of group 1, repeated nine times (...n){9}
; the lower half consists of group 5, repeated eight times (...n){8}
.
The first part of each group handles the spaces. (I've replaced space with underscore in the explanations for better visibility.)
Upper-half spaces:
( {#2-1}| {8})
( ) Group 2:
_{#2-1} Space, repeated one less time than the previous length of group 2
| Or, if this is the first row and there is no previous value of group 2...
_{8} Space, repeated eight times
Lower-half spaces:
( $6| )
( ) Group 6:
_$6 Space, concatenated to the previous value of group 6
| Or, if this is the first row and there is no previous value of group 6...
_ A single space
Now for the diamond itself. It can be divided into four quadrants, and I used three different approaches to generate them:
We generate the left half (including the center) of each row with group 3, and the right half with group 4. For both halves, observe that we can generate the next row by concatenating a digit to the previous row:
1234 321
| |
v v
12345 4321
So we can use a similar approach to what we did for the bottom-half spaces. The only difference is that the character we're concatenating at each step needs to be calculated.
Top left quadrant:
($3${#3+1}|1)
( ) Group 3:
$3 Previous value of group 3
${ } concatenated to the result of...
#3+1 Previous length of group 3 plus 1
| Or, if this is the first row and there is no previous value of group 3...
1 The digit 1
Top right quadrant:
(${#4+1}$4|)
( ) Group 4:
${ } The result of...
#4+1 Previous length of group 4 plus 1
$4 concatenated to the previous value of group 4
| Or, if this is the first row and there is no previous value of group 4...
Empty string
We generate the left half (including the center) of each row with group 7. Observe that each row is obtained by removing the rightmost digit from the previous row:
12345
|
v
1234
If we treat the entire thing as an integer, we can perform this transformation easily by dividing it by ten:
(${$7/10}|${$3/10})
( ) Group 7:
${ } The result of...
$7/10 Previous value of group 7, divided by 10
| Or, if there is no previous value of group 7...
${ } The result of...
$3/10 Group 3 (the final upper-left quadrant row) divided by 10
There isn't an easy way to remove a digit from the left side of a previous match, so for the right half of each bottom row, we resort to generating one digit at a time with group 8. Here are the first three rows that we need to generate:
7654321
654321
54321
Each digit is one less than the previous digit, except that we have to "reset" when we hit 1. The reset value is always one less than the length of the left half of the row, which we have access to as group 7.
How can we tell when we've hit 1? I used an integer-division trick I first developed for programming in Acc!!: if N is a positive integer, then 1/N will be one iff N = 1 and zero if N > 1. Multiplying this quantity by (length of group 7) - 1 gives us the reset we need.
(${$8-1+1/$8*#7-1/$8}|7){#7-1}
( ) Group 8 (generates one digit at a time):
${ } The result of...
$8-1 Previous value of group 8, minus 1
+ #7 Plus the length of group 7
1/$8* if the previous value of group 8 equals 1
-1/$8 Minus 1 if the previous value of group 8 equals 1
| Or, if there is no previous value of group 8...
7 The digit 7
{ } Generate this many digits on each row:
#7-1 One less than the length of group 7
Answered by DLosc on November 25, 2021
#define W printf("%*lldn",i,1ll*j*j)
g(i,j){i<17&&g(W,j*10+1);W;}D(){g(9,1);}
Answered by l4m2 on November 25, 2021
(Úv×H.F°ǝ=ÉÈNŸ=~ʒ€
₁˨Dûl`N₆rÇX³ΣJd‘×∞*Åv€rØ(0՜֤ΔNā—St€ô
Answered by Makonede on November 25, 2021
b=Math.abs,e="";for(i=0;i<17;i++){for(j=0;j<17;j++){z=9-(b(i-8)+b(j-8));e+=z>0?z:" "}e+="n"}console.log(e)
Answered by mekb on November 25, 2021
Ap<Fun<If<A<1>,Cat<Ap<Fun<Cat<Ap<Fun<If<A<1>,Cat<Ap<A<0>,Sub<A<1>,T>>,SP>,LF>>,Sub<I<9>,A<1>>>,Ap<Fun<If<lt<A<1>,A<2>>,Cat<Cat<A<1>,Ap<A<0>,Add<A<1>,T>,A<2>>>,A<1>>,A<1>>>,T,A<1>>>>,If<lt<A<1>,I<9>>,A<1>,Sub<I<18>,A<1>>>>,Ap<A<0>,Sub<A<1>,T>>>,LF>>,I<17>>
Has leading and trailing whitespace -- sorry! tch has no concept of "empty string" (at least not that I've found)
I doubt the ungolfed version would answer any questions (probably the opposite). I like to think of TCH as a lisp-like language with no functions, loops, or variables, so all the logic is done through recursive lambdas.
The basic structure:
lambda: (run lower lambdas with int 1,2,3...,17,18, join output)
lambda: (convert input, run lower lambdas, join output)
lambda: (int -> string of spaces & newline)
lambda: (int -> string of numbers)
Answered by Zack C. on November 25, 2021
main=mapM putStrLn[(' '<$[n..8])++(s n>>=show)|n<-s 9]
s n=[1..n-1]++[n,n-1..1]
Answered by Donat on November 25, 2021
Answered by MarcMush on November 25, 2021
Answered by lyxal on November 25, 2021
for i=-8,8 do x=9-math.abs(i)n=math.ceil(10^x-1)//9print((" "):rep(9-x)..n*n)end
Answered by Donat on November 25, 2021
eval s+={1..9}';<<<${(l:8:)s%?}`rev<<<$s`;'>f;{<f;tac f}|uniq
eval s+={1..9}';<<<${(l:8:)s%?}`rev<<<$s`;'>f;{<f;tac f}|uniq
eval {1..9}' ;' # evaluate this 9 times
s+= ; # append the number to s
<<< # print
${ s } # s
%? # with the last character removed
(l:8:) # padded to 8 spaces
`rev<<<$s` # then s, reversed
>f; # all output to the file f
<f; # print f
tac f # print f in reverse
{ }|uniq # remove the duplicated line in the middle
```
Answered by pxeger on November 25, 2021
9╒ñmÆ╒ñyFΩn
Explanation:
9╒ # Push a list in the range [1,9]
ñ # Palindromize it: [1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1]
m # Map over each inner integer,
Æ # using the following five character as inner code-block:
╒ # Convert the integer to a list in the range [1,n]
ñ # Palindromize it similar as before
y # Join the list together to a string
Ω # Prepend/append potential leading/trailing spaces (centralize)
F # to make the string length 17
n # After the map: join the strings in the list by newlines
# (after which the entire stack is output implicitly as result)
Answered by Kevin Cruijssen on November 25, 2021
-5 bytes thanks to @ceilingcat
#define f(x,y);for(j=0;j++<(i<9?x:y);)printf(
j;D(i){for(i=0;++i<19;puts("")){f(9-i,i-9)" ")f(i,18-i)"%d",j)f(i-1,17-i)"%d",i<9?i-j:18-i-j);}}
This code first prints a certain amount of spaces and then the numbers.
i,j;D(){for(;++i<19;){for(j=0;++j<19;i<10?(i+j>9&&j-i<9?printf("%d",j<9?i+j-9:9-j+i):printf(" ")):i-j<9&&i+j<27?printf("%d",j<9?j-i+9:27-i-j):printf(" "));puts("");}}
This code always chooses whether to print a space or a number, depending on the values of i
and j
.
Answered by Sheik Yerbouti on November 25, 2021
interface A{static void main(String[]a){f(i->{var o=System.out;f(j->o.print(i+j>8?" ":""+(9-i-j)));o.println();});}static void f(java.util.function.IntConsumer c){java.util.stream.IntStream.range(-8,9).map(Math::abs).forEach(c);}}
Readable:
interface A {
static void main(String[] a) {
f(i -> {
var o = System.out;
f(j -> o.print(i + j > 8 ? " " : "" + (9 - i - j)));
o.println();
});
}
static void f(java.util.function.IntConsumer c) {
java.util.stream.IntStream.range(-8, 9).map(Math::abs).forEach(c);
}
}
Answered by user100443 on November 25, 2021
saved another 3 bytes by letting the int
function crash instead of a loop condition. Thanks to dingledooper.
i=8
while[print(f'{int("1"*(9-abs(i)))**2:^17}')]:i-=1
Python 3, 57 bytes
saved 1 byte by using f-Strings thanks to dingledooper.
i=8
while i+9:print(f'{int("1"*(9-abs(i)))**2:^17}');i-=1
Python 3, 58 bytes
Even shorter solution by a different approach (prints one extra space at the beginning of each line).
i=8
while i+9:j=abs(i);i-=1;print(' '*j,int('1'*(9-j))**2)
Python 3, 61 bytes (without extra spaces)
i=8
while i+9:j=9-abs(i);i-=1;print(f'%{8+j}d'%int('1'*j)**2)
These are my previous solutions:
Python 3, 66 bytes
f=lambda c:f'%{8+c}d'%int('1'*c)**2
for c in f(9):print(f(int(c)))
Python 3, 71 bytes:
f=lambda c:str(int('1'*int(c))**2)
for c in f(9):print(f(c).center(17))
Answered by Donat on November 25, 2021
k=[]
for t in range(10):
l=str(111111111**2)[:t]
k.append(l.rjust(9)+l[:-1][::-1])
print("n".join(k+k[:-1][::-1]))
Answered by Lebster on November 25, 2021
for(z of(s=z=>"".padEnd(9-z)+(BigInt(10**z)/9n)**2n)(9))console.log(s(z))
Answered by Donat on November 25, 2021
(defn s[n](concat(range 1 n)(range n 0 -1)))(print(apply str(mapcat #(concat(repeat(- 9 %)" ")(s %)'("n"))(s 9))))
Shortened from 127 to 121 to 115.
Answered by Donat on November 25, 2021
Inspired by @BradC's answer
DECLARE @ INT=8a:PRINT
space(abs(@))+stuff('12345678987654321',9-abs(@),abs(@)*2,'')SET
@-=1IF~@<8GOTO a
Answered by t-clausen.dk on November 25, 2021
(run! #(println(reduce str "" %))(map (fn[i](map #(let[x(- (if(> % 9)(- 9(- % 9))%)(- 9 i))](if(pos? x)x " "))(range 1 18)))(concat(range 1 10)(range 8 0 -1))))
Answered by colinkahn on November 25, 2021
for(a=9;b=--a>0?9-a:9+a;print(s))for(s='',c=9;--c+b;)s+=c<0?b+c:c<b?b-c:' '
Answered by Donat on November 25, 2021
for(b of x="12345678987654321")print(b-9?"".padEnd(9-b)+"1".repeat(b)**2:x)
Doing the calculations 1**2, 11**2, 111**2, ...
This solution fixes the precision problem. It correctly produces a 1
at the end of the longest line instead of 0
. I think, this one is the clearest of the short solutions for JavaScript.
Instead of x="12345678987654321"
you could also write x=111111111**2/10+"1"
which is equally short.
Answered by Donat on November 25, 2021
f=(i=[...Array(17)].map((x,i)=>i<8?i:i-2*(i-8)))=>i.map(x=>i.map(y=>x+y>7?(x+y-7):' ').join``).join`n`
I haven't looked at the other answers up until this point, and just started out with this spreadsheet. Just saw that this answer isn't too bad of a golf compared to the other Javascript answers.
I tried to be clever coming up with something that generates a particular array (i
) that I use for the x and y-axis. But it turns out, spelling out that array is shorter.
f=(i=[0,1,2,3,4,5,6,7,8,7,6,5,4,3,2,1,0])=>i.map(x=>i.map(y=>x+y>7?(x+y-7):' ').join``).join`n`
Update. Spelling out the array differently, but I'm sure that I can golf this further
f=(i=[...'01234567876543210'])=>i.map(x=>i.map(y=>1*x+1*y>7?(1*x+1*y-7):' ').join``).join`n`
Last update for tonight:
f=(i=[...'01234567876543210'])=>i.map(x=>i.map(y=>+x+1*y>7?+x+1*y-7:' ').join``).join`n`
Getting rid of one more byte:
f=(i=[...'0'+10*11111111**2])=>i.map(x=>i.map(y=>+x+1*y>7?+x+1*y-7:' ').join``).join`n`
And one more:
f=(i=[0,...11111111**2+'0'])=>i.map(x=>i.map(y=>+x+1*y>7?+x+1*y-7:' ').join``).join`n`
Answered by Christiaan Westerbeek on November 25, 2021
interface A{static void main(String[]v){for(long m=0,a=0;++a<18;System.out.printf("%"+(a>9?26-a:8+a)+"d%n",m*m))m=a>9?m/10:m*10+1;}}
This is a different way to do it than my first answer for Java. It is using integer arithmetics. It is even shorter, maybe the shortest possible.
Formatted version of this code:
interface A {
static void main(String[] v) {
for (long m = 0, a = 0; ++a < 18; System.out.printf("%" + (a > 9 ? 26 - a : 8 + a) + "d%n", m * m))
m = a > 9 ? m / 10 : m * 10 + 1;
}
}
Or more readable:
class A {
public static void main(String[] v) {
for (long m = 0, a = 0; ++a < 18; ) {
long width = a > 9 ? 26 - a : 8 + a;
m = a > 9 ? m / 10 : m * 10 + 1;
System.out.printf("%" + width + "d%n", m * m);
}
}
}
Answered by Donat on November 25, 2021
avdqvdmffffffffqvvviifavvfblffffffflfifdflavvfbfffffflfififdfdflavvfbffffflfifififdfdfdflavvfbfffflfififififdfdfdfdflavvfbffflfifififififdfdfdfdfdflavvfbfflfififififififdfdfdfdfdfdflavvfbflfifififififififdfdfdfdfdfdfdfavvfbfififififififififdfdfdfdfdfdfdfdflavvfbflfifififififififdfdfdfdfdfdfdflavvfbfflfififififififdfdfdfdfdfdflavvfbffflfifififififdfdfdfdfdflavvfbfffflfififififdfdfdfdflavvfbffffflfifififdfdfdflavvfbfffffflfififdfdflavvfbffffffflfifdflavvfbfffffffflf
Super simple, we just create a space and the number 1, then every line just increment and print then decrement and print
Answered by Lebster on November 25, 2021
s/-//,say$"x$_.(1x(9-$_))**2for-8..8
Using 11 * 11 = 121, 111 * 111 = 12321, 1111 * 1111 = 1234321, ...
Answered by Donat on November 25, 2021
x=' 12345678987654321 '
do n=1 to 17
m=9-abs(9-n)
say substr(x,m,10)right(x,m)
end
Complete program. No real tricks used except some smooshing and keeping to a single loop. I'm assuming EOL doesn't count.
Answered by Turophile on November 25, 2021
interface A{static void main(String[]v){for(int x,a=-9;++a<9;System.out.printf("%9s%s%n","123456789".substring(0,9-x),"87654321".substring(x)))x=a>0?a:-a;}}
Formatted version of this solution:
interface A {
static void main(String[] v) {
for (int x, a = -9; ++a < 9; System.out.printf("%9s%s%n", "123456789".substring(0, 9 - x), "87654321".substring(x)))
x = a > 0 ? a : -a;
}
}
Java code is generally longer. This is my shortest solution so far.
It does not produce additional whitespace in the right side as another solution does, but it is a little bit longer.
Answered by Donat on November 25, 2021
/~/////;/3&~|/*#~*/5432~&/2^~^/#!~%/$56~$/1234~#/1
~@/ ~!/@@/!!^@ 1&@12; $;$|@ %|@%76| %7876|%789876| %7876|@%76|@ %54;$54; $;@12;@ 1&!#
Answered by nph on November 25, 2021
Answered by Denis Ibaev on November 25, 2021
interface A{static void main(String[]a){var o=System.out;for(int i=-9,j,k;++i<9;o.println())for(j=-9;++j<9;)o.print((k=(i<0?-i:i)+(j<0?-j:j))>8?" ":9-k);}}
-7 chars thanks to a kind commenter.
Answered by Matthew Anderson on November 25, 2021
for(int i=1,j=1;i>0;i+=j=i>8?-1:j)Write($"{"123456789".Substring(0,i),9}"+"87654321n".Substring(9-i));
Definitely not the shortest answer, and this interpreter was published after the question was posted. But I did not see a C# answer. When using the regular C# compiler, the print statement is much longer: System.Console.Write
. Also, string interpolation was not a thing when this question was posted.
Answered by dana on November 25, 2021
time {puts [string repe { } [expr abs([incr i]-9)]][expr [string repe 1 [expr 9-abs($i-9)]]**2]} 17
Answered by david on November 25, 2021
Saved many bytes thanks to ETHProductions
[...s="12345678987654321"].map(x=>"".padEnd(9-x)+s.slice(0,x-1)+s.slice(-x)).join`
`
Answered by Oliver on November 25, 2021
1..9+8..1|%{' '*(9-$_)+-join(1..$_+$_..1|gu)}
2 solutions with 44 bytes were proposed in the comments to the Iszi's post
Answered by mazzy on November 25, 2021
x,c,i=1,j;main(){for(;i<20;){x=10;for(j=1;j<20;){j++<10?x--:x++;printf(x>c?" ":"%d",x);}i++<10?c++:c--;printf("n");}}
My very first code golf! I still need to get into the golfing mindset, I know there is probably a lot I can do differently.
Edit: Try it online!
Answered by J.Barber on November 25, 2021
Answered by Giuseppe on November 25, 2021
9Zv-9Zvq!-t0>48*+c
9Zv
- symmetric range from [1:9 8:-1:1]
-9Zv
- reverse symmteric range, [9:-1:1 2:9]
q!
- decrement that to [8:-1:0 1:8] and transpose to vertical
-
- broadcast subtract - matrix of each value in the second range subtracted from each value in the first range
t0>
- duplicate that and get a logical matrix of 1s where it's > 0, 0s elsewhere
48*
- multiply by 48 to change 1s to 48s (ASCII '0')
+
- add that to the original matrix
c
- convert to char and implicitly display
Answered by sundar - Remember Monica on November 25, 2021
++++++++[->+>++++>+>++++++<<<<]>>>++<<+[-[-<+>>.<]<[->+<]>>>>+>[->+<<.+>]>+[-<+<.->>]<<<.<<]>>>>-[<<<<+[-<+>>.<]<[->+<]>>>>>[->+<<+.>]>-[-<+<-.>>]<<-<.>>]
[spaceMem, spaceCount, space, lf, "0", numCount, numMem]
++++++++[->+>++++>+>++++++<<<<]>>>++<<+
[ for spaceCount
-[- for spaceCount minus 1
<+ inc spaceMem
>>. print space
< go to spaceCount
]
<[->+<]> fetch spaceCount from spaceMem
>>>+ inc number
>[- for numCount
>+ inc numMem
<<.+ print and inc number
> go to numCount
]
>+[- for numMem plus 1
<+ inc numCount
<.- print and decrement number
>> go to numMem
]
<<<. print lf
<< go to spaceCount
]
>>>>-[ for numCount
<<<<+[- for spaceCount plus 1
<+ inc spaceMem
>>. print space
< go to spaceCount
]
<[->+<]> fetch spaceCount from spaceMem
>>> inc number
>[- for numCount
>+ inc numMem
<<+. print and inc number
> go to numCount
]
>-[- for numMem minus 1
<+ inc numCount
<-. print and decrement number
>> go to numMem
]
<<- decrement number
<. print lf
>> go to numCount
]
Answered by Dorian on November 25, 2021
-R
, 11 bytes9õ_õ ¬êÃê û
9õZ{Zõ q ê} ê û
9õZ{ [1..9].map(Z=>...)
Zõ [1..Z]
q Join with nothing; ["1", "12", ..., "123...9"]
ê Make palindrome; ["1", "121", ..., "123...9...321"]
}
ê Make palindrome on the array
û Center-pad each element to the longest one
`-R` joins with newline
implicit output
I like the õ_õ
emoji.
Answered by Bubbler on November 25, 2021
9{R⇵]↶┼
Explanation:
9{R⇵]↶┼
9{ ] map over i = 1..9
R push a range 1..i
⇵ and reverse that array
in Canvas, an array of arrays is a list of lines,
and the inner arrays are joined together
↶ rotate anti-clockwise
┼ and quad-palindromize with 1 overlap
I've just fixed a couple built-ins to make a 6 byte version possible:
9{R]/┼
9{R]/┼
9{ ] map over 1..9
R create a range 1..i
/ pad with a diagonal of spaces
┼ and quad-palindromize
Answered by dzaima on November 25, 2021
fun d(){for(i in 0..307){val v=Math.abs(i%18-9)+Math.abs(i/18-8)
print(if(i%18!=0)if(v>8)' '
else(57-v).toChar()
else 'n')}}
Answered by JohnWells on November 25, 2021
Answered by recursive on November 25, 2021
Print@Join=>Table[{If[_%9=_,9-_,sp]}@`+,Abs!-8:8]
Simply tables (that is, applies a function like a multiplication table) the function which adds two numbers (from [8, 7, 6, 5, ..., 5, 6, 7, 8]
), checks if they are less than 9, then yields 9 - that number
if so, otherwise a space. Then, prints each row accordingly.
Answered by Conor O'Brien on November 25, 2021
/(/# '87#//'/"67//&/123//%/43!//$/ //#/654321
//"/&45//!/21
$ /$$$$1
$$$ 1!$ &!$&% "%"#$'('8987($'65%"65% "%$&%$ &!$$1!$$ 1
Shorter than this answer by 109 bytes! Just applies a bunch of substitutions with whitespace and common numbers.
Answered by Conor O'Brien on November 25, 2021
Answered by hakr14 on November 25, 2021
z="123456789"
for i in range(9)+range(8)[::-1]:print"% 8s"%z[:i]+z[i::-1]
Answered by ShadowCat on November 25, 2021
DECLARE @ INT=8,@d INT=-1a:PRINT SPACE(@)+STUFF('12345678987654321',9-@,2*@,'')IF @=0SET @d=1SET @+=@d If @<9GOTO a
Pure procedural counter and loop, not very "SQL"-like, but the best I could come up with using what SQL offers. Formatted:
DECLARE @ INT=8, @d INT=-1
a:
PRINT SPACE(@)+STUFF('12345678987654321',9-@,2*@,'')
IF @=0 SET @d=1
SET @+=@d
If @<9 GOTO a
Cuts a length out of a hard-coded string using STUFF
. Would work just as easily with any other set of characters.
Answered by BradC on November 25, 2021
Answered by Erik the Outgolfer on November 25, 2021
/T/123//F/T45//f/4321//S/ //s/S //N/
s//a/F678//b/765f//A/1Ns 121Ns/ssSAT21NSTfN FfNF65f
SF6b
ab
a98b
ab
SF6bNF65fN FfNSTfNsT2AS1
Answered by Erik the Outgolfer on November 25, 2021
Anonymous function that takes no input and outputs to STDOUT.
For i=-8To 8
For j=-8To 9
k=Abs(i)+Abs(j)
If k>8Then?" ";
Else?Chr$(57-k);
Fi
Next
?
Next
Answered by Taylor Raine on November 25, 2021
Answered by ngn on November 25, 2021
9ŒḄr1z⁶ṚŒḄY
Done alongside caird coinheringaahing in chat.
9ŒḄr1z⁶ṚŒḄY - Full program. 9ŒḄ - The list [1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1]. r1 - Generate [N, N-1, ..., 1] for each N in ^. z⁶ - Zip; transpose ^ with filler spaces. Ṛ - Reverse. ŒḄ - Palindromize without vectorization. Y - Join by newlines.
Saved 6 bytes thanks to Leaky Nun!
Answered by Mr. Xcoder on November 25, 2021
{pB9'P+*" "- 9}J""WpB}
{pB9'P+*" "- 9}J""WpB}
{ - For each
p - palindromize [1,2,..9,..1]
B9 - range [1,2...9]
' - Iteration command begin
P - Print
+ - concatenate
*" "- 9 } - appropriate number of spaces
J""WpB} - obtain number string
J"" - Join with nothing '123454321'
W - map each element as string ['1','2'..'5','2','1']
p - palindromize [1,2,..5,..2,1]
B} - range [1,2,3,4,5]
Answered by officialaimm on November 25, 2021
9┅…ṫ¦€|ṫṣ
9┅ Push [1 2 3 4 5 6 7 8 9]
… Prefixes; push [[1] [1 2] [1 2 3] ... [1 2 3 4 5 6 7 8 9]]
ṫ¦ Palindromize each row: e.g. [1 2 3 4] -> [1 2 3 4 3 2 1]
€| Centre-align the rows, padding with spaces
ṫ Palindromize the rows
ṣ Join with newlines
Answered by Business Cat on November 25, 2021
Answered by Koishore Roy on November 25, 2021
for($y=17;$y--;print"
")for($x=17;$x--;)echo($d=9-abs($x-8)-abs($y-8))>0?$d:" ";
run in command line
php -r "CODE_ABOVE"
18 bytes saved by Jörg Hülsermann
Answered by Евгений Новиков on November 25, 2021
Answered by zgrep on November 25, 2021
x=abs(-8:8);m=x+x';m(m>8)=25;[57-m,'']
To make it work in MATLAB too, you'd need to write x=ndgrid(abs(-8:8));m=x+x';m(m>8)=25;[57-m,'']
or x=meshgrid(abs(-8:8));m=x+x';m(m>8)=25;[57-m,'']
Answered by flawr on November 25, 2021
z=@cellfun;
C=z(@(a,b,c)[a b c fliplr([a b])],[mat2cell(repelem(' ',36),1,8:-1:1),{''}],[{''},mat2cell(nonzeros(tril(repmat(49:56,8,1))')',1,1:8)],num2cell(49:57),'un',0)';
z(@(c)disp(c),[C;flipud(C(1:end-1))])
Answered by EBH on November 25, 2021
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
123456787654321
1234567654321
12345654321
123454321
1234321
12321
121
1
Yay.
Answered by sporklpony on November 25, 2021
iisiisddddooooooooiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddoddddsddddoooooooiiiiiiiiiiiiiiiiioiododddddddddddddddddddddddddddddddddddddddoddddsddddooooooiiiiiiiiiiiiiiiiioioiodododddddddddddddddddddddddddddddddddddddddoddddsddddoooooiiiiiiiiiiiiiiiiioioioiododododddddddddddddddddddddddddddddddddddddddoddddsddddooooiiiiiiiiiiiiiiiiioioioioiodododododddddddddddddddddddddddddddddddddddddddoddddsddddoooiiiiiiiiiiiiiiiiioioioioioiododododododddddddddddddddddddddddddddddddddddddddoddddsddddooiiiiiiiiiiiiiiiiioioioioioioiodododododododddddddddddddddddddddddddddddddddddddddoddddsddddoiiiiiiiiiiiiiiiiioioioioioioioiododododododododddddddddddddddddddddddddddddddddddddddodddsoioioioioioioioiodododododododododddddddddddddddddddddddddddddddddddddddoddddsddddoiiiiiiiiiiiiiiiiioioioioioioioiododododododododddddddddddddddddddddddddddddddddddddddoddddsddddooiiiiiiiiiiiiiiiiioioioioioioiodododododododddddddddddddddddddddddddddddddddddddddoddddsddddoooiiiiiiiiiiiiiiiiioioioioioiododododododddddddddddddddddddddddddddddddddddddddoddddsddddooooiiiiiiiiiiiiiiiiioioioioiodododododddddddddddddddddddddddddddddddddddddddoddddsddddoooooiiiiiiiiiiiiiiiiioioioiododododddddddddddddddddddddddddddddddddddddddoddddsddddooooooiiiiiiiiiiiiiiiiioioiodododddddddddddddddddddddddddddddddddddddddoddddsddddoooooooiiiiiiiiiiiiiiiiioiododddddddddddddddddddddddddddddddddddddddoddddsddddooooooooiiiiiiiiiiiiiiiiiodddddddddddddddddddddddddddddddddddddddo
A more human friendly spaced version:
iisiisdddd oooooooo iiiiiiiiiiiiiiiii o dddddddddddddddddddddddddddddddddddddddo
ddddsdddd ooooooo iiiiiiiiiiiiiiiii oiodo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd oooooo iiiiiiiiiiiiiiiii oioiododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd ooooo iiiiiiiiiiiiiiiii oioioiodododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd oooo iiiiiiiiiiiiiiiii oioioioiododododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd ooo iiiiiiiiiiiiiiiii oioioioioiodododododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd oo iiiiiiiiiiiiiiiii oioioioioioiododododododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd o iiiiiiiiiiiiiiiii oioioioioioioiodododododododo dddddddddddddddddddddddddddddddddddddddo
ddds oioioioioioioioiododododododododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd o iiiiiiiiiiiiiiiii oioioioioioioiodododododododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd oo iiiiiiiiiiiiiiiii oioioioioioiododododododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd ooo iiiiiiiiiiiiiiiii oioioioioiodododododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd oooo iiiiiiiiiiiiiiiii oioioioiododododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd ooooo iiiiiiiiiiiiiiiii oioioiodododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd oooooo iiiiiiiiiiiiiiiii oioiododo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd ooooooo iiiiiiiiiiiiiiiii oiodo dddddddddddddddddddddddddddddddddddddddo
ddddsdddd oooooooo iiiiiiiiiiiiiiiii o dddddddddddddddddddddddddddddddddddddddo
Answered by Uriel on November 25, 2021
((1..9)+(8..1)).any{println' '*(9-it)+('1'*it as int)**2}
old version:
((1..9)+(8..1)).any{println"${('1'*it as int)**2}".center(17)}
explanation: we create a list [1,2,...,9,8,7,..,1]. Within the closure we create strings '1', '11', '111,..., convert them to numbers, run power of two and center.
Answered by Matias Bjarland on November 25, 2021
(do((b 1)(l'(1 2 3 4 5 6 7 8 9))(i 1(+ i b)))((= i 0))(format t"~17:@<~v{~a~}~v{~a~}~>~%"i l i(reverse(subseq l 0(1- i))))(if(> i 8)(setf b -1)))
It is worse than the other Common Lisp solution, but it works and I think it is different enough to be posted.
i
is incremented up to 9 and then decremented to 0 (when i=9
sign of b
is changed effectively changing addition to subtraction - this avoids second loop.
In each line I print numbers: `123...i(i-1)...1 using loops of format function (for first loop I use list '(1 2 3 4 5 6 7 8 9) and for decrementing loop I use reversed subsequence of this list. Text is then centered.
I didn't notice that numbers are squares of 11..11
. As far as this solution is concerned the diamond could be made out of letters or (! @ # ...) (for that you would need to change ~a
to ~c
in format function.
Answered by user65167 on November 25, 2021
#(loop[[r & s](range 18)h 1](print(apply str(repeat(if(< r 8)(- 8 r)(- r 8)) )))(doseq[m(concat(range 1 h)(range h 0 -1))](print m))(println)(if s(recur s((if(< r 8)inc dec)h))))
-12 bytes by changing the outer doseq
to a loop
, which allowed me to get rid of the atom
(yay).
A double "for-loop". The outer loop (loop
) goes over each row, while the inner loop (doseq
) goes over each number in the row, which is in the range (concat (range 1 n) (range n 0 -1))
, where n
is the highest number in the row.
(defn diamond []
(let [spaces #(apply str (repeat % " "))] ; Shortcut function that produces % many spaces
(loop [[row-n & r-rows] (range 18) ; Deconstruct the row number from the range
high-n 1] ; Keep track of the highest number that should appear in the row
(let [top? (< row-n 8) ; Are we on the top of the diamond?
f (if top? inc dec) ; Decided if we should increment or decrement
n-spaces (if top? (- 8 row-n) (- row-n 8))] ; Calculate how many prefix-spaces to print
(print (spaces n-spaces)) ; Print prefix-spaces
(doseq [m (concat (range 1 high-n) (range high-n 0 -1))] ; Loop over the row of numbers
(print m)) ; Print the number
(println)
(if r-rows
(recur r-rows (f high-n)))))))
Due to a bug in the logic in my first attempt (accidentally inserting the prefix-spaces between each number instead), I managed to get this:
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
12345678987654321
1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 3 2 1
1 2 3 2 1
1 2 1
Not even correct ignoring the obvious bug, but it looked cool.
Answered by Carcigenicate on November 25, 2021
proc P i {puts [format %[expr 8+$i]s [expr [string repe 1 $i]**2]]}
time {P [incr i]} 9
time {P [incr i -1]} 8
Answered by sergiol on November 25, 2021
FOR I=-8TO 8A=ABS(I)Q=VAL("1"*(9-A))?" "*A;Q*Q
NEXT
LOCATE 16,8?1
I used the fact that 11*11=121
, 111*111=12321
, etc. Unfortunately, 12345678987654321
can't be stored as a 64 bit float, so I had to add the last 1
separately, adding 14 bytes.
Answered by 12Me21 on November 25, 2021
Anonymous VBE immediate window function that takes no input and outputs to the VBE Immediate Window
For i=-8To 8:j=Abs(i):r=Mid(987654321,j+1):?Spc(j)StrReverse(r)Mid(r,2):Next
For i=-9To 8:For j=-8To 9:k=Abs(i)+Abs(j):l=l &IIf(k>8," ",9-k):Next:?l:l="":Next
Answered by Taylor Raine on November 25, 2021
Thanks to @DJMcMayhem for saving a ton of bytes
Thanks to @AaronMiller for saving 4 bytes by generating 12345678987654321
in a different way
9i1<ESC>|C<C-r>=<C-r>"*<C-r>"
<ESC>qqYP9|xxI <ESC>YGpHq7@q
9i1<ESC> Write 9 '1's, leaving the cursor at the end of the line
|C Go to the first column and cut all that's to the right of the cursor (implictly into register "), entering insert mode
<C-r>= Enter an expression:
<C-r>"*<C-r>" The contents of register " multiplied with itself
<CR> Evaluate it, yielding 12345678987654321
qq Start recording into register q
YP Yank this entire line and Paste above
9| Go to the 9th column
xx Delete character under cursor twice
I <ESC> Go to the beginning of the line and insert a space and enter normal mode
Y Yank this entire line
G Go to the last line
p Paste in the line below
H Go to the first line
q End recording
7@q Repeat this 7 times
Answered by user41805 on November 25, 2021
(⍉⊢⍪1↓⊖)⍣2⌽↑,⍨1↓⎕d
⎕d
are the digits '0123456789'
1↓
drop the first ('0'
)
,⍨
swapped catenate scan, i.e. the reversed prefixes '1' '21' '321' ... '987654321'
↑
mix into a matrix padded with spaces:
1
21
321
...
987654321
⌽
reverse the matrix horizontally
(
...)⍣2
do this twice:
⍉⊢⍪1↓⊖
the transposition (⍉
) of the matrix itself (⊢
) concatenated vertically (⍪
) with the vertically inverted matrix (⊖
) without its first row (1↓
)
Answered by ngn on November 25, 2021
puts (-8..8).map{|i|[?s*a=i.abs,(?1*(9-a)).to_i**2]*''}
Output:
irb(main):342:0> puts (-8..8).map{|i|[?s*a=i.abs,(?1*(9-a)).to_i**2]*''}
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
123456787654321
1234567654321
12345654321
123454321
1234321
12321
121
1
Answered by Vasu Adari on November 25, 2021
My first code golf :)
a="";function b(c){a+=" ".repeat(10-c);for(i=1;i<c;i++)a+=i;for(i=2;i<c;i++)a+=c-i;a+="n";}for(i=2;i<11;i++)b(i);for(i=9;i>1;i--)b(i);document.write("<pre>"+a+"</pre>");
var str = "";
function row(line) {
str += " ".repeat(10 - line);
for (var i = 1; i < line; i++) {
str += i;
}
for (var i = 2; i < line; i++) {
str += line - i;
}
str += "n";
}
for (var line = 2; line < 11; line++) {
row(line);
}
for (var line = 9; line > 1; line--) {
row(line);
}
document.write("<pre>" + str + "</pre>");
Answered by Cr4xy on November 25, 2021
(-8..8).map{|i|puts' '*i.abs+"#{eval [?1*(9-i.abs)]*2*?*}"}
Answered by G B on November 25, 2021
9:v:<,+55<v5*88<v-9:$_68v
> v> ^>3p2vpv -1<! *
, 1^ 2p45*3+9<4: ,: +
g -^_75g94+4pg7^! +^ ,<
1 : ^ `0 :-1$_:68*^$
^1_$:55+-0>:#$1-#$:_^
It could definitely be golfed more, but it's my first Funge program and my head already hurts. Had a lot of fun, though
Answered by Leo on November 25, 2021
r=[-8..8]
f n|n<1=" "|1>0=show n
mapM putStrLn[[9-abs x-abs y|x<-r]>>=f|y<-r]
Answered by Angs on November 25, 2021
Answered by Oliver Ni on November 25, 2021
F⁹«GX⁻⁹ιI⁺ι¹↓
Draws nine, successively smaller, concentric number-diamonds on top of each other:
F⁹« Loop ι from 0 to 8:
GX Draw a (filled) polygon with four equilateral diagonal sides
⁻⁹ι of length 9-ι
I⁺ι¹ using str(ι+1) as the character
↓ Move down one space before drawing the next one
Answered by DLosc on November 25, 2021
87:
q()(printf %$[9+$1%9]s\n $[$2*$2];[ 7 -lt $1 ]||(q $[$1+1] ${2}1;q $[$1+9] $2))
q 0 1
As it usually goes, changing from iterative to recursive solution helps us win additional bytes.
Meaning of parameters to q:
$1 How much to remove from 8 to get the number of spaces in the beginning. Note value modulo 9 counts here (actual value is also a hint to quit recursion).
$2 The current chain of 1s to be squared and output by printf.
The modus operandi is:
(if not yet at 12..9..21 - the recursive step)
2.1. output the next sequence (here: 111111 > $2 , output 12345654321
2.2. output the sequence once again (123454321).
In the step 2.2 , we pass (indent value + 9) instead of indent value however, so that the algoritm "knows" we are printing the row for the second time. Without this, the [ 7 -lt $1 ]
would be false, causing us to retrigger the recursive step 1. This would never finish then.
The recursion goes like this:
q 0 1: 1
q 1 11: 121
q 2 111: 12321
q 3 1111: 1234321
q 4 11111: 123454321
q 5 111111: 12345654321
q 6 1111111: 1234567654321
q 7 11111111: 123456787654321
q 8 111111111: 12345678987654321
q 16 11111111: 123456787654321
q 15 1111111: 1234567654321
q 14 111111: 12345654321
q 13 11111: 123454321
q 12 1111: 1234321
q 11 111: 12321
q 10 11: 121
q 9 1: 1
p()(printf "%$[8+i]sn" $[k*k])
k=;for i in `seq 9`;do k+=1;p;done;for i in `seq 8 -1 1`;do k=${k:1};p;done;
"k+=1" is much cheaper as k=$[10*k+1] , and for k being a string of ones it's the same. Same goes for ${k:1} and $[k/10] .
126:
p() (printf "%$[$1+i]sn" $[k*k];)
k=1;for i in `seq 8`;do p 8;k=$[10*k+1];done;for i in `seq 8 -1 0`;do p 9;k=$[k/10];done;
I guess there may be even shorter solution, but weather is glorious, I can't stand sitting in front of computer any more :).
Answered by pawel.boczarski on November 25, 2021
CJam is a lot newer than this challenge, so this answer is not eligible for being accepted. This was a neat little Saturday evening challenge, though. ;)
8S*9,:)+9*9/2%{_W%1>+z}2*N*
The idea is to form the upper left quadrant first. Here is how that works:
First, form the string " 123456789"
, using 8S*9,:)+
. This string is 17 characters long. Now we repeat the string 9 times, and then split it into substrings of length 9 with 9/
. The mismatch between 9 and 17 will offset every other row one character to the left. Printing each substring on its own line we get:
1
23456789
12
3456789
123
456789
1234
56789
12345
6789
123456
789
1234567
89
12345678
9
123456789
So if we just drop every other row (which conveniently works by doing 2%
), we obtain one quadrant as desired:
1
12
123
1234
12345
123456
1234567
12345678
123456789
Finally, we mirror this twice, transposing the grid in between to ensure that the two mirroring operations go along different axes. The mirroring itself is just
_ "Duplicate all rows.";
W% "Reverse their order.";
1> "Discard the first row (the centre row).";
+ "Add the other rows.";
Lastly, we just join all lines with newlines, with N*
.
Answered by Martin Ender on November 25, 2021
=MAX(A2,B1,B3,C2)-1
(19 chars)0;
(2 chars)8.9
in J10 (3 char)Note: Some might call step 2 cheating as it creates 19 to 23 characters in every cell for a total of over 6000 chars. If you really want to count it that way, you would be better off not putting the formula into those squares that are to remain blank. In that case, you can use a 9
in J10 and you don't need the custom formatting. The total character count would then be just over 3000.
Answered by Wally on November 25, 2021
⍉⊃{⍕⍵↑⍨⍵>0}¨9-∘.+⍨|9-⍳17
Tested in Nars2000 and Dyalog (requires ⎕ML←3
in the latter.)
Explanation
⍳17 starting with the naturals up to 17
|9- generate the numbers from 8 to 0 and back to 8
∘.+⍨ make a table of their sum (with 0 in the middle)
9- turn it into a diamond with 9 in the middle
{ }¨ for each number
⍵↑⍨⍵>0 keep it only if it's positive
⍕ then convert the result, if any, to a string
⍉⊃ disclose the nested array and adjust the dimensions
The last step transposes the result, whose shape is 17 17 1 (because of the disclose ⊃
of nested strings) into 1 17 17, which gets printed like a plain 17 17.
Output
⍉⊃{⍕⍵↑⍨⍵>0}¨9-∘.+⍨|9-⍳17
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
123456787654321
1234567654321
12345654321
123454321
1234321
12321
121
1
Answered by Tobia on November 25, 2021
#include <iostream>
using std::cout;using std::size_t;int main(){for(int a=0;a<2;++a)for(size_t b=1+a*7;b<10-a;((a!=1)?++b:--b)){size_t c=9-b;for(;c-->0;)cout<<" ";for(c=1;c<b;)cout<<c++;for(c=b;0<c;)cout<<c--;cout<<'n';}}
Ungolfed:
#include <iostream>
using std::cout; //for not having to type std::cout over and over again
using std::size_t; //for not having to type std::size_t over and over again
int main()
{
for(int a = 0; a < 2; ++a)
for(size_t b=1+a*7; b<10-a; ((a!=1)?++b:--b))
{ //either count up to nine or down from nine
size_t c = 9-b; //space count we need
for(; c-- > 0;)
cout << " ";
for(c = 1; c < b;) //set c to the counter that will be print
cout << c++; //post-crement :)
for(c = b; 0 < c;) //count backwards
cout << c--; //post-decrement :)
cout << 'n'; //line is done
}
}
Answered by NaCl on November 25, 2021
,.(0&<#":)"+9-+/~|i:8
Thanks to FUZxxl for the "+
trick (I don't think I've ever used u"v
before, heh).
i:8 "steps" vector: _8 _7 _6 ... _1 0 1 ... 7 8
| magnitude
+/~ outer product using +
9- inverts the diamond so that 9 is in the center
( )"+ for each digit:
# copy
0&< if positive then 1 else 0
": copies of the string representation of the digit
(in other words: filter out the strictly positive
digits, implicitly padding with spaces)
,. ravel each item of the result of the above
(necessary because the result after `#` turns each
scalar digit into a vector string)
Answered by FireFly on November 25, 2021
1..8+9..1|%{' '*(9-$_)+[int64]($x='1'*$_)*$x}
1..9+8..1|%{' '*(9-$_)+[int64]($x='1'*$_)*$x}
Thanks to Strigoides for the hint to use 1^2,11^2,111^2...
Shaved some characters by:
- Eliminating
$w
.- Nested the definition of
$x
in place of its first use.- Took some clues from Rynant's solution:
- Combined the integer arrays with
+
instead of,
which allows elimination of the parenthesis around the arrays and a layer of nesting in the loops.- Used
9-$_
to calculate the length of spaces needed, instead of more complicated maths and object methods. This also eliminated the need for$y
.
Explanation:
1..8+9..1
or 1..9+8..1
generates an array of integers ascending from 1 to 9 then descending back to 1.
|%{
...}
pipes the integer array into a ForEach-Object
loop via the built-in alias %
.
' '*(9-$_)+
subtracts the current integer from 9, then creates a string of that many spaces at the start of the output for this line.
[int64]($x='1'*$_)*$x
defines $x
as a string of 1
s as long as the current integer is large. Then it's converted to int64 (required to properly output 1111111112 without using E notation) and squared.
Answered by Iszi on November 25, 2021
PowerShell, 49 48
1..9+8..1|%{" "*(9-$_)+(1..$_+($_-1)..0|?{$_})}
Answered by Rynant on November 25, 2021
r←{⍵,1↓⌽⍵}
{⎕←⍵,⍨' '⍴⍨(2×10-⌈/⍵)}¨r¨r⍳¨⍳9
I guess I'm not beating marinus. :p
Answered by protist on November 25, 2021
17,{8-abs' '*1`9*1$,>~.*n}/
or
17,{8-abs' '*.1`9*+9<~.*n}/
Both work by building a suitable repunit as a string and then converting to int and squaring to get a Demlo number.
Answered by Peter Taylor on November 25, 2021
for(i=9;--i+9;console.log(s))for(j=9;j;s=j--^9?k>0?k+s+k:" "+s:k+"")k=i<0?j+i:j-i
Answered by copy on November 25, 2021
for(i=9,a=Math.abs;--i>-9;console.log(o))for(j=9,o='';j-->-9;)o+=(n=9-a(i)-a(j))>0?n:' '
Answered by Shmiddty on November 25, 2021
Mathematica 55 50 45 41 38
(10^{9-Abs@Range[-8,8]}-1)^2/81//Grid
Grid[(10^Array[{9}-Abs[#-9]&,17]-1)^2/81]
Answered by chyanog on November 25, 2021
With recursion:
function p(l,n,s){for(i=l;i;s+=" ",i--);for(i=1;i<=n;s+=i++);for(i-=2;i>0;s+=i--);return(s+="n")+(l?p(l-1,n+1,"")+s:"")}alert(p(8,1,""))
First time on CG :)
If I can find a JS implementation that executes 111111111**2
with higher precision.
(Here: 12345678987654320).
a="1",o="n";for(i=0;i<9;i++,o+=" ".substr(i)+a*a+"n",a+="1");for(i=8;i;i--)o+=o.split("n")[i]+"n";alert(o)
Answered by Nippey on November 25, 2021
val a="543210/.-./012345";for(i<-a){for(j<-a;k=99-i-j)print(if(k<1)" "else k);println}
Answered by Rex Kerr on November 25, 2021
for n in`111111111**2`:print`int('1'*int(n))**2`.center(17)
Abuses backticks and repunits.
Answered by nneonneo on November 25, 2021
Answered by Konrad Borowski on November 25, 2021
My first entry on Codegolf!
for(l=n=1;l<18;n-=2*(++l>9)-1,console.log(s+z)){for(x=n,s="";x<9;x++)z=s+=" ";for(x=v=1;x<2*n;v-=2*(++x>n)-1)s+=v}
If this can be shortened any further, please comment :)
Answered by tomsmeding on November 25, 2021
v;main(i){for(;i<307;putchar(i++%18?v>8?32:57-v:10))v=abs(i%18-9)+abs(i/18-8);}
Answered by baby-rabbit on November 25, 2021
for i in map(int,str(int('1'*9)**2)):print' '*(9-i),int('1'*i)**2
Answered by cardboard_box on November 25, 2021
i=(-8..9);i.each{a->i.each{c=a.abs()+it.abs();print c>8?' ':9-c};println""}
old version:
(-8..9).each{a->(-8..9).each{c=a.abs()+it.abs();print c>8?' ':9-c};println""}
Answered by Marco Martinelli on November 25, 2021
for(i=1;i<18;i++){s="";a=Math.abs(9-i);for(j=0;j<a;j++)s+=" ";for(k=a+1;k<=9;k++)s+=k-a;for(l=8;l>a;l--)s+=l-a;console.log(s)}
Includes suggestion from Shmiddty in comments. Original preserved below:
for(i=1;i<18;i++){s="";a=Math.abs(9-i);for(j=0;j<a;j++){s+=" "}for(k=a+1;k<=9;k++){s+=k-a}for(l=8;l>a;l--){s+=l-a}console.log(s)}
I'm sure this could be condensed further, but darned if I know how. :P
Answered by joequincy on November 25, 2021
adding +1 for -E
which is required for say
say$"x(9-$_).(1x$_)**2for 1..9,reverse 1..8
edit: shortened a bit
Answered by chinese perl goth on November 25, 2021
for i=1 to 9:?string(27-i*3,32)l;:for j=1 to i:?j;:next:for j=i-1 to 1 step -1:?j;:next:?:next:for i=8 to 1 step -1:?string(27-i*3,32)l;:for j=1 to i:?j;:next:for j=i-1 to 1 step -1:?j;:next:?:next
if vba didn't automatically add a space for the + sign it doesn't print, perhaps I could avoid the 27-i*3
construct for making it look right
Answered by SeanC on November 25, 2021
-1'(-:'9+k,1_|k:!9)$,/'$b,1_||:'b:(-1_'a),'|:'a:1_1+!:'!10;
Answered by tmartin on November 25, 2021
public class A{public static void main(String[]v){
for(int a=-8,b,c;a<9;a++){
for(b=-8;b<9;){c=Math.abs(a)+Math.abs(b++);
System.out.print(c>8?" ":9-c);}System.out.println();}}}
correct formatting of this solution (352 chars):
public class A {
public void main(String[] args) {
for (int a = -8; a < 9; a++) {
for (int b = -8; b < 9;) {
int c = Math.abs(a) + Math.abs(b++);
System.out.print(c > 8 ? " " : 9 - c);
}
System.out.println("");
}
}
}
Answered by Martin Thoma on November 25, 2021
(-8..8).map{i=_1.abs;puts' '*i+"#{eval(?1*(9-i))**2}"}
(Thanks, Patrick, G B, and Slim Liser!)
Improvements welcome. :)
Answered by Mark Reed on November 25, 2021
For the records:
s=c(1:9,8:1);for(i in s)cat(rep(" ",9-i),s[0:i],s[(i-1):0],"n",sep="")
Answered by Paolo on November 25, 2021
l=9,n;p(i){for(i=18;i;putchar(i?n>l?48+n-l:32:10))n=9<--i?18-i:i;}
main(){p(l--);l&&p(main());l++;}
Answered by ugoren on November 25, 2021
(defun x(n)(if(= n 0)1(+(expt 10 n)(x(1- n)))))(dotimes(n 17)(format t"~17:@<~d~>~%"(expt(x(- 8(abs(- n 8))))2)))
First I noticed that the elements of the diamond could be expressed like so:
1 = 1 ^ 2
121 = 11 ^ 2
12321 = 111 ^ 2
etc.
x
recursively calculates the base (1, 11, 111, etc), which is squared, and then printed centered by format
. To make the numbers go up to the highest term and back down again I used (- 8 (abs (- n 8)))
to avoid a second loop
Answered by Strigoides on November 25, 2021
A⍪1↓⊖A←A,0 1↓⌽A←⌽↑⌽¨⍴∘(1↓⎕D)¨⍳9
If spaces separating the numbers are allowed (as in the Mathematica entry), it can be shortened to 28 26:
A⍪1↓⊖A←A,0 1↓⌽A←⌽↑⌽∘⍕∘⍳¨⍳9
Explanation:
⍳9
: a list of the numbers 1 to 91↓⎕D
: ⎕D
is the string '0123456789', 1↓
removes the first element⍴∘(1↓⎕D)¨⍳9
: for each element N of ⍳9
, take the first N elements from 1↓⎕D
. This gives a list: ["1", "12", "123", ... "123456789"] as strings⌽¨
: reverse each element of this list. ["1", "21", "321"...]
(Short program:)
⍳¨⍳9
: the list of 1 to N, for N [1..9]. This gives a list [[1], [1,2], [1,2,3] ... [1,2,3,4,5,6,7,8,9]] as numbers.⌽∘⍕∘
: the reverse of string representation of each of these lists. ["1", "2 1"...]A←⌽↑
: makes a matrix from the list of lists, padding on the right with spaces, and then reverse that. This gives the upper quadrant of the diamond. It is stored in A.A←A,0 1↑⌽A
: A, with the reverse of A minus its first column attached to the right. This gives the upper half of the rectangle. This is then stored in A again.A⍪1↓⊖A
: ⊖A
is A mirrored vertically (giving the lower half), 1↓
removes the top row of the lower half and A⍪
is the upper half on top of 1↓⊖A
.Answered by marinus on November 25, 2021
Added 1 char for the -p
switch.
Uses squared repunits to generate the sequence.
s//12345678987654321/;s|(.)|$/.$"x(9-$1).(1x$1)**2|eg
Answered by ardnew on November 25, 2021
Not clever:
s=str(111111111**2)
for i in map(int,s):print'%8s'%s[:i-1]+s[-i:]
Answered by Steven Rumbalski on November 25, 2021
Another GolfScript solution
17,{8-abs." "*10@-,1>.-1%1>n}%
Thank you to @PeterTaylor for another char.
Previos versions:
17,{8-abs" "*9,{)+}/9<.-1%1>+}%n*
17,{8-abs" "*9,{)+}/9<.-1%1>n}%
Answered by Howard on November 25, 2021
Print@@#&/@(Sum[k~DiamondMatrix~17,{k,0,8}]/.0->" ")
With 3 bytes saved thanks to Kelly Lowder.
Analysis
The principal part of the code, Sum[DiamondMatrix[k, 17], {k, 0, 8}]
, can be checked on WolframAlpha.
The following shows the underlying logic of the approach, on a smaller scale.
a = 0~DiamondMatrix~5;
b = 1~DiamondMatrix~5;
c = 2~DiamondMatrix~5;
d = a + b + c;
e = d /. 0 -> "";
Grid /@ {a, b, c, d, e}
Answered by DavidC on November 25, 2021
-1'(::;1_|:)@:((|!9)#'" "),'$i*i:"J"$(1+!9)#'"1";
Old method:
-1',/(::;1_|:)@:((|!9)#:" "),',/'+(::;1_'|:')@:i#:,/$i:1+!9;
Answered by skeevey on November 25, 2021
Assuming that this is meant as a code-golf challenge, here's a basic GolfScript solution:
9,.);-1%+:a{a{1$+7-.0>" "if}%;n}%
Answered by Ilmari Karonen on November 25, 2021
<?for($a=-8;$a<9;$a++){for($b=-8;$b<9;){$c=abs($a)+abs($b++);echo$c>8?" ":9-$c;}echo"n";}
Calculates and prints the Manhattan distance of the position from the centre. Prints a space if it's less than 1.
An anonymous user suggested the following improvement (84 characters):
<?for($a=-8;$a<9;$a++,print~õ)for($b=-8;$b<9;print$c>8?~ß:9-$c)$c=abs($a)+abs($b++);
Answered by Gareth on November 25, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP