Challenge
Create the shortest program that meets the requirements
Requirements
The code must generate a 5x5 grid of 0s, like so:
00000 00000 00000 00000 00000The code must accept an input (column, row, character). The grid must change accordingly:
Start:
00000 00000 00000 00000 00000Input:
(2,5,*)Output:
0*000 00000 00000 00000 00000(Note: the bottom-left corner is position 1,1.)
The program must return an error message other than the grid if the row/column input is not 1,2,3,4, or 5. This can be any message of your choice (as long as it's not the grid), so
0is an acceptable error-output.The program must work with all printable ASCII characters (of a US keyboard).
THE WINNER
The winner will be the person who has the shortest code and fulfills all requirements. If more than one answer works and has the same (shortest) length, the person who answered first will be the winner.
27 Answers 27
Dyalog APL, (削除) 17 (削除ここまで) (削除) 13 (削除ここまで) 10 bytes
Prompts for an enclosed array containing (row, column) and then for a character. Gives INDEX ERROR on faulty input.
⊖⍞@⎕⊢5 5⍴0
⊖ flip upside-down the result of
⍞ inputted-character
@ replacing the content at position
⎕ evaluated-input (enclosed row, column)
⊢ of
5 5⍴ ×ばつ5 array of
0 zeros
-
\$\begingroup\$ Is
⊢necessary? I think in this case it's redundant. \$\endgroup\$Conor O'Brien– Conor O'Brien2016年11月29日 14:00:41 +00:00Commented Nov 29, 2016 at 14:00 -
1\$\begingroup\$ @ConorO'Brien @ConorO'Brien if it isn't there, the parser sees
(⊂⎕)5 5as a single 3-element array – the argument to⍴. \$\endgroup\$Adám– Adám2016年11月29日 14:31:38 +00:00Commented Nov 29, 2016 at 14:31 -
\$\begingroup\$ That is 13 Unicode characters, not 13 bytes, isn't it? \$\endgroup\$wilx– wilx2016年11月29日 16:15:13 +00:00Commented Nov 29, 2016 at 16:15
-
1
-
\$\begingroup\$ This answer is the winner. \$\endgroup\$Dave Jones– Dave Jones2016年12月01日 23:47:28 +00:00Commented Dec 1, 2016 at 23:47
Ruby, (削除) 157 (削除ここまで) 149 bytes
g=(1..5).map{[0]*5}
loop{puts g.map(&:join).join ?\n
x=gets.match /\((.),(.),(.)\)/
a,b=x[1].hex,x[2].hex
1/0 if a<1||a>5||b<1||b>5
g[5-b][a-1]=x[3]}
Error on malformed input or out of bound position
Thanks to ConorO'Brien (8 bytes) and afuous (2 bytes) for helping saving bytes
-
\$\begingroup\$
loop do...end->loop{...}; I thinkArray.new(5,[0]*5)works, too, or even[*[0]*5]*5. \$\endgroup\$Conor O'Brien– Conor O'Brien2016年11月29日 15:46:51 +00:00Commented Nov 29, 2016 at 15:46 -
\$\begingroup\$ @ConorO'Brien Nope,
Array.new(5,[0]*5)make an array of reference and[*[0]*5]*5make a flat array \$\endgroup\$TuxCrafting– TuxCrafting2016年11月29日 19:16:57 +00:00Commented Nov 29, 2016 at 19:16 -
\$\begingroup\$ Oh, right. Omit the first
*. Then that still creates an array of references. \$\endgroup\$Conor O'Brien– Conor O'Brien2016年11月29日 19:19:11 +00:00Commented Nov 29, 2016 at 19:19 -
\$\begingroup\$
Array.new(5){[0]*5}can be replaced with(1..5).map{[0]*5}to save 2 bytes. \$\endgroup\$afuous– afuous2016年11月30日 07:57:16 +00:00Commented Nov 30, 2016 at 7:57
Batch, 199 bytes
@echo off
if %1 gtr 0 if %1 lss 6 if %2 gtr 0 if %2 lss 6 goto g
if
:g
for /l %%j in (5,1,-1)do call:l %* %%j
exit/b
:l
set s=000000
if %2==%2 call set s=%%s:~0,%1%%%3%%s:~%1%%
echo %s:~1,5%
Errors out if the position is out of range.
-
\$\begingroup\$ I think you can use symbols for
<, like^<. not sure tho. \$\endgroup\$Conor O'Brien– Conor O'Brien2016年11月29日 15:47:55 +00:00Commented Nov 29, 2016 at 15:47
PHP, (削除) 111 (削除ここまで) (削除) 100 (削除ここまで) 97 bytes
$s=str_repeat("00000\n",5);$s[($x=($a=$argv)[1])+29-6*$y=$a[2]]=$a[3];echo$x&&$y&&$x<6&$y<6?$s:E;
prints E if row/column out of range.
Run with php -r <code> <row> <column> <character>
Python, 66 bytes
lambda a,b,n,l='00000\n':6>b>0<a<6and(5-b)*l+l[:a-1]+n+l[a:]+~-b*l
-
\$\begingroup\$ Won´t this fail for a=4,b=3? \$\endgroup\$Titus– Titus2016年11月29日 13:21:21 +00:00Commented Nov 29, 2016 at 13:21
-
\$\begingroup\$ @Titus not anymore ;D \$\endgroup\$Rod– Rod2016年11月29日 13:28:06 +00:00Commented Nov 29, 2016 at 13:28
-
1\$\begingroup\$ Solution also works for Python3 \$\endgroup\$george– george2016年11月29日 13:55:49 +00:00Commented Nov 29, 2016 at 13:55
Dyalog APL, (削除) 24 (削除ここまで) (削除) 20 (削除ここまで) 18 bytes
Saved 4 bytes thanks to Zgarb! Saved 2 bytes thanks to Adam!
a←5 5⍴0⋄a[⊂⎕]←⍞⋄⊖a
Prompts for input. See below for an explanation.
20 bytes
{a←5 5⍴0⋄a[⊂⍺]←⍵⋄⊖a}
Assign to a function and call it y x f 'c'. E.g.:
f←{a←5 5⍴0⋄a[⊂⍺]←⍵⋄⊖a}
5 2 f '*'
0 * 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
6 6 f '*'
INDEX ERROR
←{a←5 5⍴0 ⋄ a[⊂⍺]←⍵ ⋄ ⊖a}
∧
0 0 f '*'
INDEX ERROR
←{a←5 5⍴0 ⋄ a[⊂⍺]←⍵ ⋄ ⊖a}
∧
Explanation
{a←5 5⍴0⋄a[⊂⍺]←⍵⋄⊖a}
{...} is a function with left argument ⍺ and right argument ⍵. ⋄ separates statements, so there are three statements:
a←5 5⍴0⋄a[⊂⍺]←⍵⋄⊖a
The first statement a←5 5⍴0 sets a to a 5 by 5 grid of 0s.
The second statement sets the member at coordinates dictated by ⍺ to ⍵ (that is, the character).
Finally, we perform ⊖ on a and return that, yielding the firsts of a reversed.
-
\$\begingroup\$
{a←5 5⍴0⋄a[⊂⌽⍺]←⍵⋄⊖a}saves a few bytes. \$\endgroup\$Zgarb– Zgarb2016年11月29日 13:52:28 +00:00Commented Nov 29, 2016 at 13:52 -
\$\begingroup\$ @Zgarb Oh, fantastic! I didn't know indexing worked like that. \$\endgroup\$Conor O'Brien– Conor O'Brien2016年11月29日 13:53:47 +00:00Commented Nov 29, 2016 at 13:53
-
\$\begingroup\$ You can save two bytes by converting to a tradfn body:
a←5 5⍴0⋄a[⊂⎕]←⍞⋄⊖a\$\endgroup\$Adám– Adám2016年11月29日 14:29:52 +00:00Commented Nov 29, 2016 at 14:29 -
\$\begingroup\$ @Adám how does that work? It doesn't seem to work on TryAPL. \$\endgroup\$Conor O'Brien– Conor O'Brien2016年11月29日 14:37:02 +00:00Commented Nov 29, 2016 at 14:37
-
JavaScript (ES6), (削除) 73 (削除ここまで) 76 bytes
Throws a TypeError if the column or the row is out of range.
(c,r,C,a=[...`00000
`.repeat(5)])=>(a[29+c-r*6]=C,c<1|r<1|c>5|r>5||a).join``
Demo
let f =
(c,r,C,a=[...`00000
`.repeat(5)])=>(a[29+c-r*6]=C,c<1|r<1|c>5|r>5||a).join``
console.log(f(2,5,'*'));
-
\$\begingroup\$ Sweet, but does it throw an error if either
corris less than 1? \$\endgroup\$ETHproductions– ETHproductions2016年11月29日 16:15:18 +00:00Commented Nov 29, 2016 at 16:15 -
\$\begingroup\$ @ETHproductions It's only testing
c == 0 || r == 0. But I guess you're right: I will update it to prevent negative values. \$\endgroup\$Arnauld– Arnauld2016年11月29日 16:32:42 +00:00Commented Nov 29, 2016 at 16:32
C#, 199 Bytes
Based on Pete Arden's answer
string g(int c, int r, char a){if(c<1|c>5|r<1|r>5)return "Index Error";var b="00000";var d=new[]{b,b,b,b,b};c--;d[r-1]=new string('0',c)+a+new string('0',4-c);return string.Join("\r\n",d.Reverse());}
Ungolfed:
public static string G(int c, int r, char a)
{
if (c < 1 || c > 5 || r < 1 || r > 5) return "Index Error"; // Check it's not out of range
var b = "00000";
var d = new [] { b, b, b, b, b }; // Generate display box, and fill with the default character
c--; // Convert the X to a 0 based index
d[r - 1] = new string('0',c) + a + new string('0',4-c); // Replace the array's entry in y coordinate with a new string containing the new character
return string.Join("\r\n", d.Reverse()); // Reverse the array (so it's the right way up), then convert to a single string
}
-
\$\begingroup\$ Welcome to the site! I'm not an expert in C#, but it looks like there's some whitespace you could remove. \$\endgroup\$DJMcMayhem– DJMcMayhem2016年11月29日 17:35:29 +00:00Commented Nov 29, 2016 at 17:35
-
1\$\begingroup\$ (Sorry, don't know submission etiquette) Shorter G(): public static string G(int c,int r,char a){return(0<c&&c<6&&0<r&&r<6)?string.Concat(Enumerable.Range(1,29).Select(i=>i%6>0?i/6==5-r&&i%6==c?a:'0':'\n')):"Index Error";} \$\endgroup\$Eric– Eric2016年11月29日 20:32:26 +00:00Commented Nov 29, 2016 at 20:32
Jelly, 28 bytes
This feels way too long...
Ṫ0ẋ24¤;ṙÑs5UY
’ḅ5
Ṗḟ5R¤
-ÑÇ?
How?
Ṫ0ẋ24¤;ṙÑs5UY - Link 1, make grid: [row, column, character] e.g. [5,2,'*']
Ṫ - tail: character '*'
¤ - nilad followed by link(s) as a nilad
0 - zero
ẋ - repeated
24 - 24 times [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
; - concatenate: "000000000000000000000000*"
Ñ - call next link (2) as a monad 21
ṙ - rotate left by "000*000000000000000000000"
s5 - split into chunks of length 5 ["000*0","00000","00000","00000","00000"]
U - upend (reveres each) ["0*000","00000","00000","00000","00000"]
Y - join with line feeds 0*000
- implicit print 00000
00000
’ḅ5 - Link 2, position: [row, column] 00000
’ - decrement 00000
ḅ5 - convert from base 5
Ṗḟ5R¤ - Link 3, input error checking: [row, column, character]
Ṗ - pop: [row, column]
ḟ - filter out values in
5R¤ - range(5): [1,2,3,4,5] - any values not in this remain giving a truthy result
-ÑÇ? - Main link: [row, column, character]
? - ternary if:
Ç - last link (3) as a monad
- - -1 (if truthy - the error identification)
Ñ - next link (1) as a monad (if falsey - the grid)
JavaScript (ES6), 89 bytes
f=(X,Y,Z,x=5,y=5)=>x+y>1?(x?X+x-6|Y-y?0:Z:`
`)+f(X,Y,Z,x?x-1:5,y-!x):X<1|X>5|Y<1|Y>5?e:""
Because I love recursion. Throws a ReferenceError on invalid coordinates.
Mathematica, 38 bytes
(x=Table[0,5,5];x[[-#2,#]]=#3;Grid@x)&
Brain-Flak 415 Bytes
Includes +3 for -c
([][()()()]){{}}{}({}<(({}<(({})<>)<>>)<>)<>([((((()()()){}){}){}){}]{}<([((((()()()){}){}){}){}]{})>)(()()()()()){({}[()]<(({})){{}(<({}[()])>)}{}({}<(({})){{}(<({}[()])>)}{}>)>)}{}({}{}){<>{{}}<>{}}<>>)<>(()()()()()){({}[()]<(((((((((()()()){}){}){}){})))))((()()()()()){})>)}{}{}<>({}<()((((((()()()){}){}()){}){}()[{}])({})({})({})({}){}{}[((((()()()){}){}){}){}()]){({}[()]<<>({}<>)>)}{}<>{}>)<>{({}<>)<>}<>
Takes the character to insert first, then the row then column without spaces.
Most of this is just error handling. Brain-Flak doesn't have a good way to check if values are in a range. For errors, it either outputs nothing, or just the character that was supposed to be inserted. Solving the actual problem only takes 211 bytes:
<>(()()()()()){({}[()]<(((((((((()()()){}){}){}){})))))((()()()()()){})>)}{}{}<>({}<()((((((()()()){}){}()){}){}()[{}])({})({})({})({}){}{}[((((()()()){}){}){}){}()]){({}[()]<<>({}<>)>)}{}<>{}>)<>{({}<>)<>}<>
Excel VBA, 67 Bytes
Outputs to the range A1:E5 on the activesheet of the vba project, exits with
Run-time error '1004':
Application-defined or object-defined error
when an invalid input is provided.
Code:
Sub a(c,r,x)
c=IIf(r<1Or c>5,-1,c)
[A1:E5]=0
Cells(6-r,c)=x
End Sub
Usage:
a 4,5,"#"
Output (from example above):
A B C D E
1 0 0 0 # 0
2 0 0 0 0 0
3 0 0 0 0 0
4 0 0 0 0 0
5 0 0 0 0 0
C#, 208 Bytes
Golfed:
string G(int c,int r,char a){if(c<1||c>5||r<1||r>5)return"Index Error";var b="00000";var d=new string[]{b,b,b,b,b};d[r-1]=d[r-1].Substring(0,c-1)+a+d[r-1].Substring(c);return string.Join("\r\n",d.Reverse());}
Ungolfed:
public string G(int c, int r, char a)
{
if (c < 1 || c > 5 || r < 1 || r > 5) return "Index Error";
var b = "00000";
var d = new string[] { b, b, b, b, b };
d[r - 1] = d[r - 1].Substring(0, c - 1) + a + d[r - 1].Substring(c);
return string.Join("\r\n", d.Reverse());
}
Testing:
Console.Write(G(6, 6, '*')); //Index Error
Console.Write(G(1, 4, '#'));
00000
#0000
00000
00000
00000
Console.Write(G(5, 5, '@'));
0000@
00000
00000
00000
00000
Console.Write(G(1, 1, '}'));
00000
00000
00000
00000
}0000
-
\$\begingroup\$ If
cand/orrare out of bounds it will throw anIndexOutOfRangeExceptionso you might be able to remove the first if statement though I haven't checked the specs properly for that. You can compile to aFunc<int, int, char, string>to save bytes, I believe you need to addusing System.Linq;in because of theReversecall though I can't remember off the top of my head \$\endgroup\$TheLethalCoder– TheLethalCoder2016年11月29日 16:38:53 +00:00Commented Nov 29, 2016 at 16:38 -
\$\begingroup\$ Change
d[r - 1] = d[r - 1].Substring(0, c - 1) + a + d[r - 1].Substring(c);tod[--r] = d[r].Substring(0, c - 1) + a + d[r].Substring(c);to save 4 bytes \$\endgroup\$TheLethalCoder– TheLethalCoder2016年11月29日 16:39:24 +00:00Commented Nov 29, 2016 at 16:39
WinDbg, 95 bytes
j(0<(@$t0|@$t1))&(6>@$t0)&(6>@$t1)'f8<<16 L19 30;eb2000018+@$t0-@$t1*5 @$t2;da/c5 8<<16 L19';?0
Almost half of it just verifying the indexes are in range... Input is done by setting the psuedo-registers $t0, $t1, and $t2 (where $t2 holds the ascii value of the char to replace). For example, (2,5,*) like the example would be:
0:000> r$t0=2
0:000> r$t1=5
0:000> r$t2=2a
Prints 0 on error.
How it works:
j (0<(@$t0|@$t1)) & (6>@$t0) & (6>@$t1) * If $t0 and $t1 are both positive and less than 6
'
f 8<<16 L19 30; * Put 19 (0n25) '0's (ascii 30) at 2000000 (8<<16)
eb 2000018+@$t0-@$t1*5 @$t2; * Replace the specified cell with the new char
da /c5 8<<16 L19 * Print 19 (0n25) chars in rows of length 5
';
?0 * ...Else print 0
Sample Output:
0:000> r$t0=2
0:000> r$t1=5
0:000> r$t2=2a
0:000> j(0<(@$t0|@$t1))&(6>@$t0)&(6>@$t1)'f8<<16 L19 30;eb2000018+@$t0-@$t1*5 @$t2;da/c5 8<<16 L19';?0
Filled 0x19 bytes
02000000 "0*000"
02000005 "00000"
0200000a "00000"
0200000f "00000"
02000014 "00000"
0:000> r$t0=-2
0:000> j(0<(@$t0|@$t1))&(6>@$t0)&(6>@$t1)'f8<<16 L19 30;eb2000018+@$t0-@$t1*5 @$t2;da/c5 8<<16 L19';?0
Evaluate expression: 0 = 00000000
0:000> r$t0=4
0:000> r$t1=2
0:000> r$t2=23
0:000> j(0<(@$t0|@$t1))&(6>@$t0)&(6>@$t1)'f8<<16 L19 30;eb2000018+@$t0-@$t1*5 @$t2;da/c5 8<<16 L19';?0
Filled 0x19 bytes
02000000 "00000"
02000005 "00000"
0200000a "00000"
0200000f "000#0"
02000014 "00000"
0:000> r$t1=f
0:000> j(0<(@$t0|@$t1))&(6>@$t0)&(6>@$t1)'f8<<16 L19 30;eb2000018+@$t0-@$t1*5 @$t2;da/c5 8<<16 L19';?0
Evaluate expression: 0 = 00000000
Haskell, 77 bytes
r=[1..5]
(x#y)c|x>0,x<6,y>0,y<6=unlines[[last$'0':[c|i==x,j==6-y]|i<-r]|j<-r]
Usage example:
*Main> putStr $ (2#5) '*'
0*000
00000
00000
00000
00000
If x and y are within range, outer and inner loop through [1..5] and take the char c if it hits the given x and y and a 0 otherwise. If x or y is not in range, a Non-exhaustive patterns exception is raised.
Octave 49 bytes
@(c,r,s)char(accumarray([6-r c],s+0,[5 5],[],48))
QBIC, (削除) 53 (削除ここまで) 50 bytes
EDIT: Now that I know that I don't have to show the starting grid, I've swapped out the user inputs _!_!_? for command line parameters ::;, saving 3 bytes.
[5|?@00000|]::;~(b>5)+(c>5)>1|_Xd\$LOCATE 6-c,b|?B
Original version: This halts between printing the 0-grid and taking the coordinates for the substitution, showing the 0-grid.
[5|?@00000|]_!_!_?~(b>5)+(c>5)>1|_Xd\$LOCATE 6-c,b|?B
Prints 5 strings of 5 0's, asks user for 2 numerical inputs and 1 string input, checks if the numbers are < 5 and uses QBasic's LOCATE function to substitute the right character.
Bash, 59 bytes
Golfed
printf '00000%0.s\n' {1..5}|sed "1ドル s/./3ドル/2ドル"|grep -z "3ドル"
1ドル, 2ドル - row, column, 3ドル - replacement char, error is reported via exit code
Test
>./box 2 2 "*"
00000
0*000
00000
00000
00000
>echo $?
0
>./box 6 2 '*'
>echo $?
1
-
\$\begingroup\$ Nice work, but the origin (0,0) needs to be in the bottom left \$\endgroup\$roblogic– roblogic2024年06月13日 00:32:15 +00:00Commented Jun 13, 2024 at 0:32
Java, 99 bytes
(i,j,k)->{int[]b=new int[]{60,60,60,60,60};int[][]a=new int[][]{b,b,b,b,b};a[i-1][5-j]=k;return a;}
Vim, (削除) 60 (削除ここまで) (削除) 47 (削除ここまで) (削除) 42 (削除ここまで) 76 keystrokes
Input is in the format (on the first line):
25*
With the cursor starting at the beginning
"ax"bxx:if<C-r>a<1||<C-r>a>5||<C-r>b<1||<C-r>b>5
^
endif
6i0<ESC>Y5pG:norm <C-r>al<C-r>bkr<C-r>-
Hqqxjq5@qdd
If the input is invalid, then throws: E492: Not an editor command: ^
The cide that produces the output is only 42 bytes, but in order to create an error, my bytecount is drastically increased.
-
\$\begingroup\$ BTW I don't know how to create the error in Vim \$\endgroup\$user41805– user418052016年12月07日 20:00:19 +00:00Commented Dec 7, 2016 at 20:00
Java 8, (削除) 194 (削除ここまで) 192 bytes
interface M{static void main(String[]a){String r="";int i=0,j,z=new Byte(a[0]),y=new Byte(a[1]);for(;++i<6;r+="\n")for(j=0;++j<6;r+=6-i==y&j==z?a[2]:0);System.out.print(z>0&z<7&y>0&y<7?r:0);}}
Try it here with correct input.
Try it here with incorrect input.
This would be (削除) 116 (削除ここまで) 114 bytes instead as function instead of full program:
(a,b,c)->{String r="";for(int i=0,j;++i<6;r+="\n")for(j=0;++j<6;r+=b==6-i&a==j?c:0);return a>0&a<7&b>0&b<7?r:"0";}
Explanation:
interface M{ // Class
static void main(String[]a){// Mandatory main-method
String r=""; // Result-String, starting empty
int i=0,j, // Index-integers
z=new Byte(a[0]), // First input converted to integer
y=new Byte(a[1]); // Second input converted to integer
for(;++i<6; // Loop (1) from 1 to 6 (inclusive)
r+="\n") // After every iteration: Append a new-line to the result
for(j=0;++j<6; // Inner loop (2) from 1 to 6 (inclusive)
r+=6-i==y // If the second input equals `6-1`,
&j==z? // and the first input equals `j`:
a[2] // Append the third input to the result-String
: // Else:
0 // Append a zero to the result-String
); // End of inner loop (2)
// End of inner loop (1) (implicit / single-line body)
System.out.print( // Print:
z>0&z<7&y>0&y<7? // If the coordinates are valid (1-6):
r // Print the result `r`
: // Else:
0); // Print 0 as error instead
} // End of main-method
} // End of class
GFortran -fbounds-check, 97 bytes
character(1)K(5,5),a;K='0';read*,m,n;read*,a;K(m,n)=a
do j=5,1,-1;print*,(K(i,j),i=1,5);enddo;end
Any index outside the range [1,5] throws a Fortran runtime error.
(& much shorter than checking if(m<1.or.m>5.or.n<1.or.n>5)x=1/0 )
Zsh, (削除) 68 (削除ここまで) 55 bytes
((1ドル<6&&2ドル<6))&&jot -b00000 5|sed "2ドル s/./3ドル/1ドル"|tac||e
Try it online!
(削除) 68b (削除ここまで)
If 1ドル or 2ドル are more than 5, Zsh throws command not found: e. If they are 0 or less, sed throws an error.
0for error and the grid for success? \$\endgroup\$