(no, not those ones)
The Challenge
You'll be given two inputs. The first is a positive integer n > 0
, which is used to output an n x n
right triangle of the numbers 1, 2, 3, ... n
. This triangle starts in a corner and increases horizontally and vertically by one and diagonally by two. See examples below for clarification. Keep one space between columns and keep all numbers right-aligned in their particular columns. (This is ascii-art after all).
The second input, x
, is one of four distinct single ASCII characters of your choice that determines the triangle's starting corner (and hence orientation). For example, you could use 1,2,3,4
or a,b,c,d
or #,*,!,)
, etc. Please specify in your answer how the orientation works.
For clarification in this challenge, I will use 1,2,3,4
which will correspond to 1
for the upper-left, 2
for the upper-right, and so on clockwise.
The Examples
For example, for n = 5
, x = 1
output the following:
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
For input n = 11
, x = 1
output the following (note the extra spaces so the single digits are right-aligned):
1 2 3 4 5 6 7 8 9 10 11
2 3 4 5 6 7 8 9 10 11
3 4 5 6 7 8 9 10 11
4 5 6 7 8 9 10 11
5 6 7 8 9 10 11
6 7 8 9 10 11
7 8 9 10 11
8 9 10 11
9 10 11
10 11
11
With input n=6
and x=2
output:
6 5 4 3 2 1
6 5 4 3 2
6 5 4 3
6 5 4
6 5
6
With input n = 3
and x = 4
, output:
3
2 3
1 2 3
With input n = 1
and any x
, output:
1
The Rules
- Leading/trailing newlines or other whitespace are optional, provided that the numbers line up appropriately. (For example, trailing whitespace to make a square output is acceptable).
- Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
- Output can be to the console, saved as an image, returned as a list of strings, etc. Any convenient and allowed format.
- Standard loopholes are forbidden.
- This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.
-
\$\begingroup\$ This question is just this + this. I don't know yet but I feel like this is a dupe of one of them. \$\endgroup\$Wheat Wizard– Wheat Wizard ♦2017年10月18日 15:11:02 +00:00Commented Oct 18, 2017 at 15:11
-
4\$\begingroup\$ @WheatWizard I don't think answers from either of those challenges can be trivially modified to be competitive here. \$\endgroup\$AdmBorkBork– AdmBorkBork2017年10月18日 15:18:41 +00:00Commented Oct 18, 2017 at 15:18
-
\$\begingroup\$ To be honest I know a lot of people say thats what makes a duplicate, but as far as I can tell its not a rule. To me a duplicate is a question that offers nothing in terms of challenge that's not provided by existing questions. \$\endgroup\$Wheat Wizard– Wheat Wizard ♦2017年10月18日 15:20:04 +00:00Commented Oct 18, 2017 at 15:20
-
2\$\begingroup\$ @WheatWizard Meta consensus. \$\endgroup\$AdmBorkBork– AdmBorkBork2017年10月18日 15:25:56 +00:00Commented Oct 18, 2017 at 15:25
-
\$\begingroup\$ I've read that answer. Its a recommendation in a more specific context not a universal ruling. \$\endgroup\$Wheat Wizard– Wheat Wizard ♦2017年10月18日 15:27:32 +00:00Commented Oct 18, 2017 at 15:27
10 Answers 10
Jelly, 13 bytes
Rṫ`z6ṚH}¡U9¡G
Left argument: n
Right argument: x
(0
= top-left, 1
= top-right, 2
= bottom-left, 3
= bottom-right)
APL (Dyalog), 29 bytes
{' '@(=∘0)⌽∘⍉⍣⍺⊢↑⌽(⍳+⍵-⊢) ̈⍳⍵}
How?
̈⍳⍵
- for each i
in range of n
(⍳+⍵-⊢)
- produce range of i
with vectorized addition of n - i
↑⌽
- reverse and flatten
⌽∘⍉
- rotate right
⍣⍺⊢
- x
times
' '@(=∘0)
- remove zeros
JavaScript (削除) 130 (削除ここまで) (削除) 128 (削除ここまで) (削除) 154 (削除ここまで) (削除) 142 (削除ここまで) (削除) 138 (削除ここまで) (削除) 135 (削除ここまで) 133 bytes
*fixed padding issues
A=(n,x)=>(j=>{for(;n--;s=x<3?S+`
`+s:s+S+`
`)
for(S=O,i=j;i;S=i-->n^~-x%3?X+S:S+X)
X=(i>n?i+O:O).padStart(j.length+1)})(n+=s=O="")||s
console.log(A(6,1))
console.log(A(6,2))
console.log(A(6,3))
console.log(A(6,4))
console.log(A(12,1))
console.log(A(12,2))
console.log(A(12,3))
console.log(A(12,4))
/* 154 solution
A=(n,x)=>{s=""
for(j=n;n--;s=x<3?S+`
`+s:s+S+`
`)
for(S="",i=j;i;S=i-->n?~-x%3?S+X:X+S:~-x%3?X+S:S+X)
X=(i>n?i+"":"").padStart((j+"").length+1)
return s
}
142 solution
A=(n,x)=>{s=""
for(j=n;n--;s=x<3?S+`
`+s:s+S+`
`)
for(S="",i=j;i;S=i-->n ^ ~-x%3?X+S:S+X)
X=(i>n?i+"":"").padStart((j+"").length+1)
return s
}
138 solution
A=(n,x)=>{s=""
for(j=n+" ";n--;s=x<3?S+`
`+s:s+S+`
`)
for(S="",i=+j;i;S=i-->n^~-x%3?X+S:S+X)
X=(i>n?i+"":"").padStart(j.length)
return s
}
135 solution
A=(n,x)=>{for(j=n+=s=O="";n--;s=x<3?S+`
`+s:s+S+`
`)
for(S=O,i=j;i;S=i-->n^~-x%3?X+S:S+X)
X=(i>n?i+O:O).padStart(j.length+1)
return s
}
*/
-
\$\begingroup\$ @AdmBorkBork i think i fixed it now \$\endgroup\$DanielIndie– DanielIndie2017年10月21日 09:20:17 +00:00Commented Oct 21, 2017 at 9:20
MATL, 18 bytes
:&YhiX!VZ{' 0'2:YX
First input is n
. Second input is x
, which can be:
0
: top left1
: bottom left2
: bottom right3
: top right
(Or it can be any other integer, which is interpreted modulo 4).
Try it at MATL Online!
Python 2, (削除) 124 (削除ここまで) 120 bytes
n,x=input()
r=range(n)
for l in zip(*[(r+[n]+['']*i)[-n:]for i in r][::1-x%4/2*2])[::1-x/3*2]:print' %%%ds'%len(`n`)*n%l
Try it online! or Try all test cases
(r+[n]+['']*i)[-n:]
will add some empty strings to the number list, and chop to the right size, zip
with [::1-x%4/2*2]
and [::1-x/3*2]
will make the rotation, and %%%ds'%len(`n`)*n
will generate a string for fomating (like ' %3s %3s %3s'...
) to be used on each numbers+empty string list
Mathematica, 89 bytes
(R=Reverse;Grid[{#&,R/@#&,R[R/@#]&,R@#&}[[#2]]@PadRight@Array[Range[#,s]&,s=#]/. 0->""])&
here is another solution that works in TIO
Mathematica, 122 bytes
(R=Reverse;StringRiffle[""<>ToString/@#&/@({#&,R/@#&,R[R/@#]&,R@#&}[[#2]]@PadRight@Array[#~Range~s&,s=#]/. 0->" "),"\n"])&
Charcoal, 39 bytes
×ばつ‹+ιλτI⊕+ιλLθσFN≔⮌EσEσ§μλσEσ⪫ι
Try it online! Note: Trailing space. Link is to verbose version of code. Second value is number of anticlockwise rotations so 0 is upper left, 1 lower left, 2 lower right, 3 upper right. Explanation:
Nτ Assign the first input as an integer
EτEτ Map in two dimensions
⊕+ιλ Sum of zero-indexed coordinates plus 1
I Cast to string
‹+ιλτ Is this the upper left triangle?
×ばつ Repeat the string once if so
◧ Lθ Pad to length of first input
≔ σ Assign to variable
EσEσ§μλ Transpose the array
⮌ Reflect the array, giving a rotation
≔ σ Reassign to variable
N Second input as an integer
F Repeat that many times
Eσ Map over array
⪫ι Join with spaces and implicitly print
Javascript (ES6), (削除) 241 (削除ここまで) (削除) 222 (削除ここまで) 214 bytes
let f =
(n,x)=>(L=x=>(''+x).length,M=b=>x&b?(c,i,a)=>a[n-1-i]:c=>c,Array(n).fill(b=' ').map((c,i)=>b.repeat(L(n)-L(++i))+i).map((c,i,a)=>a.map((v,j)=>j>i?b.repeat(L(n)):v)).map(M(1)).map(c=>c.map(M(2))).map(c=>c.join(b)))
function printTriangle() { // display array of strings returned by f
o.innerText = f(
+Length.value, // number
Rotate.value[0] // ASCII char
).join('\n');
}
Length: <input type="text" value="11" id="Length"><br>
Rotate: <input type="text" value="0" id="Rotate"> 0,1,2,3<br>
<button type="button" onclick="printTriangle()">
OK
</button>
<br>
<pre id="o"></pre>
Less Golfed
(n,x)=>(
L= x=> (''+x).length, // strlen(x)
M= b=> x&b ? (c,i,a)=>a[n-1-i] : c=>c, // reverse or identity map
Array(n).fill(b=' ')
.map((c,i)=>b.repeat(L(n)-L(++i))+i) // a complete line of numbers
.map((c,i,a)=>a.map((v,j)=>j>i?b.repeat(L(n)):v)) // to 2-d array
// with spaces for blank numbers
.map(M(1)) // flip vertically?
.map(c=>c.map(M(2))) // flip horizontally?
.map(c=>c.join(b)) // convert lines to strings
)
Note on orientation.
The second parameter is a character from {'0', '1', '2', '3'} and automatically type converted to a number by the &
operator. If bit 0 (lsb) of the number is set, lines are flipped vertically. If bit 1 (nlsb) is set, columns are flipped horizontally. Other decimal digit characters can be used with predictable results.
Trailing Spaces
Blank entries in the output string have been replaced with spaces, which means lines have trailing spaces in orientations '0' and '1'.
Lua, 250 bytes
function f(w,m)d=""for y=1,w do for x=1,w do d=string.format("%s%"..tostring(w):len().."s ",d,m<2 and(y+x-1<=w and x+y-1 or"")or(m<3 and(x>=y and w-x+y or"")or(m<4 and(y+x-1>=w and w+w-x-y+1 or"")or(y>=x and w-y+x or""))))end;d=d.."\n"end;print(d)end
Takes parameters [w]idth and [m]ode using 1,2,3,4 for modes as described in the example.