19
\$\begingroup\$

Challenge

Create the shortest program that meets the requirements

Requirements

  1. The code must generate a 5x5 grid of 0s, like so:

    00000
    00000
    00000
    00000
    00000
    
  2. The code must accept an input (column, row, character). The grid must change accordingly:

    Start:

    00000
    00000
    00000
    00000
    00000
    

    Input:

    (2,5,*)
    

    Output:

    0*000
    00000
    00000
    00000
    00000
    

    (Note: the bottom-left corner is position 1,1.)

  3. 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 0 is an acceptable error-output.

  4. 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.

\$\endgroup\$
20
  • 8
    \$\begingroup\$ The program must return an error message. What error message? Can the program return 0 for error and the grid for success? \$\endgroup\$
    – Rod
    Nov 29, 2016 at 12:26
  • 1
    \$\begingroup\$ Where is the origin on the matrix? does it need to be zero or one indexed? \$\endgroup\$
    – george
    Nov 29, 2016 at 12:30
  • 3
    \$\begingroup\$ Welcome to PPCG, by the way. \$\endgroup\$ Nov 29, 2016 at 12:40
  • 4
    \$\begingroup\$ he program must work with all characters on the US keyboard Why not just ASCII? I do not even know the characters of a US keyboard, and that doesn't add anything to the challenge \$\endgroup\$
    – Luis Mendo
    Nov 29, 2016 at 14:02
  • 1
    \$\begingroup\$ @LuisMendo I think the US keyboard is ASCII, or is at least a subset. \$\endgroup\$ Nov 29, 2016 at 14:03

23 Answers 23

11
\$\begingroup\$

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

Try it online!

 flip upside-down the result of

 inputted-character

@ replacing the content at position

 evaluated-input (enclosed row, column)

 of

5 5⍴ 5×5 array of

0 zeros

\$\endgroup\$
5
  • \$\begingroup\$ Is necessary? I think in this case it's redundant. \$\endgroup\$ Nov 29, 2016 at 14:00
  • 1
    \$\begingroup\$ @ConorO'Brien @ConorO'Brien if it isn't there, the parser sees (⊂⎕)5 5 as a single 3-element array – the argument to . \$\endgroup\$
    – Adám
    Nov 29, 2016 at 14:31
  • \$\begingroup\$ That is 13 Unicode characters, not 13 bytes, isn't it? \$\endgroup\$
    – wilx
    Nov 29, 2016 at 16:15
  • 1
    \$\begingroup\$ @wilx Click on the word bytes! \$\endgroup\$
    – Adám
    Nov 29, 2016 at 16:17
  • \$\begingroup\$ This answer is the winner. \$\endgroup\$
    – Dave Jones
    Dec 1, 2016 at 23:47
5
\$\begingroup\$

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

\$\endgroup\$
4
  • \$\begingroup\$ loop do...end -> loop{...}; I think Array.new(5,[0]*5) works, too, or even [*[0]*5]*5. \$\endgroup\$ Nov 29, 2016 at 15:46
  • \$\begingroup\$ @ConorO'Brien Nope, Array.new(5,[0]*5) make an array of reference and [*[0]*5]*5 make a flat array \$\endgroup\$ Nov 29, 2016 at 19:16
  • \$\begingroup\$ Oh, right. Omit the first *. Then that still creates an array of references. \$\endgroup\$ 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
    Nov 30, 2016 at 7:57
4
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ I think you can use symbols for <, like ^<. not sure tho. \$\endgroup\$ Nov 29, 2016 at 15:47
3
\$\begingroup\$

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>

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
3
  • \$\begingroup\$ Won´t this fail for a=4,b=3? \$\endgroup\$
    – Titus
    Nov 29, 2016 at 13:21
  • \$\begingroup\$ @Titus not anymore ;D \$\endgroup\$
    – Rod
    Nov 29, 2016 at 13:28
  • 1
    \$\begingroup\$ Solution also works for Python3 \$\endgroup\$
    – george
    Nov 29, 2016 at 13:55
3
\$\begingroup\$

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.

\$\endgroup\$
5
  • \$\begingroup\$ {a←5 5⍴0⋄a[⊂⌽⍺]←⍵⋄⊖a} saves a few bytes. \$\endgroup\$
    – Zgarb
    Nov 29, 2016 at 13:52
  • \$\begingroup\$ @Zgarb Oh, fantastic! I didn't know indexing worked like that. \$\endgroup\$ 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
    Nov 29, 2016 at 14:29
  • \$\begingroup\$ @Adám how does that work? It doesn't seem to work on TryAPL. \$\endgroup\$ Nov 29, 2016 at 14:37
  • \$\begingroup\$ @ConorO'Brien Right. TryAPL prohibits prompting for input, but you can get the full version for free. \$\endgroup\$
    – Adám
    Nov 29, 2016 at 14:42
3
\$\begingroup\$

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,'*'));

\$\endgroup\$
2
  • \$\begingroup\$ Sweet, but does it throw an error if either c or r is less than 1? \$\endgroup\$ 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
    Nov 29, 2016 at 16:32
3
\$\begingroup\$

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
    }
\$\endgroup\$
2
  • \$\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
    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
    Nov 29, 2016 at 20:32
2
\$\begingroup\$

05AB1E, 27 22 bytes

Returns no grid when row/column > 5.

‚6‹Pi25L²<5*¹+Q5äR»1³‡

Try it online!

Previous version

‚6‹Pi26G¾5²<*¹+NQi\³}})5äR»
\$\endgroup\$
2
\$\begingroup\$

Jelly, 28 bytes

This feels way too long...

Ṫ0ẋ24¤;ṙÑs5UY
’ḅ5
Ṗḟ5R¤
-ÑÇ?

TryItOnline!

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)
\$\endgroup\$
0
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

Mathematica, 38 bytes

(x=Table[0,5,5];x[[-#2,#]]=#3;Grid@x)&
\$\endgroup\$
2
\$\begingroup\$

Brain-Flak 415 Bytes

Includes +3 for -c

([][()()()]){{}}{}({}<(({}<(({})<>)<>>)<>)<>([((((()()()){}){}){}){}]{}<([((((()()()){}){}){}){}]{})>)(()()()()()){({}[()]<(({})){{}(<({}[()])>)}{}({}<(({})){{}(<({}[()])>)}{}>)>)}{}({}{}){<>{{}}<>{}}<>>)<>(()()()()()){({}[()]<(((((((((()()()){}){}){}){})))))((()()()()()){})>)}{}{}<>({}<()((((((()()()){}){}()){}){}()[{}])({})({})({})({}){}{}[((((()()()){}){}){}){}()]){({}[()]<<>({}<>)>)}{}<>{}>)<>{({}<>)<>}<>

Try it Online!

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:

<>(()()()()()){({}[()]<(((((((((()()()){}){}){}){})))))((()()()()()){})>)}{}{}<>({}<()((((((()()()){}){}()){}){}()[{}])({})({})({})({}){}{}[((((()()()){}){}){}){}()]){({}[()]<<>({}<>)>)}{}<>{}>)<>{({}<>)<>}<>
\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ If c and/or r are out of bounds it will throw an IndexOutOfRangeException so you might be able to remove the first if statement though I haven't checked the specs properly for that. You can compile to a Func<int, int, char, string> to save bytes, I believe you need to add using System.Linq; in because of the Reverse call though I can't remember off the top of my head \$\endgroup\$ Nov 29, 2016 at 16:38
  • \$\begingroup\$ Change d[r - 1] = d[r - 1].Substring(0, c - 1) + a + d[r - 1].Substring(c); to d[--r] = d[r].Substring(0, c - 1) + a + d[r].Substring(c); to save 4 bytes \$\endgroup\$ Nov 29, 2016 at 16:39
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Octave 49 bytes

@(c,r,s)char(accumarray([6-r c],s+0,[5 5],[],48))
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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;}
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ BTW I don't know how to create the error in Vim \$\endgroup\$
    – user41805
    Dec 7, 2016 at 20:00
0
\$\begingroup\$

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";}

Try it here.

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
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.