title: Taxicab in San Francisco

text:
# Question
Title: Taxicab in San Francisco
You are a taxicab driver in San Francisco. As is typical of taxicab drivers, you are navigating a grid where the only valid directions you can move are the left, right, up, and down. However, San Fransisco is very hilly so the distance between two adjacent intersections is not necessarily the same. More specifically, the distance between an intersection at altitude `a` and an adjacent intersection at altitude `b` would be `1 + |a - b|`. Your goal is to find all the shortest paths from your origin at the top left of the map to your destination at the bottom right.

## Input

A two-dimensional grid of integer altitudes in whichever format is most convenient (two-dimensional array, one-dimensional array with width and/or height, etc.).

## Output

A sequence of directions to travel to arrive at the bottom right corner of the input from the top left in the shortest distance possible given the distance between two adjacent intersections of altitudes `a` and `b` is given by the formula `1 + |a - b|`. If there are multiple solutions output all solutions.

Though I use `U`, `D`, `L`, and `R` for up, down, left, and right in the examples below your program may use any four distinct strings to represent the directions so long as it is consistent with them in and across all inputs.

## Examples

```
Input:
0 3 0 0 0
0 2 0 2 0
0 0 0 3 0
Output:
D D R R U U R R D D

Input:
3
Output:
<empty>

Input:
11 11 11
11 11 11
11 11 11
Output:
R R D D
R D R D
R D D R
D R R D
D R D R
D D R R

Input:
7 8 1 -1 0
4 4 6 -1 7
3 4 4  2 8
2 5 2 -1 2
Output:
D R D R R D R
D R D R D R R

```

This is so the answer with the shortest byte count wins.

# Answer
> 2 votes
## JavaScript (ES6), ~~228~~ ~~212~~ ~~200~~ 194 bytes

```
a=>w=>(B=1/0,(F=(r,p,s,b=a[p])=>p-a.length+1?1/b&&([...a[p]='RDUL'].map((c,d)=>d|p%w<w-1&&d-3|p%w&&F(r+c,P=p+[1,w,-w,-1][d],s+1+Math.abs(b-a[P]))),a[p]=b):R=s>B?R:s<B?(B=s,r):R+' '+r)('',0,0),R)

```

### Input

One-dimensional array `a` and width `w` in currying syntax `(a)(w)`

### Output

A space-separated list of solutions such as `"DRDRRDR DRDRDRR"`

### Formatted and commented

```
a => w => (                            // given an array 'a' and a width 'w'
  B = 1 / 0,                           // B = best score so far, initialized as +Infinity
  (                                    //
    F = (                              // F = recursive function with:
      r,                               //   - r = current path (string)
      p,                               //   - p = current position in grid
      s,                               //   - s = current score
      b = a[p]                         //   - b = backup of current cell
    ) =>                               //
    p - a.length + 1 ?                 // if we haven't reached our destination:
      1 / b && (                       //   if the current cell is valid:
        [...a[p] = 'RDUL']             //     invalidate the current cell
        .map((c, d) =>                 //     for each possible direction:
          d | p % w < w - 1 &&         //       check right boundary
          d - 3 | p % w &&             //       check left boundary
          F(                           //       do a recursive call with:
            r + c,                     //         - new direction appended to the path
            P = p + [1, w, -w, -1][d], //         - updated position
            s + 1 + Math.abs(b - a[P]) //         - updated score
          )                            //
        ),                             //
        a[p] = b                       //     restore current cell value
      )                                //
    :                                  // else:
      R = s > B ?                      //   if the current score is worse than B:
        R                              //     keep the previous solution
      : s < B ?                        //   if the current score is better than B:
        (B = s, r)                     //     update best score / store path as new solution
      : R + ' ' + r                    //   if it's just as good: append path to solution
  )('', 0, 0),                         // initial call to F with r = '', p = 0, s = 0
  R                                    // return solution
)                                      //

```

### Test cases

```
let f =

a=>w=>(B=1/0,(F=(r,p,s,b=a[p])=>p-a.length+1?1/b&&([...a[p]='RDUL'].map((c,d)=>d|p%w<w-1&&d-3|p%w&&F(r+c,P=p+[1,w,-w,-1][d],s+1+Math.abs(b-a[P]))),a[p]=b):R=s>B?R:s<B?(B=s,r):R+' '+r)('',0,0),R)

console.log(f([
  0, 3, 0, 0, 0,
  0, 2, 0, 2, 0,
  0, 0, 0, 3, 0
])(5));

console.log(f([
  3
])(1));

console.log(f([
  11, 11, 11,
  11, 11, 11,
  11, 11, 11
])(3));

console.log(f([
  7, 8, 1, -1, 0,
  4, 4, 6, -1, 7,
  3, 4, 4,  2, 8,
  2, 5, 2, -1, 2
])(5));
```

# Answer
> 1 votes
# Python3, 383 bytes

```
E=enumerate
def f(b):
 d,D={(x,y):v for x,r in E(b)for y,v in E(r)},{}
 q=[(0,0,0,'',[(0,0)])]
 for x,y,c,m,p in q:
  if(x,y)==(len(b)-1,len(b[0])-1):D[c]=D.get(c,[])+[m];continue
  for U,X,Y in[('R',0,1),('L',0,-1),('U',-1,0),('D',1,0)]:
   if(n:=(x+X,y+Y))not in d:continue
   C=1+abs(d[(x,y)]-d[n])
   if n not in p and(D=={}or C<=min(D)):q+=[(*n,c+C,m+U,p+[n])]
 return D[min(D)]

```

Try it online!

---
Tags: code-golf, grid, path-finding, puzzle-solver
---


# Question
Title: Generating a random alphanumeric string of length N
What is the shortest way of generating a random string with a given length and with only alphanumeric characters allowed?

* example of a random string: with N = 9 output would be `aZua7I0Lk`
* the given length N can be assumed to be always greater than 0
* if necessary you can assume 256 as a maximum value for N, but solutions with higher limits for N and still having a fast computation time are preferred
* allowed characters: 0-9, a-z and A-Z
* a character can occur more than once in the output string
* each possible string should be equally likely (to the accuracy of your language's random number generator)

# Answer
> 5 votes
# Jelly, 4 bytes

```
ØBṗX

```

Try it online!

## Explanation

```
ØBṗX
ØB     All letters (uppercase and lowercase) and digits
  ṗ    Cartesian power with {the input}
   X   Select a random possibility

```

Cartesian power basically generates all list of a given length that can be formed out of a given set of elements; that's exactly what we need here.

# Answer
> 13 votes
# Taxi, 2577 bytes

```
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:n 1 l 1 l 1 r.[a]Go to Heisenberg's:n 1 r 1 r 3 r.Pickup a passenger going to Cyclone.Go to Go More:n 1 l 3 l 3 l.Go to Starchild Numerology:e 2 r.62 is waiting at Starchild Numerology.Pickup a passenger going to Cyclone.Go to Cyclone:e 1 l 2 r.Pickup a passenger going to What's The Difference.Pickup a passenger going to Divide and Conquer.Pickup a passenger going to Divide and Conquer.Go to Divide and Conquer:n 2 r 2 r 1 r.Pickup a passenger going to Trunkers.Go to Trunkers:e 1 r 3 r 1 l.Pickup a passenger going to Multiplication Station.Go to Cyclone:w 2 r.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:s 1 l 2 r 4 l.Pickup a passenger going to What's The Difference.Go to What's The Difference:n 2 l 1 r 3 l.Pickup a passenger going to Addition Alley.Go to Starchild Numerology:e 1 r 3 l 2 r.1 is waiting at Starchild Numerology.63 is waiting at Starchild Numerology.Pickup a passenger going to Addition Alley.Pickup a passenger going to The Underground.Go to Addition Alley:e 1 l 2 r 3 r 1 r.Pickup a passenger going to Joyless Park.Go to Writer's Depot:n 1 l 1 l.ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789- is waiting at Writer's Depot.Pickup a passenger going to Chop Suey.Go to Joyless Park:n 3 r 2 r 2 l.Go to Chop Suey:w 1 r 1 r 1 l.[b]Pickup a passenger going to Narrow Path Park.Go to Narrow Path Park:n 1 l 1 r 1 l.Go to The Underground:e 1 r.Switch to plan "c" if no one is waiting.Pickup a passenger going to The Underground.Go to Fueler Up:s.Go to Chop Suey:n 3 r 1 l.Switch to plan "b".[c]Go to Joyless Park:n 1 r.Pickup a passenger going to The Underground.Go to Narrow Path Park:w 1 r 3 l.[d]Pickup a passenger going to KonKat's.Go to KonKat's:e 1 r.Pickup a passenger going to KonKat's.Go to The Underground:s.Switch to plan "e" if no one is waiting.Pickup a passenger going to The Underground.Go to Fueler Up:s.Go to Narrow Path Park:n 4 l.Switch to plan "d".[e]Go to KonKat's:n.Pickup a passenger going to Riverview Bridge.Go to Riverview Bridge:n 1 l.Go to Narrow Path Park:e 1 l 1 r.Pickup a passenger going to Post Office.Go to Post Office:e 1 r 4 r 1 l.Go to Sunny Skies Park:s 1 r 1 l 1 r.Pickup a passenger going to The Underground.Go to The Underground:n 1 r 1 r 2 r.Switch to plan "f" if no one is waiting.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:n 3 l 2 l 1 l.Switch to plan "a".[f]

```

Try it online!

Taxi is *super* not made for this but you can do it! I'll try to explain what's happening below the un-golfed version.

```
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to Sunny Skies Park.
Go to Sunny Skies Park: north 1st left 1st left 1st right.
[a]
Go to Heisenberg's: north 1st right 1st right 3rd right.
Pickup a passenger going to Cyclone.
Go to Go More: north 1st left 3rd left 3rd left.
Go to Starchild Numerology: east 2nd right.
62 is waiting at Starchild Numerology.
Pickup a passenger going to Cyclone.
Go to Cyclone: east 1st left 2nd right.
Pickup a passenger going to What's The Difference.
Pickup a passenger going to Divide and Conquer.
Pickup a passenger going to Divide and Conquer.
Go to Divide and Conquer: north 2nd right 2nd right 1st right.
Pickup a passenger going to Trunkers.
Go to Trunkers: east 1st right 3rd right 1st left.
Pickup a passenger going to Multiplication Station.
Go to Cyclone: west 2nd right.
Pickup a passenger going to Multiplication Station.
Go to Multiplication Station: south 1st left 2nd right 4th left.
Pickup a passenger going to What's The Difference.
Go to What's The Difference: north 2nd left 1st right 3rd left.
Pickup a passenger going to Addition Alley.
Go to Starchild Numerology: east 1st right 3rd left 2nd right.
1 is waiting at Starchild Numerology.
63 is waiting at Starchild Numerology.
Pickup a passenger going to Addition Alley.
Pickup a passenger going to The Underground.
Go to Addition Alley: east 1st left 2nd right 3rd right 1st right.
Pickup a passenger going to Joyless Park.
Go to Writer's Depot: north 1st left 1st left.
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789- is waiting at Writer's Depot.
Pickup a passenger going to Chop Suey.
Go to Joyless Park: north 3rd right 2nd right 2nd left.
Go to Chop Suey: west 1st right 1st right 1st left.
[b]
Pickup a passenger going to Narrow Path Park.
Go to Narrow Path Park: north 1st left 1st right 1st left.
Go to The Underground: east 1st right.
Switch to plan "c" if no one is waiting.
Pickup a passenger going to The Underground.
Go to Fueler Up: south.
Go to Chop Suey: north 3rd right 1st left.
Switch to plan "b".
[c]
Go to Joyless Park: north 1st right.
Pickup a passenger going to The Underground.
Go to Narrow Path Park: west 1st right 3rd left.
[d]
Pickup a passenger going to KonKat's.
Go to KonKat's: east 1st right.
Pickup a passenger going to KonKat's.
Go to The Underground: south.
Switch to plan "e" if no one is waiting.
Pickup a passenger going to The Underground.
Go to Fueler Up: south.
Go to Narrow Path Park: north 4th left.
Switch to plan "d".
[e]
Go to KonKat's: north.
Pickup a passenger going to Riverview Bridge.
Go to Riverview Bridge: north 1st left.
Go to Narrow Path Park: east 1st left 1st right.
Pickup a passenger going to Post Office.
Go to Post Office: east 1st right 4th right 1st left.
Go to Sunny Skies Park: south 1st right 1st left 1st right.
Pickup a passenger going to The Underground.
Go to The Underground: north 1st right 1st right 2nd right.
Switch to plan "f" if no one is waiting.
Pickup a passenger going to Sunny Skies Park.
Go to Sunny Skies Park: north 3rd left 2nd left 1st left.
Switch to plan "a".
[f]

```

**Start: Get stdin**
Pick up the stdin value as text, convert it to a number, and go stick it somewhere to wait.

**Plan A Part 1: Get a random integer 1-62**
Get a random integer and then get `62` as a number. Duplicate both the random integer and the `62` because we'll need them later. You can only carry 3 passengers at once so we end up with `rand`, `rand`, and `62`. (The other `62` will wait around until we get back.) Go divide `rand` by `62` and truncate the result to get an integer. Go back to get the other copy of `62` and multiply it by the truncated integer from the division. Finally, subtract the product from the first copy of `rand`. This gives us a number 0-61. Now we have to go back to pickup a `1` and add it to the result to get a number 1-62. Yes, all those many lines of text are just `mod(rand(),62)+1`.

**Plan A Part 2: Create an array of characters from which to choose**
Pickup a string with all the valid characters and also one at the end we don't want (more on that later). The `63` we picked up earlier matches this string length. Take it over to Chop Suey to have it broken into individual passengers.

**Plan B: Move the array so we can select a character**
One by one, move every character over to Narrow Path Park. It's the only stack available and the only way to not have leftover passengers getting in the way. Everything else in Townsburg is FIFO so I would have to go back and clear out all the passengers every iteration of the overall loop. This way, I can just leave them at the park and they'll get pushed out of the way by the 63 new characters every time. The very first `A` is likely to never escape.

**Plan C: Prepare to select a character**
This is really just a few stops that didn't need to be in Plan D. Re-position the taxi in preparation.

**Plan D: Get all the characters we *dont* want**
Starting with the first character in the reversed "array" (this is the 63rd character we don't want), keep picking up and concatenating characters as we count down from the result of the `mod` function in Plan A. Once you hit zero, the next character is the one you want.

**Plan E: Drown the ones you don't want and return the chosen one.**
"\[P\]assengers dropped off at Riverview Bridge seem to always fall over the side and into the river..." Well, that gets rid of that concatenated string of losers. Go pick up the next character and send it to stdout. Finally, let's check how many characters we've printed thus far. Back to Sunny Skies to pick up the stdin value we left so long ago. Subtract one and, if the result is more than zero, send it back to wait and start over again at Plan A.

# Answer
> 7 votes
# C (gcc), ~~57~~ ~~55~~ 52 bytes

Thanks to 2501 for the pointers...

```
i;f(n){for(;n-=isalnum(i=rand()%150)&&putchar(i););}

```

Try it online!

# Answer
> 6 votes
# Jelly, 5 bytes

*Missed a trick - see ais523's 4 byter*

```
ØBX$€

```

**Try it online!**

### How?

```
ØBX$€ - Main link: n
    € - for each in range(n):
   $  -   last two links as a monad:
ØB    -     "base digits" - yields list of chars "01..9AB...Zab...z"
  X   -     random choice

```

# Answer
> 5 votes
# Shell + pwgen, 13 bytes

```
pwgen -s $1 1

```

> -s, --secure
>
> Generate completely random, hard-to-memorize passwords.

### Sample output

```
%pwgen -s 10 1
2cyhLovbfT

```

# Answer
> 5 votes
# Java 8, ~~183~~ ~~149~~ ~~97~~ 88 bytes

```
n->{for(int t;n-->0;t*=Math.random(),System.out.printf("%c",t+=t>9?t>35?61:55:48))t=62;}

```

Try it online.

-9 bytes by porting *@2501*'s C answer, so make sure to upvote him as well!

**Old answer, 97 bytes**

```
n->{for(int t;n-->0;t*=Math.random(),System.out.printf("%c",t>9?(t<36?65:97)+t%26:48+t%10))t=62;}

```

Try it online.

**Explanation:**

```
n->{                           // Method with integer parameter and String return-type
  for(int t;                   //  Temp integer
      n-->0                    //  Loop the input amount of times:
      ;                        //    After every iteration:
       t*=Math.random(),       //     Set `t` to a random integer in the range [0,62)
       System.out.printf("%c", //     Print as character:
         t+=                   //      The random integer, after we've added:
            t>9?               //       If the random integer is larger than 9:
             t>35?             //        If the random integer is larger than 35:
              61               //         Add 61
             :                 //        Else:
              55               //         Add 55
            :                  //       Else:
             48))              //        Add 48
    t=62;}                     //   (Re)set `t` to 62 for the random

n->{for(int t;n-->0;t*=Math.random(),System.out.printf("%c",...))t=62;}
                               // Similar as above
         t>9?                  //      If the random integer is larger than 9:
          (t<36?               //       If the random integer is smaller than 36:
            65                 //        Start with 65 ('A')
           :                   //       Else:
            97)                //        Start with 97 ('a')
               +t%26           //       And add the random integer modulo-26
         :                     //      Else:
          48                   //       Start with 48 ('0')
            +t%10)             //       And add the random integer modulo-10

```

# Answer
> 4 votes
# PowerShell, ~~58~~ 54 Bytes

-4 thanks to Andrei Odegov - casting to a char array instead of looping to create a char array.

```
-join[char[]](65..90+97..122+48..57|random -C "$args")

```

generates a range `1..2+4..5 = 1,2,4,5` of all the acceptable charachter codes, then selects `$args` number of elements randomly using `random -Count` \- the resulting elements ~~are looped through `|%{}` and turned into `[char]`s,~~ are cast to an array of chars using `[char[]]` \- then the whole thing is encapsulated in brackets and `-join`ed together.

```
PS C:\users\sweeneyc\Desktop> .\grstr.ps1 5
oaCE5
PS C:\users\sweeneyc\Desktop> .\grstr.ps1 10
UReh6McG7D
PS C:\users\sweeneyc\Desktop> .\grstr.ps1 30
t1YrhZf5egyzqnPlWUKV3cEoIudMTs

```

Does not work for an input of 0 as `Get-Random` only accepts numbers above 1 for the `-Count` parameter.

# Answer
> 4 votes
## C, 60 bytes

```
r;f(n){for(;n--;)r=rand()%62,putchar(r+=r>9?r>35?61:55:48);}

```

See it work here.

See the distribution here.

It is uniformly distributed, assuming `rand() % 62` produces a uniform distribution. Since 62 usually doesn't evenly divide RAND\_MAX, there is a very small bias.

# Answer
> 4 votes
# Snowman, 58 bytes

```
((}#`""*:48vn58nR|65vn91nR,aC|97vn123nR,aCAsH1AaL#aC*;bR))

```

Try it online!

This is a subroutine that takes an integer as input and returns the random string.

```
((             subroutine
  }            make b, e, g active
  #`           e = input (from +)
  ""*          store an empty string in +
  :            what follows is the block to prepend a random char to +
    48vn58nR|  generate range(48..58) and place in g (need b and e for next step)
    65vn91nR   generate range(65..91) in b
    ,aC|       move g to e, concatenate b and e, and move the result to g
    97vn123nR  generate range(97..123) in b
    ,aC        move g to e, concatenate b and e, keeping the result in b
    AsH        shuffle the array of candidate ASCII codes stored in b
    1AaL       equivalent to 0aAwR - get the first element wrapped in an array
    #aC        retrieve + and prepend the randomly generated character
    *          store back into +
  ;bR          repeat this block e times, where e has been set to the input
))             output is given via +

```

# Answer
> 3 votes
# PHP, 56 Bytes

```
for(;$argn;)ctype_alnum($l=chr(rand()))&&$argn-=print$l;

```

Online Version

ctype\_alnum

# Answer
> 3 votes
# APL (Dyalog Extended), 17 bytes

Full program. Prompts for length.

```
(?⎕⍴62)⊇⎕A,⎕D,⌊⎕A

```

Try it online!

`⎕A` uppercase **A**lphabet

**L**owercased

`⎕D,` prepended by the **D**igits

`⎕A,` prepended by the uppercase **A**lphabet

`(``)⊇` select the following indices from that:

`⍴62` reshape 62 to the following shape:

prompt for a number

`?` random indices in in those ranges

# Answer
> 2 votes
# 05AB1E, 6 bytes

```
FžK.RJ

```

Try it online!

**Explanation**

```
F        # input number of times do
 žK      # push [a-zA-Z0-9]
   .R    # pick one at random
     J   # join to string

```

# Answer
> 2 votes
# Perl 5, 41 bytes

40 bytes of code + `-p` flag.

```
$\.=(a..z,A..Z,0..9)[rand 62]for 1..$_}{

```

Try it online!

`(a..z,A..Z,0..9)` creates an array containing all letters and numbers, `[rand 62]` returns an random element of this array, which is append (`.=`) to `$\`, which is implicitly printed at the end thanks to `-p` flag with `}{`.

---

Or, for the same bytecount, but using the parameters rather than the standart input:

```
print+(a..z,A..Z,0..9)[rand 62]for 1..pop

```

Try it online!

# Answer
> 2 votes
# JavaScript (ES6), ~~61~~ ~~54~~ ~~39~~ ~~52~~ 64 bytes

This is almost like reverse-golf! Took a big hit on the byte count ensuring that the full range of characters from all three groups would be used.

```
f=n=>n--?btoa(String.fromCharCode(Math.random()*248))[0]+f(n):""

```
* 15 bytes saved (at one stage) thanks to Arnauld's suggestion of using a recursive function.

---

## Try it

```
f=n=>n--?btoa(String.fromCharCode(Math.random()*248))[0]+f(n):""
i.addEventListener("input",_=>o.innerText=f(+i.value))
```

```
<input id=i type=number><pre id=o>
```

# Answer
> 2 votes
## R, 54 52 51 49 bytes

```
intToUtf8(sample(c(65:90,97:122,48:57),scan(),T))

```

Explanation:

1. Read input integer *n*: `scan()`
2. Vector with ASCII values: `c(65:90,97:122,48:57)`
3. Sample *n* ASCII values with replacement: `sample(c(65:90,97:122,48:57),scan(),T)`
4. Transform ASCII values to a character string with `intToUtf8`

# Answer
> 2 votes
# R, 51 bytes

Same length as the other R answer, but a different approach.

```
cat(sample(c(letters,LETTERS,0:9),scan(),T),sep="")

```

`letters` and `LETTERS` both are built-in variables containing all lower and uppercase letters respectively. Adding `0:9` to that and we have the entire set of alphanumeric characters.

# Answer
> 2 votes
## Alice, 24 bytes

```
/w9u"Uz;r
\0.rdao"ki@/t&

```

Try it online!

This layout is already a lot better than what I originally had (32 bytes), but I'm sure it's not optimal yet...

### Explanation

```
/      Reflect to SE. Switch to Ordinal.
       The IP now bounces diagonally up and down through the code.
09     Append 0 and 9 to an (implicit) empty string to create "09".
r      Range expansion, turns the string into "0123456789".
"az"   Push this string.
r      Range expansion, turns it into the lower-case alphabet.
i      Read all input as a string.
/      Reflect to E. Switch to Cardinal.
t      Implicitly convert the input string to the integer value N it
       contains and decrement it.
&      Run the next command N-1 times.
       The IP wraps around to the first column.
\      Reflect to NE. Switch to Ordinal. (This is not a command.)
w      Push the current IP address to the return address stack N-1
       times. This starts a loop whose body will run N times.
  .      Duplicate the lower-case alphabet.
  u      Convert it to upper case.
  d      Push the concatenation of all values on the stack. This pushes
         a single string with digits, lower-case and upper-case alphabet.
  U      Random choice. Pick a character from this string uniformly at random.
  o      Print it.
  ;      Discard the upper-case alphabet, because it will be regenerated
         in the next loop iteration (and if we leave it, then upper-case
         letters will become more and more likely as the output grows).
k      As long as there is still an address on the return address stack,
       jump back to that address (i.e. to the w). Once the return address
       stack has been depleted, this does nothing and the loop is exited.
@      Terminate the program.

```

# Answer
> 2 votes
# Python + exrex, 81 bytes

```
import exrex,random
lambda n:random.choice(list(exrex.generate("[A-Za-z0-9]"*n)))

```

# Answer
> 2 votes
# Python 2, 79 83 79 bytes

```
import random as r,string as s;lambda x:''.join(r.sample(s.printable[:62]*x,x))

```

+4 bytes (didn't account for repetition)

-4 bytes (Thanks to @Rod for the suggestion for using `printable[:62]`)

# Answer
> 2 votes
# Bash, 43 bytes

```
shuf -ern$1 {a..z} {A..Z} {0..9}|tr -d "\n"

```

Try it online!

# Answer
> 2 votes
# Pip, 13 bytes

```
LaORCz.AZ.J,t

```

Try it online!

### Explanation

```
               a is cmdline arg; t is 10; z is lcase alphabet; AZ is ucase (implicit)
La             Do the following, a times:
  O             Output (without newline)
   RC           random choice from:
     z           Lowercase letters
      .AZ        concatenated with uppercase letters
         .J,t    concatenated with range(10) joined into a string

```

# Answer
> 2 votes
# Zsh, 33 bytes

```
tr -dc a-zA-Z0-9</*/ur*|head -c$1

```

Try it online!

# Answer
> 2 votes
# Thunno 2 `J`, 4 bytes

```
ıkȦɼ

```

Try it online!

#### Explanation

```
ıkȦɼ  # Implicit input
ı     # Input number of times:
 kȦ   #  Push [a-zA-Z0-9]
   ɼ  #  Random choice
      # Implicit output

```

# Answer
> 2 votes
# Swift, ~~138~~ ~~127~~ ~~124~~ 115 bytes

```
var s={String((1...$0).map{_ in"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".randomElement()!})}

```

# Answer
> 1 votes
# Pyth, ~~7~~ 11 bytes

```
O^s++rG1GUT

```

Try it online

Explanation

```
O^s++rG1GUT
    +rG1G      Take the uppercase and lowercase alphabets.
   +     UT    Add it to the list [0, ..., 9].
  s            Concatenate to get a string.
 ^         Q   Get all strings of length N.
O              Choose one at random.

```

# Answer
> 1 votes
# MATL, 8 bytes

```
8Y2iT&Zr

```

Try it online!

```
8Y2      % Push string '012...89ABC...YZabc...yz'
i        % Input N
T&Zr     % Sample with replacement. Implicitly display

```

# Answer
> 1 votes
# Brachylog, 14 bytes

```
~l{Ạụ:Ạ:Ịcṛ}ᵐc

```

Try it online!

### Explanation

```
~l                 Create a list of length Input
  {        }ᵐ      Map on each element of that list:
   Ạụ:Ạ:Ịc           The string "A…Za…z0…9"
          ṛ          Pick a character at random
             c     Concatenate into a single string

```

# Answer
> 1 votes
## Batch, 175 bytes

```
@set s=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
@for /l %%i in (1,1,%1)do @call :c
@echo %s:~62%
:c
@set/an=%random%%%62
@call set s=%s%%%s:~%n%,1%%

```

`s` performs double duty here as it contains both the alphanumeric list and the randomly selected characters. After printing the result the code falls through to the subroutine whose result is ignored.

# Answer
> 1 votes
# Pyke, 4 bytes

```
~JfH

```

Try it online!

```
~J   -   "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  f  -  cominbations(^, length=input)
   H - random.choice(^)

```

# Answer
> 1 votes
## C, 67 Bytes

```
c;f(n){char b[1],*p=b+64;for(;n;)isalnum(c=*p++)?putchar(c),n--:0;}

```

Try it online

I'm getting some strange results - keep on hitting the run button - feels like I'm a character in Lost:

```
PoPPmyE79hmy
arcPaTasITJK
PCFaniHSAKPS
yPytyxQoAKMA
DOPrgDONeDO8
...

```

Can anyone explain why there is always a 'P' or 'p' in the output?

# Answer
> 1 votes
# C# - 121 bytes

```
void g(int n){Console.Write(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(new Random().Next().ToString())).Substring(0,n));}

```

# Answer
> 1 votes
# Ruby, 47 bytes

```
->n{([*?a..?z,*?A..?Z,*?0..?9]*n).sample(n)*''}

```

Try it online!

# Answer
> 1 votes
# Sinclair ZX81/Timex TS1000/1500 BASIC, ~63 tokenized BASIC bytes

```
 1 INPUT N
 2 IF NOT N THEN STOP
 3 FOR N=SGN PI TO N
 4 PRINT CHR$ (CODE "A"+RND*26);
 5 NEXT N

```

There are no lower-case characters in ZX81 without using assembly or having some sort of UDG ROM or something, and for the time being, it only outputs `A-Z`. If zero is entered then the program halts and returns to direct mode.

# Answer
> 1 votes
# Japt, ~~12~~ 8 bytes

```
;BiCí)öU

```

Try it

# Answer
> 1 votes
# PHP, 51 bytes

```
while($argn-=ctype_alnum($c=chr(rand()))&&print$c);

```

Run as pipe with `-nR` or try it online.

# Answer
> 1 votes
# 05AB1E, 4 bytes

```
žKãΩ

```

Try it online! Times out on TIO for inputs \\$\>3\\$, but it does work in theory.

```
žKãΩ  # full program
   Ω  # random element from...
žK    # "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"...
  ã   # to the cartesian power of...
      # implicit input
      # implicit output

```

# Alternative, 4 bytes

```
žLãΩ

```

Try it online!

```
žLãΩ  # full program
   Ω  # random element from...
žL    # "zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA9876543210"...
  ã   # to the cartesian power of...
      # implicit input
      # implicit output

```

# Answer
> 1 votes
# Javascript, 83 bytes

```
f=n=>n?f(--n)+String.fromCharCode((k=Math.random()*62|0)+(k<10?48:(k<36?87:29))):''

```

Explained:

```
f=n=>  //Define function, n =  string length
n?      // if n is not falsy (0)
f(--n)+ //return f(n-1) (1 char shorter) plus
String.fromCharCode( // the character of
(k=Math.random()*62|0) //random number between 0 and 62 (num of chars)
+(
k<10?          //plus, if k < 10 (char is number)
48             //k + 48
:(k<36?        //else, if k < 36 (char is lowercase)
87             //k + 87
:29)           // else k + 29
)
)
:''   //if n is falsy, return empty string.

```

The numbers (48,29,etc) come from lining the charcodes up: |char|num|charcode|num - charcode| | - | - | - | - | | 0 | 0 | 48 | 48 | | 1 | 1 | 49 | 48 | | ... | ... | ... | ... | | 9 | 9 | 57 | 48 |

So random + 48 for numbers. For lowercase,

| char | num | charcode | num - charcode |
| --- | --- | --- | --- |
| a | 10 | 97 | 87 |
| b | 11 | 98 | 87 |
| ... | ... | ... | ... |
| z | 35 | 122 | 87 |

so rand + 87, and for uppercase, |char|num|charcode|num - charcode| | - | - | - | - | | A | 36 | 65 | 29 | | B | 37 | 66 | 29 | | ... | ... | ... | ... | | Z | 61 | 90 | 29 |

# Answer
> 1 votes
# PowerShell, 56 bytes

```
param($n)-join((0..9+'a'..'z'+'A'..'Z')*$n|random -C $n)

```

Try it online!

# Answer
> 1 votes
# Vyxal, 18 bits<sup>v2</sup>, 2.25 bytes

```
krƈ

```

Try it Online!

What can I say, there's a built-in for choosing n random characters from a string.

## Explained

```
krƈ
  ƈ  # Choose n random characters from
kr   # the string 0-9a-zA-Z

```

# Answer
> 1 votes
## Google Sheets, 106 bytes

```
=REDUCE(,SEQUENCE(N),LAMBDA(s,_,s&SORTN({ROW(1:9);CHAR(ROW(65:90));CHAR(ROW(97:122))},1,,RANDARRAY(61),)))

```

# Answer
> 1 votes
# Scala 3, 123 bytes

A port of @Kevin Cruijssen's Java answer in Scala.

---

Golfed version. Attempt This Online!

```
n=>{var t=62;for(_<-0 to n-1){t=(t*scala.math.random).toInt;if(t>9)t+=(if(t>35)61 else 55)else t+=48;print(t.toChar);t=62}}

```

Ungolfed version. Attempt This Online!

```
object Main {
  trait N {
    def c(n: Int): Unit
  }

  val n: N = (n: Int) => {
    var t = 62
    for (_ <- 0 until n) {
      t = (t * scala.math.random()).toInt
      if (t > 9) t += (if (t > 35) 61 else 55) else t += 48
      print(t.toChar)
      t = 62
    }
  }

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to 3) {
      n.c(5)
      println()
      n.c(10)
      println()
      n.c(20)
      println()
      n.c(33)
      println()
      println()
    }
  }
}

```

# Answer
> 1 votes
# Ruby `-rsecurerandom`, 32 bytes

```
->n{SecureRandom.alphanumeric n}

```

Attempt This Online!

# J-uby `-rsecurerandom`, 26 bytes

```
:alphanumeric&SecureRandom

```

Attempt This Online!

# Answer
> 0 votes
# Stacked, 33 bytes

```
:>[alpha 10:>ALPHA,,''#`randin]"!

```

Try it online! Takes input from the top of the stack and leaves output on the top of the stack.

```
:>[alpha 10:>ALPHA,,''#`randin]"!
:>                                  range from 0 to n-1
  [                           ]"!   on each, do:
   alpha                            push "abc...xyz"
         10:>                       push (0 1 2 ... 8 9)
             ALPHA                  push "ABC...XYZ"
                  ,,                concat twice
                    ''#`            join by nothing
                        randin      select random member in it

```

# Answer
> 0 votes
# C#, ~~214~~ 177 bytes

Sorry to embarrass myself like this but:

```
void q(){int k=int.Parse(Console.ReadLine());Random r=new Random();for(;k>0;k--){Console.Write((char)(r.Next(1,4)>2?r.Next(1,3)>1?r.Next(97,123):r.Next(48,58):r.Next(65,91)));}}}}

```

Shaved some bytes off due to suggestion to just make it a function.

# Answer
> 0 votes
# Python 3, ~~132~~ ~~124~~ 123 bytes

...I most probably can golf this further. ~~Might be able to do that by using ASCII numbers.~~ Tried and ended up longer than Java.

```
from random import*
a='abcdefghijklmnopqrstuvwxyz0123456789'
f=lambda n:''.join(choice(a+a[:-10].upper())for i in range(n))

```

Try it online!

# Answer
> 0 votes
## Mathematica 66 Bytes

```
""<>Cases[1~CharacterRange~122,_?LetterQ|_?DigitQ]~RandomChoice~#&

```

which is a little bit shorter than using the `WordCharacter` pattern with `StringCases`

# Answer
> 0 votes
# Lua, ~~105~~ 98 bytes

```
s,n="",io.read()while#s<n do c=s.char(math.random(48,122))s=s..(c:match"%w"and c or'')end print(s)

```

Generate any character between 48 and 122, if alphanumeric, add to output string. When output string is length n, stop and output.

Edit: Saved 7 bytes thanks to suggestions from Josh.

# Answer
> 0 votes
## CJam, 18 bytes

```
ri{;'],_el^9,+mR}%

```

Explanation:

```
ri   e# Read integer
{    e# For each (loops from 0..n-1):
 ;   e#   Delete the index from the top of the stack
 '], e#   Get all the characters 0x00 to 0x5b ("[")
 _el e#   Duplicate and convert letters to lowercase
 ^   e#   Symmetric set difference - this keeps only
     e#     uppercase and lowercase letters
 A,+ e#   Add all the digits into this string
 mR  e#   Random choice of one element in the array
}%   e# End for loop
e# Implicit output

```

# Answer
> 0 votes
# C, ~~54~~ 52 bytes

* -2 bytes, thanks to @RosLuP

**Try Online**

```
i;f(n){n&&f(n-(isalnum(i=rand()%128)&&putchar(i)));}

```

# Answer
> 0 votes
## Clojure, 80 bytes

```
#(apply str(for[i(range %)](char(rand-nth(mapcat range[48 97 65][57 122 90])))))

```

I guess the only smart part is building that set of ASCII integer values.

# Answer
> 0 votes
# Axiom, 150 bytes

```
f(x:NNI):Union(String,Complex INT)==(x>9.E8=>%i;c:=alphanumeric()::String;r:="";repeat(x=0=>break;x:=x-1;w:=1+random()@INT rem 62;r:=concat(c.w,r));r)

```

i find repeat( ...break...) the most versatile type of loop in Axiom as for(;;) in C. I find functions without some think or reflection on their input only danger toys

```
   [0,""]
   [1,"t"]
   [2,"rT"]
   [10,"fcCOgd2aoP"]
   [100,
    "byFH5ikoQTIEA3TdJ4thNueA0vuowxz5PC7N1yUEgZUkuddjfwbRjYMim1mAYzLhZ8hDJskOUZ
    SckbflbU1ZL2q0KTWUMF9dx6jX"
     ]
   [10000000000000000,%i]

```

# Answer
> 0 votes
# APL NARS, 65 bytes, 35 chars

```
{(⍵≤0)∨⍵≥1E6:''⋄t[?¨⍵⍴⍴t←⎕A,⎕a,⎕D]}

```

As usual here do not is specificied the range of validity for the function... I agree in check for range but not agree 100% in checking the type, because some time is possible one extention for one function (possible not in this case). Test:

```
  g←{(⍵≤0)∨⍵≥1E6:''⋄t[?¨⍵⍴⍴t←⎕A,⎕a,⎕D]}
  g ¯2000000

  g 0

  g ¯3

  g 23
86uSfWH1zfpj4JE439he9Jp
  g 3
ueQ
  g 2
l3
  g 1
M
  g 100
pkHi07YmFmZpr9TpUNCIEtQf20CURGszkP2LvzgpnfaZTKPg3nYvo4PK0Rg
  1cMxcjSRGWLrtf1RP8NEC3HlIcjW6TqfSOdqmrSqu

```

# Answer
> 0 votes
# Alchemist, ~~577~~ 689 bytes

Contains a line for every character `[0-9A-Za-z]`:

```
_->In_n
n->Out_"0"
...
n->Out_"9"
n->Out_"A"
...
n->Out_"Z"
n->Out_"a"
...
n->Out_"z"

```

Input from *stdin*, try it online!

## Explanation

The *universe* of Alchemist will start with one `_`-atom, so the only thing that can happen is to read the number of `n`-atoms. Then one of the remaining rules will be matched pseudo-uniformly at random until no `n`-atoms remain.

# Answer
> 0 votes
# Uiua <sup>SBCS</sup>, 26 bytes

```
⊏⌊×62∵⋅⚂⊚:⊂+@0⇡10⊂⌵.+@a⇡26

```

Try it!

```
⊏⌊×62∵⋅⚂⊚:⊂+@0⇡10⊂⌵.+@a⇡26
                    +@a⇡26  # lowercase alphabet
                 ⊂⌵.        # join uppercase alphabet
          ⊂+@0⇡10           # join digits
        ⊚:                  # create array of length n
     ∵⋅⚂                    # fill with random numbers in [0, 1)
  ×62                       # times 62
 ⌊                          # floor
⊏                           # select

```

---
Tags: code-golf, string, number, random, alphabet
---


title: Generate a "GitHub" Avatar

text:
# Question
Title: Generate a "GitHub" Avatar
### Background / Description

Note: as @HelkaHomba points out, the actual GitHub identicons *are not actually random but based on the hash of a username*

The default GitHub avatar is a 5x5-pixel image. A color is picked randomly, and then random pixels are filled in on one side (right or left, 2x5 size) using that color. Then that side is copied & flipped to the other side, across the y-axis. The pixels left over that are not filled in are #F0F0F0, or rgb(240,240,240).

The center column's pixels (1x5 size) are then randomly filled in, using the same color as previously.

### Output

*Note: for this challenge we will ignore the space that encloses the GitHub avatars*

The program should output a 5x5 pixel image file. See http://meta.codegolf.stackexchange.com/a/9095/42499 for specifics

### Examples

*Note: these were obviously scaled up from 5x5 so you can see them*

Good luck!

# Answer
> 12 votes
# Pyth - 27 bytes

```
.wC+Kc3O^Cm,240O256 3 15_PK

```

Obviously doesn't work online, but you can have it print color codes here.

# Answer
> 10 votes
# Perl 5 \+ `-M5.10.0`, 77 bytes

**This solution only has a 256 colour palette.**

```
sub x{".[48;5;@{[rand>.5?$-||=rand 254:254]}m "}say$}=x,$b=x,x,$b,$}for 0..4
```

Try it online!

### Explanation

Nothing particularly clever except perhaps:

* Use `$-` to automatically round the colour number for use in the escape sequence, used instead of `$n=0|rand 254`.

# Answer
> 9 votes
# MATL, ~~36~~ 29 bytes

```
5l$rtP+!kllII$r*O16tQ/XE'a'YG

```

This saves the result in file `a.png`.

Replacing `'a'` by `2` in the code displays the image (scaled up) instead of saving a file:

```
5l$rtP+!kllII$r*O16tQ/XE2YG

```

Here's an example output:

### Explanation

```
5l$r     % 5×5 matrix of independent random values with uniform distribution
         % on the interval (0,1)
tP+!     % Duplicate, flip vertically, add, transpose. This gives a horizontally
         % symetric matrix. Center column pixels are uniformly distributed on the
         % interval (0,2). Rest have a triangular distribution on (0,2)
k        % Round down. In either of the above cases, this gives 0 and 1
         % with the same probability
llII$r   % 1×1×3 array of independent random numbers with uniform distribution
         % on (0,1). This is the foreground color.
*        % Multiply the two arrays with broadcast. Gives a 5×5×3 array. Ones in the
         % 5×5 array become the random foreground color. Zeros remain as zeros.
O        % Push 0
16tQ/    % 16, duplicate, add 1, divide: gives 16/17, or 240/255
XE       % Replace 0 by 16/17: background color
'a'      % Push file name
YG       % Write image to that file

```

# Answer
> 7 votes
## Actually, 53 bytes

```
3'≡*;╗`┘#8╙r-J┌`MΣ╝5`3"2rJ└"£n3╟;RdX+Σ`nkΣ"P6 5 5 255

```

Try it online!

Actually is bad at string processing. I think I've mentioned that before. This program outputs a P6 netpbm image using CP437, like the following:

```
P6 5 5 255
εεεεεεå♠ƒεεεεεεå♠ƒå♠ƒεεεå♠ƒå♠ƒεεεεεεεεεεεεεεεεεεεεεå♠ƒεεεεεεå♠ƒå♠ƒå♠ƒå♠ƒå♠ƒ

```

This can be converted to a PNG using ImageMagick:

```
seriously -f prog.srs | convert - out.png

```

Scaled up PNG version:

Explanation:

```
3'≡*;╗`┘#8╙r-J┌`MΣ╝5`3"2rJ└"£n3╟;RdX+Σ`nkΣ"P6 5 5 255
3'≡*                                                   push "≡≡≡" (char 240, 3 times)
    ;╗                                                 save a copy to reg0
      `┘#8╙r-J┌`M                                      map:
       ┘#                                                cp437 char code, as list ([240])
         8╙r-J                                           random value in range(2**8) that is not 240
              ┌                                          char code
                 Σ╝                                    concatenate, push to reg1
                   5`3"2rJ└"£n3╟;RdX+Σ`n               do this 5 times:
                     3"2rJ└"£n                           do this 3 times:
                       2rJ└                                randomly pick 0 or 1, push the value in that register
                              3╟                         push the top 3 items to a list
                                ;RdX+                    duplicate, reverse, discard first value, append (mirror the list)
                                     Σ                   concatenate
                                       kΣ              push stack as list, concatenate
                                         "P6 5 5 255   prepend header

```

# Answer
> 6 votes
## Python, ~~167~~ ~~164~~ ~~155~~ 148 bytes

Output as ppm

```
from random import*
print"P3 5 5 255"
C,P=choice,[[240]*3,[randint(0,255)for _ in"RGB"]]
exec"a,b=C(P),C(P);print' '.join(map(str,a+b+C(P)+b+a));"*5

```
* Edit1: `range(5)` to `" "*5`
* Edit2: shoved a byte at the first `print`
* Edit3: Replaced list comprehension with `map` since only `str(p)` was used
* Edit4: `exec""*5` instead `for _ in " "*5:`

Some improvement over old, string-based code:

```
from random import*
print "P3 5 5 255"
j,c,a=' '.join,choice,['']*5
P=["240 "*3,j([str(randint(0,255))for _ in"RGB"])]
for _ in a:a=[c(P)]*5;a[1]=a[3]=c(P);a[2]=c(P);print j(a)

```

# Answer
> 6 votes
## Mathematica, ~~105~~ ~~102~~ ~~98~~ 94 bytes

```
c=1~RandomReal~3;r@l_:={c,4{4,4,4}/17}~RandomChoice~{l,5};Image[Join[#,r@1,Reverse@#]&@r@2]

```

is the Transpose operator.

Edit 1: Saved 3 bytes by replacing `Round` \+ `RandomReal` with `RandomInteger`

Edit 2: Saved 4 bytes by replacing `RandomInteger` with `RandomChoice`

Edit 3: Saved 4 bytes by replacing `RandomColor` and `GrayLevel` with `RandomReal`

# Answer
> 5 votes
## MATLAB, 102 bytes

Hi, this is my matlab solution:

```
p=@(x)(imwrite(floor(randi(2,5,2)*[eye(2) ones(2,1)./2 fliplr(eye(2))]),[0.9412*[1 1 1];rand(1,3)],x))

```

The input `x` of the function is the name of the output file. For example:

```
p('output.png')

```

produces a png image called 'output.png'.

Here the results of some executions of this code.

# Answer
> 5 votes
# Swift 2.3, ~~593~~ 585 bytes

```
var t = 0,g = UIGraphicsGetCurrentContext(),c = UIColor(hue:CGFloat(drand48()),saturation:1,brightness:1,alpha:1).CGColor
srand48(time(&t))
UIGraphicsBeginImageContext(CGSizeMake(5,5))
for x in 0..<3 {for y in 0..<5 {CGContextSetFillColorWithColor(g,drand48()>0.5 ? c : UIColor.whiteColor().CGColor)
var r = [CGRect(x:x,y:y,width:1,height:1)]
if x<2 {let m = x==0 ? 4 : 3;r.append(CGRect(x:m,y:y,width:1,height:1))}
CGContextFillRects(g,&r,r.count)}}
let i = UIGraphicsGetImageFromCurrentImageContext()
UIImagePNGRepresentation(i)!.writeToURL(NSURL(string:"/a/a.png")!,atomically:true)

```

**Update**

# Swift 3, 551 bytes

```
var t = 0,g = UIGraphicsGetCurrentContext()!,c = UIColor(hue:CGFloat(drand48()),saturation:1,brightness:1,alpha:1).cgColor
srand48(time(&t))
UIGraphicsBeginImageContext(CGSize(width:5,height:5))
for x in 0..<3 {for y in 0..<5 {g.setFillColor(drand48()>0.5 ? c : UIColor.white().cgColor)
var r = [CGRect(x:x,y:y,width:1,height:1)]
if x<2 {let m = x==0 ? 4 : 3;r.append(CGRect(x:m,y:y,width:1,height:1))}
g.fill(&r,count: r.count)}}
let i = UIGraphicsGetImageFromCurrentImageContext()!
try!UIImagePNGRepresentation(i)!.write(to: URL(string:"/a/a.png")!)

```

I'm at WWDC and just got the Xcode 8 beta with Swift 3. Apple made some of the CoreGraphics calls more "Swifty," and I am able to reduce the bytecount.

Swift 2 code Ungolfed:

```
var t = 0
srand48(time(&t))

UIGraphicsBeginImageContext(CGSizeMake(5,5))
let context = UIGraphicsGetCurrentContext()
let color = UIColor(hue: CGFloat(drand48()),saturation:1,brightness:1,alpha:1).CGColor

for x in 0..<3 {
    for y in 0..<5 {
        CGContextSetFillColorWithColor(context, drand48() > 0.5 ? color : UIColor.whiteColor().CGColor)
        var rects = [CGRect(x:x,y:y,width:1,height:1)]

        if x < 2 {
            let mirror = x==0 ? 4 : 3
            rects.append(CGRect(x: mirror, y: y, width: 1, height: 1))
        }

        CGContextFillRects(context, &rects, rects.count)
    }
}

let image = UIGraphicsGetImageFromCurrentImageContext()
UIImagePNGRepresentation(image)!.writeToURL(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory,inDomains:.UserDomainMask).first!.URLByAppendingPathComponent("a.png"), atomically:true)

```

This answer assumes UIKit is available and uses the Cocoa Touch framework.

Some example output images:

I know I can't compete with most of the other answers but I wanted to give this a shot as a personal challenge. There is definitely room for improvement with this answer, but I think it will be hard to get this down below a few hundred bytes due to the length of the UIKit and CoreGraphics image writing method names. I opted to write an actual PNG file rather than PPM values as an exercise for myself, but shorter answers would definitely be possible if I used the PPM format.

I already start out as a loss by having to declare a variable to seed `srand48` with `time`. I chose this over `arc4random()` or `arc4random_uniform()` because ultimately I would lose more bytes with those. I seed the rng to use `drand48` to generate a random color and pick when to write a color to a pixel.

`CGSize` vs `CGSizeMake` and `CGRect` vs `CGRectMake`:

I switch between the inline C API functions and their Swift extensions to find the shortest constructor for each. `CGSizeMake` ends up being shorter than `CGSize()`, and `CGRect`ends up being shorter than `CGRectMake()`:

```
CGSizeMake(5,5)
CGSize(width:5,height:5)

CGRect(x:x,y:y,width:1,height:1)
CGRectMake(CGFloat(x),CGFloat(y),1,1)

```

I would have to create `CGFloat`s `x` and `y` due to the nature of the for loop. I'm really not thrilled with the 2D loop and if equality checks, but I was really struggling to find a shorter way. There's definitely room to shave off a few bytes here.

Calling `CGContextFillRects` with an array of `CGRect` structs is cheaper than calling `CGContextFillRect` twice with two different values, so I save a few bytes with the array and pointer.

I also save 27 bytes by not calling `UIGraphicsEndImageContext()`. While this would normally be a "bug" in production code, it's not necessary for this toy program.

Colors:

Colors are also a pain to deal with, since I'm creating `UIColor` objects but need to write a `CGColor` opaque type to each pixel. The shortest code I found to create a random color was to use the `UIColor` constructor and get the `CGColor` from that `UIColor`. Same with white. If I were using the Cocoa framework instead of Cocoa Touch, I might be able to save some bytes using `CGColorGetConstantColor()`, but unfortunately that method is unavailable in the Cocoa Touch SDK.

Writing to to file:

Writing to a file takes almost 100 bytes. I'm not sure how to even go about optimizing this. On some systems depending on your permissions, you may need to use the Documents directory which would be even longer:

```
UIImagePNGRepresentation(i)!.writeToURL(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory,inDomains:.UserDomainMask).first!.URLByAppendingPathComponent("a.png"), atomically:true)

```

Definitely open to further optimizations.

**Edit 1:** Saved a few bytes by rearranging some variable declarations.

# Answer
> 4 votes
# Dyalog APL, ~~43~~ 42 bytes

~~`'P3',5 5 256,∊(3⍴240)(?3⍴256)[⌈(⊢+⌽)?5 5⍴0]`~~

`'P3',5 5a,∊(3⍴240)(?3⍴a←256)[⌈(⊢+⌽)?5 5⍴0]`

Right to left:

`?5 5⍴0` generates a 5×5 matrix of random numbers between 0 and 1 (but never 0 or 1)

`(⊢+⌽)` is a train that adds the matrix with its reflection

ceiling, returns 1 or 2 for each element

`(3⍴240)(?3⍴256)` colours - white-ish and a random one

`[ ]` use each element of the matrix as an index in colours

`'P3',5 5 256,∊` flatten and add header

# Answer
> 2 votes
## PHP, 236 bytes

I know this is an old challenge but I just like to challenge myself.

```
$o=imagecreate(5,5);$t=imagecolorallocate;$r=rand;for($c=[$t($o,240,240,240),$t($o,$r(0,255),$r(0,255),$r(0,255))];$y++<5;)for($x=-2,$a=[];$x<3;)imagesetpixel($o,$x+2,$y,isset($a[$v=abs($x++)])?$a[$v]:($a[$v]=$c[$r(0,1)]));imagepng($o);

```

Ungolfed:

```
// Store these frequently used functions
$t=imagecolorallocate;
$r=rand;

// Create 5x5 image
$o=imagecreate(5, 5);

// Define array of the possible colors
$c=[$t($o,240,240,240),$t($o,$r(0,255),$r(0,255),$r(0,255))];

// Loop over y axis
for($y=0;$y++<5;) {

    // This stores values for colors used in the current row indexed by the absolute value of x starting from -2
    $a = [];

    // Loop over x axis
    for($x=-2;$x<3;) {

        // Set a pixel of a random color for current coordinate. If it exists in the array, use the array value.
        imagesetpixel($o,$x+2,$y, isset($a[$v=abs($x++)]) ? $a[$v] : ($a[$v]=$c[rand(0,1)]) );
    }

    // Empty the array
    $a = [];
}

// Output as PNG
imagepng($o);

```

Sample Output:

# Answer
> 2 votes
# Javascript ES6, 296 bytes

*Note:* does not produce a file, draws to a canvas.

See it in action in this JS Fiddle.

```
s=20;W='#fff';M=Math;R=M.random;ctx=document.getElementById('c').getContext('2d');cr=`#${M.floor(R()*16777215).toString(16).slice(0,3)}`;f=Array(5).fill();a=f.map((_,i)=>f.map((_,j)=>R()*2|0));a.map((c,x)=>c.map((v,y)=>{ctx.fillStyle=y>=3?c[y==3?1:0]?cr:W:c[y]?cr:W;ctx.fillRect(y*s,x*s,s,s);}));

```

# Answer
> 2 votes
# Uiua SBCS, ~~36~~ 35 bytes

```
&ims≡⍉⍉⊂⇌↘1.⊏⁅⊞⋅⋅⚂⊚3⊚5⊟⚂_⚂_⚂▽3 0.94

```

Try it!

```
&ims≡⍉⍉⊂⇌↘1.⊏⁅⊞⋅⋅⚂⊚3⊚5⊟⚂_⚂_⚂▽3 0.94
                            ▽3 0.94  # gray color
                       ⚂_⚂_⚂         # random color
                      ⊟              # couple
             ⁅⊞⋅⋅⚂⊚3⊚5               # random 3x5 binary matrix
            ⊏                        # select
        ⇌↘1.                         # duplicate, drop first row, reverse
       ⊂                             # join
    ≡⍉⍉                              # rotate image
&ims                                 # display image

```

# Answer
> 1 votes
# Ruby, 132 bytes

Outputs a PPM image.

```
c=(1..3).map{rand 256}
puts"P3 5 5 255",(1..15).map{rand 2}.join.gsub(/(..)./){$&+$1.reverse}.gsub(/./){($&==?0?c:["240"]*3)*" "+$/}

```

Attempt This Online!

---
Tags: code-golf, graphical-output, random
---


# Question
Title: Output first \$n\$ digits of \$\pi^{1/\pi}\$
This challenge is to produce the shortest code for the constant \\$\pi^{1/\pi}\\$. Your code must output the first \\$n\\$ consecutive digits of \\$\pi^{1/\pi}\\$, where \\$n\\$ is given in the input. **Alternatively**, your program may accept no input, and output digits indefinitely

This is code golf, so the shortest submission (in bytes) wins except that it must output the 1000 digits for \\$n = 1000\\$ in less than 10 seconds on a reasonable PC.

You may not use a built-in for \\$\pi\\$, the gamma function or any trigonometic functions.

If the input is \\$n = 1000\\$ then the output should be:

```
1.439619495847590688336490804973755678698296474456640982233160641890243439489175847819775046598413042034429435933431518691836732951984722119433079301671110102682697604070399426193641233251599869541114696602206159806187886346672286578563675195251197506612632994951137598102148536309069039370150219658973192371016509932874597628176884399500240909395655677358944562363853007642537831293187261467105359527145042168086291313192180728142873804095866545892671050160887161247841159801201214341008864056957496443082304938474506943426362186681975818486755037531745030281824945517346721827951758462729435404003567168481147219101725582782513814164998627344159575816112484930170874421446660340640765307896240719748580796264678391758752657775416033924968325379821891397966642420127047241749775945321987325546370476643421107677192511404620404347945533236034496338423479342775816430095564073314320146986193356277171415551195734877053835347930464808548912190359710144741916773023586353716026553462614686341975282183643

```

Note the 1000 decimal places includes the first \\$1\\$.

**Output format**

Your code can output in any format you wish.

This related question tackles a simpler variant but with the same restrictions.

**Notes**

If it's helpful, you can assume \\$\pi^{1/\pi}\\$ is irrational and in fact you can even assume it is a Normal number.

# Answer
# Python, 149 bytes

*Saved one byte due to @H.PWiz.*

```
k=n=int(input())+1
i=j=8*n
e=l=p=z=10**n
while i:p=2*z-i//2*p//~i;i-=2
q=z-z*z//p
while j:l=q//j+q*l//z;j-=1
while k:e=z+e*l//k//p;k-=1
print(e//100)

```

Try it online!

Input *n = 1000* finishes in less than 0.5s.

\\$\sqrt\[\pi\]{\pi}\\$ is calculated as the \\$e^\frac{\ln(\pi)}{\pi}\\$.\\$\pi\\$ is calculated with the usual Euler-Leibniz: \\$\pi=\sum\_{n=0}\limits^{\infty}{\frac{n!}{(2n+1)!!}}\\$.

\\$e^x\\$ and \\$\ln(x)\\$ are both computed using a Taylor series: \\$e^x=\sum\limits\_{n=0}^{\infty}{\frac{x^n}{n!}}\\$ and \\$\ln(1-x)=-\sum\limits\_{n=1}^{\infty}{\frac{x^n}{n}}\\$. Because the iteration for \\$\ln(x)\\$ converges only when \\$|x|\<1\\$, this is instead calculated as \\$\ln(\pi)=-\ln(\frac{1}{\pi})\\$.

Given that Python uses Karasuba Multiplication, the overall runtime complexity is \\$\mathcal{O}(n^{1+\log\_2(3)})\\$ \- in other words, twice as many digits will take approximately 6 times as long.

---

### Subquadratic Complexity

```
import sys
from gmpy2 import isqrt, mpz

def piks(a, b):
  if a == b:
    if a == 0:
      return (1, 1, 1123)
    p = a*(a*(32*a-48)+22)-3
    q = a*a*a*24893568
    t = 21460*a+1123
    return (p, -q, p*t)
  m = (a+b) >> 1
  p1, q1, t1 = piks(a, m)
  p2, q2, t2 = piks(m+1, b)
  return (p1*p2, q1*q2, q2*t1 + p1*t2)

n = int(sys.argv[1])-1
m = n*20//3
z = mpz(10)**n

# n / log(777924, 10)
pi_terms = mpz(n*0.16975227728583067)

pp, pq, pt = piks(0, pi_terms)
pq *= 3528

pi2m = (pq << m) // pt

a, b = 2 << m, 8
while a != b:
  a, b = (a + b) >> 1, isqrt(a*b)

mlog2_pi = (z << m) // a

a, b = 2*pi2m, 8
while a != b:
  a, b = (a + b) >> 1, isqrt(a*b)
logpi_pi = z * pi2m // a - mlog2_pi

mlog2 = mlog2_pi * pq // pt

d = e = (15044673 << m) // 10450451
pt //= z
while d:
  a, b = 2*e, 8
  while a != b:
    a, b = (a + b) >> 1, isqrt(a*b)
  lnx = (pq * e) // (pt * a) - mlog2
  d = e * (lnx - logpi_pi) // z
  e -= d

print(e * z >> m)

```

Try it online!

Input *n = 20000* finishes in less than one second.

\\$\pi\\$ can be computed in subquadratic time by use of Karatsuba splitting a.k.a. Fast E-function Evaluation, which reduces a summation to *n* terms to a single rational value *p/q*, splitting in binary descent. I've chosen to use Ramanujan #39, which is the fastest converging series of its kind that doesn't require an arbitrary precision square root, to my knowledge. Explicitly, this is computed as:

\\$\large{\left.{3528}\middle/{\sum\limits\_{n=0}^{\infty}\frac{(-1)^n (4n)! (1123+21460n)}{(n!)^4 14112^{2n}}}\right.}\\$

For \\$\ln(x)\\$ and \\$e^x\\$, using the same technique wouldn't provide any benefit, because both are computed as a power series of an arbitrary precision variable. Fortunately, Gauss has gifted us with an elegant quadratically converging formula for \\$\ln(x)\\$, based on the Arithmetic-Geometric Mean:

\\$\DeclareMathOperator{\AGM}{AGM}\large\ln(x)=\lim\limits\_{n\rightarrow\infty}\frac{\pi x^n}{2n\AGM(x^n,4)}\\$

or, in cases when large powers of *x* are inconvenient, this can also be computed as:

\\$\large\ln(x)\approx\frac{\pi x 2^m}{2\AGM(x 2^m,4)}-m\log(2)\\$

Conveniently, division by \\$\pi\\$ can be acheived simply by not multiplying through by \\$\pi\\$.

With the natural logarithm thusly defined, \\$e^\frac{\ln(\pi)}{\pi}\\$ can be computed via Newton's method on \\$x\_{n+1}=x\_n-x\_n(\ln(x\_n)-\frac{\ln(\pi)}{\pi})\\$. The overall complexity is then \\$\mathcal{O}(n^\*\log^3(n))\\$, where \\$n^\*\\$ will vary with the complexity of the multiplication algorithm GMP is using for any given bit length.
> 14 votes

# Answer
# Wolfram Language (Mathematica), 62 bytes

In my first try I used Zeta function but this one uses the imaginary part of ln(-1) for pi. (@someone)
Prints more than 4000 digits in the first 10 seconds,

```
q=Im@Log@-1;Do[Print@RealDigits[N[q^(1/q),2k]][[1,k]],{k,∞}]

```

Try it online!

*9 bytes saved from @someone*
> 3 votes

# Answer
# Wolfram Language (Mathematica), ~~23~~ 22 bytes

```
(p=Log@-1/I)^p^-1~N~#&

```

Try it online!

<sup>-1 byte by @someone — the use and reuse of `p` beats the pure function</sup>

Taking a lot of inspiration from @J42161217 and displaying n digits instead of an infinite stream.

Note that I'm using `ToString` in Tio to suppress the trailing precision specifier in the output, which does not appear when this code is executed in Mathematica.

Maybe using `180°` for pi would work; but maybe that's too close to being trigonometric and is disallowed.
> 2 votes

# Answer
# AXIOM, 221 bytes

```
m(k)==(v:=8.*k;(4/(v+1)-2/(v+4)-1/(v+5)-1/(v+6))*16^-k)
p(n:PI):String==(d:=digits(n+9);e:=10.^-digits();i:=s:=0;repeat(k:=m(i);k<e=>break;s:=s+k;i:=i+1);r:=concat split((s^(1/s))::String,char " ");digits(d);r.(1..(n+1)))

```

test and ungolf:

```
(3) -> p 1000
   (3)
  "1.43961949584759068833649080497375567869829647445664098223316064189024343948
  91758478197750465984130420344294359334315186918367329519847221194330793016711
  10102682697604070399426193641233251599869541114696602206159806187886346672286
  57856367519525119750661263299495113759810214853630906903937015021965897319237
  10165099328745976281768843995002409093956556773589445623638530076425378312931
  87261467105359527145042168086291313192180728142873804095866545892671050160887
  16124784115980120121434100886405695749644308230493847450694342636218668197581
  84867550375317450302818249455173467218279517584627294354040035671684811472191
  01725582782513814164998627344159575816112484930170874421446660340640765307896
  24071974858079626467839175875265777541603392496832537982189139796664242012704
  72417497759453219873255463704766434211076771925114046204043479455332360344963
  38423479342775816430095564073314320146986193356277171415551195734877053835347
  93046480854891219035971014474191677302358635371602655346261468634197528218364
  3"
                                                             Type: String
           Time: 0.03 (IN) + 0.53 (EV) + 0.25 (OT) + 0.15 (GC) = 0.97 sec

-- Bailey-Borwein-Plouffe formula for pi
-- https://en.m.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula
--       +oo
--      -----          --                                      --
--      \          1   |     4         2         1         1    |
--   pi= |      -------|  ------- - ------- - ------- - ------- |
--      /            k |   8*k+1     8*k+4     8*k+5     8*k+6  |
--      ----- k   16   --                                      --
--        0
m(k)==(v:=8.*k;(4/(v+1)-2/(v+4)-1/(v+5)-1/(v+6))*16^-k)
p(n:PI):String==
      d:=digits(n+9); e:=10.^-digits(); i:=s:=0
      repeat
          k:=m(i)
          k<e=>break
          s:=s+k;i:=i+1
      r:=concat split((s^(1/s))::String,char " ")
      digits(d)
      r.(1..(n+1))

```

the function m calculate the term of the sum; the p() function loop, sum them in the variable s until the term is \< than min float value (one can see as epsilon); p() function return one string of that number pi^(1/pi); it seems the required digits are returned in less than 1 second for input to p() function 1000.
> 2 votes

# Answer
# APL(NARS), 114 chars

```
r←Q w;m;i;d;e;k;⎕FPC
⎕FPC←4×w+←8⋄m←i←0v⋄e←÷10v*w
k←1+8×i⋄m+←d←(+/4 2 1 1÷k,-k+3..5)÷16*i⋄i+←1⋄→2×⍳e<∣d⋄r←¯9↓w⍕m*÷m

```

If it is allowed to use one function that can return π my solution is

# APL(NARS), 27 chars

```
{⎕FPC←5×⍵+←8⋄¯9↓⍵⍕r*÷r←○1x}

```

Because function for show the number make the rounding, it is possible one error in the last digits. But for happen that there would be the number 99999999 in the digits before where to cut

test

```
  990↓Q 1000
975282183643
  Q 90
1.43961949584759068833649080497375567869829647445664098223316064189024343948917584781977504
  Q 91
1.439619495847590688336490804973755678698296474456640982233160641890243439489175847819775046
  ⎕FPC
128

```

note that ⎕FPC is not changed outside the function f.
> 1 votes

# Answer
# APL(NARS), 159 chars

```
r←Q w;m;i;d;e;k;⎕FPC
⎕FPC←4×w⋄m←i←0v⋄e←÷10v*w
k←1+8×i⋄m+←d←(+/4 2 1 1÷k,-k+3..5)÷16*i⋄i+←1⋄→2×⍳e<∣d⋄r←m*÷m

D←{k←{m←⍵⍕Q⍵⋄'123'∊⍨m[≢m]:⍵⋄∇⍵+1}⍵⋄⍵-←1⋄(⍵-k)↓k⍕Q k}

```

This would be the bullet proof solution...

Q w function would calculate the number π^(1/π) enough for have w digits after point.

{m←⍵⍕Q⍵⋄'123'∊⍨m\[≢m\]:⍵⋄∇⍵+1} w function would calculate the number z≥w in the way the last printed digits in z⍕Q z is in the set '123'. If it is in that set than the string result in z⍕Q z has to be right the digits in position ..w..(z-1)

D w function would cut in the right point w-1 from the string z⍕Q z

```
  D 90
1.439619495847590688336490804973755678698296474456640982233160641890
  24343948917584781977504
  D 91
1.439619495847590688336490804973755678698296474456640982233160641890
  243439489175847819775046
  990↓D 1000
975282183643

```

In my opinion if r is the input and P it is as ⍕ but not use any round, (r-1)P Q r return **always** the right result. If i make it wrong this is the P function, you show I'm wrong

```
r←a P w;⎕ct;s;y;k;b
   ⎕ct←0⋄s←''⋄→B×⍳∼w<0⋄s←'¯'⋄w←-w
B: y←⌊w×10x*a⋄b←''
C: b,←10∣y⋄→C×⍳0<y←⌊y÷10⋄k←≢r←⎕D[1+⌽b]⋄→D×⍳∼a=0⋄r←s,r⋄→0
D: →F×⍳∼0≥y←k-a⋄r←s,'0.',('0'⍴⍨-y),r⋄→0
F: r←s,(y↑r),'.',y↓r

```
> 0 votes

---
Tags: code-golf, sequence, pi, restricted-time
---


title: Draw a Gameboy Tile

text:
# Question
Title: Draw a Gameboy Tile
## Description

The Gameboy stores tiles as 2 bit-per-pixel 8x8 images, thus 16 bytes. Every two bytes is a complete row with all of the Low-bits of each pixel in the first byte, and all of the High-bits of each pixel in the second.

## Input

Input will be exactly 16 bytes, received through Standard IO in one of the following forms:

* Array of bytes or strings
* 16 byte string

Per the Standard IO, these may be in a language convenient form (Deliminated string, on the stack, etc.)

## Output

An image, Rendered or Saved, of the Gameboy Tile.

Scale and Aspect Ratio of each pixel is not fixed.

Each 2 bit colour of the Pallet may be anything so long as the Manhattan Distance of the RGB256 representation is atleast 48. Eg. `#FFFFFF, #AAAAAA, #555555, #000000`. Traditionally, although not a requirement, `00` is the lightest colour, and `11` is the darkest.

## Examples

`[FF, 00, 7E, FF, 85, 81, 89, 83, 93, 85, A5, 8B, C9, 97, 7E, FF]`

`[7C, 7C, 00, C6, C6, 00, 00, FE, C6, C6, 00, C6, C6, 00, 00, 00]`

## Final Notes

* Standard Loopholes apply
* An online demo, and more in-depth explanation of the implementation can be found HERE
* This is , so fewest bytes wins! (The Gameboy only had 65536 bytes of Address Space, after all!)
* Have Fun!

# Answer
# MATL, 13 bytes

```
8&B1L&Y)E+1YG

```

Inputs an array of bytes, and displays an image. The image consists of grey colours where `00` corresponds to black and `11` to white.

Try it at MATL Online!

### How it works

```
8&B    % Implicit input: 1×16 array. Convert to binary with 8 bits.
       % Gives a 16×8 array
1L     % Push [1 2 j]. As an index, this is interpreted as 1:2:end
&Y)    % Two-ouput row indexing. This gives an 8×8 subarray with the
       % indicated rows, and an 8×8 subarray with the remaining rows
E      % Multiply by 2, element-wise
+      % Add. This gives an 8×8 array with possible values 0, 1, 2, 3
1YG    % Display as an image with scaled colors, using the default
       % grey colormap

```
> 8 votes

# Answer
# Gameboy machine code, 257 bytes

```
00000000  f0 44 fe 90 38 fa 3e e4  e0 47 21 90 81 1a 22 13  |.D..8.>..G!...".|
00000010  1a 22 13 1a 22 13 1a 22  13 1a 22 13 1a 22 13 1a  |."..".."..".."..|
00000020  22 13 1a 22 13 1a 22 13  1a 22 13 1a 22 13 1a 22  |".."..".."..".."|
00000030  13 1a 22 13 1a 22 13 1a  22 13 1a 22 18 fe 00 00  |..".."..".."....|
00000040  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
*
000000d0  00 00 00 00 00 00 00 00  ff 00 7e ff 85 81 89 83  |..........~.....|
000000e0  93 85 a5 8b c9 97 7e ff  00 00 00 00 00 00 00 00  |......~.........|
000000f0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000100  c7                                                |.|
00000101

```

Generated by this RGBASM assembly:

```
DEF rLY EQU $ff44
DEF rBGP EQU $ff47

SECTION "0",ROM0[0]
WaitVBlank:
    ldh a, [rLY]
    cp 144
    jr c, WaitVBlank

    ld a, %11100100    ; set background palette
    ldh [rBGP], a

    ld hl, $8190    ; override the tile data for the (R) icon
    REPT 15
        ld a, [de]
        ld [hli], a
        inc de
    ENDR
    ld a, [de]
    ld [hli], a
    jr @

SECTION "Input Data",ROM0[$d8]
DB $ff, $00, $7e, $ff, $85, $81, $89, $83, $93, $85, $a5, $8b, $c9, $97, $7e, $ff

SECTION "Entrypoint",ROM0[$100]
    rst 0    ; jump to reset vector 0

```

You can compile this code with rgbds: `rgbasm tile.asm -o - | rgblink - -o tile.gb`.

A gameboy ROM is usually at least 16K, so some emulators don't support this, but sameboy executes it with no problem. The entrypoint of the ROM, after the boot ROM executed is 0x100, so I don't think it can be any smaller.

As per the IO rules, Assembly programs may read input from some specified memory location, in this case `0xd8`, which is conveniently the value of the `de` register when the boot ROM exits.
> 26 votes

# Answer
# , 41 bytes

```
load'viewmat'
[:viewmat 2#._2|:@|.\#:@dfh

```

Try it online - fails because TIO can't run viewmat

Working link that outputs a matrix of integers 0 thru 3

Takes input as an array of hex strings.

* Convert each hex string to a binary number
* Take then in rows of two, reverse and transpose and convert back decimal
* View the resulting matrix as an image

Image produced when running the function locally:
> 9 votes

# Answer
# Shell + rgbds devkit, 16 bytes

```
rgbgfx -r1 -o- -

```

Takes raw bytes from stdin and outputs a png on stdout. rgbgfx is the graphics conversion program from the RGBDS Gameboy Development Kit, intended to convert PNGs to Gameboy tile data, and vice-versa.
> 8 votes

# Answer
# , 65 bytes

```
\(a)image(t((b=outer(rev(a),2^(7:0),`%/%`)%%2)[!1:0,]+2*b[!0:1]))

```

Don't attempt This Online; instead, Try it at rdrr.io with graphical output (uses `function` instead of `\` due to older version of R installed at rdrr.io).

Note that this could be 7 bytes shorter by omitting the `image()` call and outputting a matrix of bytes, but R has good graphical output so it seems more in the spirit of the challenge to actually draw the image.
> 7 votes

# Answer
# QBasic, ~~100~~ 96 bytes

```
SCREEN 7
FOR r=0TO 7
INPUT a
INPUT b
FOR c=0TO 7
PSET(7-c,r),a\2^c MOD 2+(1AND b\2^c)*3
NEXT c,r

```

You can try it on Archive.org. Input the bytes one at a time as decimal integers (0 to 255). The image is displayed in the upper left corner of the screen, overwriting the `?` prompt from the first `INPUT` statement. Each "pixel" is 2x2. The colors are:

* Black: rgb(0,0,0)
* Blue: rgb(0,0,170)
* Cyan: rgb(0,170,170)
* Red: rgb(170,0,0)

### Ungolfed

With a less golfy formula for computing the color code, and drawing each pixel as a filled box rather than a single point, it turns out we can reproduce the grayscale images in the OP exactly.

```
SCREEN 7
' Each point in screen mode 7 is 2x2 pixels, so we draw 15x15 boxes to match
' the 30x30 pixel boxes in OP's image
size = 15
FOR row = 0 TO 7
  INPUT lowbits
  INPUT highbits
  FOR col = 0 TO 7
    place = 2 ^ (7 - col)
    lowbit = (lowbits \ place) AND 1
    highbit = (highbits \ place) AND 1
    ' 00 = color 15, white
    ' 01 = color 7, light gray
    ' 10 = color 8, dark gray
    ' 00 = color 0, black
    colorcode = 15 - lowbit * 8 - highbit * 7
    ' Compute top and left coordinates of the box based on row and column
    ' (with the left shifted over to avoid drawing over the inputs)
    top = row * size
    left = 60 + col * size
    ' Draw the box using the LINE command with the BF (box filled) option
    LINE (left, top)-(left + size - 1, top + size - 1), colorcode, BF
  NEXT col
NEXT row

```
> 7 votes

# Answer
# Japt `-R`, ~~17 25~~ 23 bytes

```
m¤ùT8 ò ®yÍ¸Ãi"P2 8 8 3

```

Try it

Saved two bytes thanks to Shaggy

Previously, this answer outputted a string using differently shaded unicode characters to represent the different colors, but as OP has clarified that this is not allowed, it now outputs a Plain PGM file.

Takes input as byte array and outputs a string representing a PGM file.

```
m¤ùT8 ò ®yÍ¸Ãi"P2 8 8 3  : implicit input of byte array
m¤                       : convert each byte to binary
  ùT8                    : left-pad each binary string with 0s
      ò ®                : map each pair of lines to:
         yÍ              :   transpose the pair, map each two-char string to a number
           ¸             :   join by spaces
            Ã            : end map
             i"P2 8 8 3  : prepend the start of a PGM file
                         : -R join by newlines

```

## Japt `-R`, 11 bytes

Outputs a matrix of bytes.

```
m¤ùT8 ò ®yÍ

```
> 6 votes

# Answer
# JavaScript (ES6), 79 bytes

Expects a list of bytes and outputs a matrix of RGB tuples, using the greenish palette `00C000`, `008000`, `004000`, `000000`.

```
a=>(v=[...'01234567']).map(y=>v.map(x=>[0,~a[y*2]<<x>>1&64|~a[y-~y]<<x&128,0]))

```

Try it online!

## 73 bytes

Outputs a matrix of bytes.

```
a=>(v=[...'01234567']).map(y=>v.map(x=>~a[y*2]<<x>>1&64|~a[y-~y]<<x&128))

```

Try it online!

## Rendering

```
f=
a=>(v=[...'01234567']).map(y=>v.map(x=>[0,~a[y*2]<<x>>1&64|~a[y-~y]<<x&128,0]))

F = (id, a) => { m = f(a); m.forEach(r => r.forEach(rgb => { div = document.createElement('div'); div.style.backgroundColor = '#' + rgb.map(v => v.toString(16).padStart(2, '0')).join(''); document.getElementById(id).appendChild(div); })) }

F('b0', [0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF])
F('b1', [0xFF, 0x00, 0x7E, 0xFF, 0x85, 0x81, 0x89, 0x83, 0x93, 0x85, 0xA5, 0x8B, 0xC9, 0x97, 0x7E, 0xFF])
F('b2', [0x7C, 0x7C, 0x00, 0xC6, 0xC6, 0x00, 0x00, 0xFE, 0xC6, 0xC6, 0x00, 0xC6, 0xC6, 0x00, 0x00, 0x00])
F('b3', [0xFF, 0xFF, 0xFF, 0x81, 0xC3, 0x81, 0xDF, 0x85, 0xDF, 0x85, 0xFF, 0xBD, 0xFF, 0x81, 0xFF, 0xFF])
```

```
.box { float:left; margin-right:16px; width:128px; height:128px; } .box div { float:left; width:16px; height:16px; }
```

```
<div id="b0" class="box"></div><div id="b1" class="box"></div><div id="b2" class="box"></div><div id="b3" class="box"></div>
```
> 5 votes

# Answer
# C, ~~108~~ ~~105~~ ~~95~~ ~~93~~ ~~89~~ 85 bytes

```
b;main(j){for(puts("P5 8 8 3");j=j-1?:read(0,&b,2)*4;b+=b)putchar(3^b>>14&2^b>>7&1);}

```

Try it online!

Reads raw bytes from `stdin` and outputs an image in the PGM format to `stdout`.

-17! thanks to @c--
> 5 votes

# Answer
# K (ngn/k), 44 bytes

```
`0:"P2 8 8 3"
2/+,/+'0N 2#-8#'+(8#0),2\.0:`

```

Takes input as a space separated list of integers. Outputs a plain pgm to stdout.

Colors are inverted from the example.
> 3 votes

# Answer
# Charcoal, 36 bytes

```
ＥＥ⁸⮌Ｅ²↨↧Ｓ¹⁶⮌⭆⁸§░▒▓█↨²﹪÷ιＸ²λ²

```

Try it online! Link is to verbose version of code. Now uses @Arnauld's output characters. Explanation:

```
  ⁸                             Literal integer `8`
 Ｅ                              Map over implicit range
     ²                          Literal integer `2`
    Ｅ                           Map over implicit range
        Ｓ                       Next input hex digit pair
       ↧                        Lowercased
      ↨  ¹⁶                     Converted from base `16`
   ⮌                            Reversed
Ｅ                               Map over each pair of hex values
             ⁸                  Literal integer `8`
            ⭆                   Map over implicit range and join
               ░▒▓█             Literal string
              §                 Indexed by
                       ι        Current pair
                      ÷         Vectorised divided by
                         ²      Literal integer `2`
                        Ｘ       Raised to power
                          λ     Current value
                     ﹪     ²    Vectorised modulo `2`
                   ↨²           Converted from base `2`
           ⮌                    Reversed
                                Implicitly print

```

Note that the deverbosifier on TIO erroneously uselessly quotes the special characters inside `”y` and ; this is not actually necessary for correct operation of the program.

32 bytes by taking the input bytes with `0x` prefix using the newer version of Charcoal on ATO:

```
ＥＥ⁸⮌Ｅ²Ｎ⮌⭆⁸§░▒▓█↨²﹪÷ιＸ²λ²

```

Attempt This Online! Link is to verbose version of code.
> 2 votes

# Answer
# JavaScript, 105 bytes

```
v=>{for(i=0;i<8;++i)for(j=0;j<8;++j)window['c'+i+(7-j)].className='wldb'[2*(b=n=>v[2*i+n]>>j&1)(0)+b(1)]}

```

Try it:

```
f=v=>{for(i=0;i<8;++i)for(j=0;j<8;++j)window['c'+i+(7-j)].className='wldb'[2*(b=n=>v[2*i+n]>>j&1)(0)+b(1)]}

button.addEventListener('click', _=>f(input.value.split` `.map(x=>+('0x'+x))));
```

```
.f {
  border: 1px solid black;
  width: fit-content;
}

.r {
  display: flex;
}

[id^="c"] {
  width: 40px;
  height: 40px;
  background-color: lightblue;
}

input {
  width: 320px;
}

.w {
  background-color: #fff;
}

.l {
  background-color: #555;
}

.d {
  background-color: #aaa;
}

.b {
  background-color: #000;
}
```

```
<input id="input" value="7C 7C 00 C6 C6 00 00 FE C6 C6 00 C6 C6 00 00 00">
<button id='button'>Draw</button>
<br><br>
<div class="f">
<div class="r">
  <div id="c00"></div><div id="c01"></div><div id="c02"></div><div id="c03"></div><div id="c04"></div><div id="c05"></div><div id="c06"></div><div id="c07"></div>
</div>
<div class="r">
  <div id="c10"></div><div id="c11"></div><div id="c12"></div><div id="c13"></div><div id="c14"></div><div id="c15"></div><div id="c16"></div><div id="c17"></div>
</div>
<div class="r">
  <div id="c20"></div><div id="c21"></div><div id="c22"></div><div id="c23"></div><div id="c24"></div><div id="c25"></div><div id="c26"></div><div id="c27"></div>
</div>
<div class="r">
  <div id="c30"></div><div id="c31"></div><div id="c32"></div><div id="c33"></div><div id="c34"></div><div id="c35"></div><div id="c36"></div><div id="c37"></div>
</div>
<div class="r">
  <div id="c40"></div><div id="c41"></div><div id="c42"></div><div id="c43"></div><div id="c44"></div><div id="c45"></div><div id="c46"></div><div id="c47"></div>
</div>
<div class="r">
  <div id="c50"></div><div id="c51"></div><div id="c52"></div><div id="c53"></div><div id="c54"></div><div id="c55"></div><div id="c56"></div><div id="c57"></div>
</div>
<div class="r">
  <div id="c60"></div><div id="c61"></div><div id="c62"></div><div id="c63"></div><div id="c64"></div><div id="c65"></div><div id="c66"></div><div id="c67"></div>
</div>
<div class="r">
  <div id="c70"></div><div id="c71"></div><div id="c72"></div><div id="c73"></div><div id="c74"></div><div id="c75"></div><div id="c76"></div><div id="c77"></div>
</div>
</div>
```
> 2 votes

# Answer
# Nibbles, 20.5 bytes (41 nibbles)

```
"P2 8 8 3 ".`/~.$``@hex:1$>>/$!@@~++

```

Input is an array of hex strings; output is a plain PGM image file (inspired by pan's answer).

```
"P2 8 8 3 "                 # prepend the string "P2 8 8 3 " onto:
    .                       # map over
     $                      # the input:
            :1$             #   prepend a '1'
         hex                #   then get the hex value
      ``@                   #   convert to bits
 `/                         # get chunks of 2
.                           # and map over these:
                 /$         #   fold across each chunk of 2
                   !@@      #   zipping-together the 2 elements
                      ~+    #   by adding together
                        +   #     the first elements added to themselves
                            #     and the second elements
               >>           #   and remove the first element

```

---

Note that if output as a matrix of bytes would be valid, we could drop the initial `"P2 8 8 3 "` header for the plain PGM format, for just 13 bytes.
> 2 votes

# Answer
# Thunno `N`, \\$ 30 \log\_{256}(96) \approx \\$ 24.69 bytes

```
b8zK2ApeZt.JBA_sjE"P2 8 8 3"ZN

```

Attempt This Online!

Port of ~~Jacob~~ *noodle man*'s Japt answer.

*-3 characters thanks to noodle man*

#### Explanation

```
b           # Convert each number in the (implicit) input list to binary
 8zK        # Fill each with zeros to length 8
    2Ap     # Split the list into pairs
       e    # Map over this list of pairs:
        Zt  #  Transpose the pair
.J          #  And join each inner list into a string
  B         #  Convert each string from binary
   A_sj     #  And join this list of strings by spaces
       E    # (End map)
"..."ZN     # Prepend the string "P2 8 8 3"
            # Implicit output, joined on newlines

```
> 2 votes

# Answer
# Vyxal, ~~26~~ 21 bytes

```
bṅvṅ2ẇv∩vvB883f‛P2pp⁋

```

Try it Online!

Uses roughly the same method as my Japt answer. I have tried a lot of different things but I can't find a 20-byter. With Vyncode this is 17 bytes but I'm not the biggest fan of that.

Takes input as a list of bytes, outputs a Plain PGM file.

Explanation:

```
bṅvṅ2ẇv∩vvB883f‛P2pp⁋
b                      # Convert to list of binary digits
 ṅ                     # join each to a string
  vṅ                   # pad each binary string to length 8 with zeroes
    2ẇ                 # chunks of length 2
      v∩               # transpose each pair to a list of two-bit binary strings
        vvB            # convert each from binary
           883f        # digits of 883
               ‛P2     # string literal “P2”
                  p    # prepend this to digit list
                   p   # prepend this header to the matrix
                    ⁋  # join each item on spaces and then join the items on newlines

```

Created with the help of Luminespire.
> 2 votes

# Answer
# C (GCC), ~~110~~ ~~109~~ 93 bytes

*-16 bytes thanks to @c--*

```
m;main(h){for(;m=m/2?:read(!puts(""),&h,2)*64;)printf("[%dm ",(h&m?39:99)+(h>>8&m?1:8));}

```

Attempt This Online!

Takes the input as a binary array from `stdin`, outputs spaces with different ANSI-colored background.

If the input is longer than 16 bytes, it continues displaying 8-pixel rows (which is incidentally useful for testing).
> 2 votes

# Answer
# Python, ~~526 524 483 471 470 454~~ 447 bytes

I'm a `turtle` veteran. For fast results, use `speed(0)`. Uses the given pallet.

```
def g(l,x=range(8)):
 r=[int(i,16)for i in l];j=[[r[i+1],r[i]]for i in range(0,16,2)]
 for i in x:j[i]=["".join([bin(j[i][0])[2:].zfill(8).replace(" ","0")[k],bin(j[i][1])[2:].zfill(8).replace(" ","0")[k]])for k in x]
 for i in x:
  for l in x:j[i][l]=int(j[i][l],2);j[i][l]="#"+"FA50"[j[i][l]]*6
 for i in j:
  for k in i:seth(0);color(k);begin_fill();exec('fd(9);rt(90);'*4);end_fill();fd(9)
  pu();goto(0,ycor()-9);pd();ht()
from turtle import*

```

Test case 1:

Test case 2:
> 2 votes

# Answer
# Go, ~~304~~ 302 bytes

```
import(."image";c"image/color";d"image/draw";p"image/png";."os")
func f(s[]byte){N,S,R,D,P:=NewUniform,d.Src,Rect,d.Draw,Point{0,0}
T:=NewGray(R(0,0,8,8))
for i:=0;i<8;i++{for l,h,j:=s[2*i],s[2*i+1],0;j<8;j++{D(T,R(j,i,j+1,i+1),N(c.Gray{255-85*(h&128>>6+l&128>>7)}),P,S)
h*=2
l*=2}}
p.Encode(Stdout,T)}

```

Attempt This Online!

Prints the bytes of a PNG to STDOUT.

* -2 bytes by @The Thonnu

### Slightly-Ungolfed Explanation

```
import(."image";c"image/color";d"image/draw";p"image/png";."os")
func f(s[]byte){
N,S,R,D,P:=NewUniform,d.Src,Rect,d.Draw,Point{0,0}
                                      // various variables
T:=NewGray(R(0,0,8,8))                // new 8-bit grayscale, 8x8px
for i:=0;i<8;i++{                     // for each row...
l,h:=s[2*i],s[2*i+1]                  // get the bytes for that row
for j:=0;j<8;j++{                     // for each pixel...
C:=c.Gray{255-85*(h&128>>6+l&128>>7)} // calculate the color.
                                      // yields an inverted color, so `255-x` is needed.
D(T,R(j,i,j+1,i+1),N(C),P,S)          // draw the pixel to the tile
h<<=1;l<<=1}}                         // shift the bytes left to get the next pixel.
p.Encode(Stdout,T)}                   // print the PNG to STDOUT

```
> 2 votes

# Answer
# Befunge-with-graphics, 149 bytes

Takes raw bytes from stdin and creates a window which displays the result.

```
99*:sfcu88803v
v_v#!:-1\~<+p<
$ >       ^
>802p>:2%\2/\01p\:2%\2/\01g2*+3\-89+5v
$    ^$p20_v#:-1g20-1g30\xg30g20f::**<
^$p30_v#:$ <
v-1z<u<
>  #^_@

```

Test case:
> 2 votes

# Answer
# SAS

# 136 - ascii art in Log

This solution uses the idea from Charcoal language with help of special characters: `" ░▒▓"` of "gradient dots", it is 11 bytes, the firs symbol is a space.

The Code:

```
data;input(a b)(:hex2.)@@;do x=1to 8;c=ksubstr(" ░▒▓",1+2*char(put(a,binary8.),x)+char(put(b,binary8.),x),1);put c+(-1)@;end;put;cards;;

```

Input goes between last two semicolons as a string e.g., `FF 00 7E FF 85 81 89 83 93 85 A5 8B C9 97 7E FF`

It allows to use multiple strings at once, so if there are any other test cases I gladly add then to display.

In human readable form it looks like:

```
data;
  input (a b) (:hex2.) @@;
  do x = 1 to 8;
    c = ksubstr(" ░▒▓"
               ,1 + 2*char(put(a, binary8.), x) + char(put(b, binary8.), x)
               ,1);
    put c +(-1) @;
  end;
  put;
cards;
FF 00 7E FF 85 81 89 83 93 85 A5 8B C9 97 7E FF
7C 7C 00 C6 C6 00 00 FE C6 C6 00 C6 C6 00 00 00
;

```

In the log you will see:

```
▒▒▒▒▒▒▒▒
░▓▓▓▓▓▓░
▓    ▒ ▓
▓   ▒ ░▓
▓  ▒ ░▒▓
▓ ▒ ░▒░▓
▓▒ ░▒░░▓
░▓▓▓▓▓▓░
 ▓▓▓▓▓
░░   ░░
▒▒   ▒▒
░░░░░░░
▓▓   ▓▓
░░   ░░
▒▒   ▒▒

```

# 180 = 113+67 - heatmap

Since SAS at its origin stand for Statistical Analysis System let's use "three dimensional" histogram i.e. HeatMap

The code

* part 1)

```
data;input(a b)(:hex2.)@@;y+(-1);do x=1to 8;c=2*char(put(a,binary8.),x)+char(put(b,binary8.),x);output;end;cards;

```
* part 2)

```
;proc sgplot;heatmap x=x y=y/colorresponse=c nxbins=8 nybins=8;run;

```

Input goes between past 1) and 2) as a string e.g., `FF 00 7E FF 85 81 89 83 93 85 A5 8B C9 97 7E FF`

Human readable form looks like:

```
data;
  input (a b) (:hex2.) @@;
  y + (-1);
  do x = 1 to 8;
    c = 2*char(put(a, binary8.), x) + char(put(b, binary8.), x);
    output;
  end;
cards;
FF 00 7E FF 85 81 89 83 93 85 A5 8B C9 97 7E FF
;
proc sgplot;
  heatmap x=x y=y /
    colorresponse=c nxbins=8 nybins=8
  ;
run;

```

The `sgplot` procedure uses its default setup and the output looks like:

Wit some "polishing"

```
proc sgplot noautolegend;
  heatmap x=x y=y /
    colorresponse=c nxbins=8 nybins=8
    colormodel=(lightgrey black);
  xaxis display=none;
  yaxis display=none;
run;

```

the output looks like:

and
> 2 votes

# Answer
# Uiua, 15 bytes

```
÷3°⋯≡⍉↯8_2_8≡⇌⋯

```

Try it

Explanation:

```
≡⇌⋯

```

Convert the input numbers to bits. Automatically pads to 8 bits with 0s, so this gives a 16x8 array. This gives the least-significant-bit first, so we need to then reverse each of the rows.

```
↯8_2_8

```

Reshape the array to 8x2x8. This essentially gives the pairs of rows in the array.

```
≡⍉

```

Transpose each of the rows. This changes the array from 8x2x8 to 8x8x2.

```
°⋯

```

Convert each number back from bits. This gives us an 8x8 array of numbers 0-3.

```
÷3

```

Divide `÷` each number by 3. This gives a matrix of numbers between 0 (black) and 1 (white), which is the format Uiua does images in.
> 2 votes

# Answer
## Clojure, 316 bytes

```
(fn[i](doto(Frame.)(.add(proxy[Panel][](paint[g](dotimes[r 8](dotimes[c 8](.setColor g(((mapv(fn[[l h]](mapv #(Color.({0 0xFFFFFF 1 0xAAAAAA 2 5592405 3 0}(Long/parseLong(str % %2)2)))h l))(partition 2(map #(clojure.pprint/cl-format nil "~8,'0b"%)i)))r)c))(.fillRect g(* c 9)(* r 9)9 9)))))).pack(.setVisible true)))

```

Inputs:

1. `[0xFF, 0x00, 0x7E, 0xFF, 0x85, 0x81, 0x89, 0x83, 0x93, 0x85, 0xA5, 0x8B, 0xC9, 0x97, 0x7E, 0xFF]`
2. `[0x7C, 0x7C, 0x00, 0xC6, 0xC6, 0x00, 0x00, 0xFE, 0xC6, 0xC6, 0x00, 0xC6, 0xC6, 0x00, 0x00, 0x00]`

Outputs:
> 1 votes

# Answer
# Postscript 245 168

Images in Postscript can have 2 bits per pixel, or, more specifically, 2 bits per color component and 1 component (e.g. Grayscale) per sample. However, interpreter expects bytes in data source to constitute a continuous bit stream, not low bits here, high bits there. We'll have to zip bits from each two bytes:

```
currentpagedevice /PageSize get aload pop scale

<FF 00 7E FF 85 81 89 83 93 85 A5 8B C9 97 7E FF>

% 16 byte string on stack here
{not} forall                % 16 bytes
8 8 2 [8 0 0 8 0 0]
{                           % consume by pairs (a, b)
    0                       % accumulator (x)
    0 1 7 {                 % a b x s
        dup dup             % a b x s s s
        1 exch bitshift     % a b x s s m
        dup 5 index and     % a b x s s m bm
        4 1 roll            % a b x bm s s m
            6 index and     % a b x bm s s am
        exch bitshift       % a b x bm s ax
        3 1 roll            % a b x ax bm s
        1 add bitshift      % a b x ax bx
        or or               % a b x
    } for
    3 1 roll pop pop        % x

    dup  256 idiv
    exch 255 and            % 2 bytes

    2 string dup 0 5 -1 roll put
             dup 1 4 -1 roll put
}
image

```

I'll use "16 byte string already on stack" for simplicity as allowed in the OP, though it could have been read from file (e.g. STDIN) or command line. I think it's OK for program size byte count to begin after 1st comment, and then stripped of insignificant whitespace it would be:

```
{not}forall 8 8 2[8 0 0 8 0 0]{0 0 1 7{dup dup 1 exch bitshift dup 5 index and 4 1 roll 6 index and exch bitshift 3 1 roll 1 add bitshift or or}for 3 1 roll pop pop dup 256 idiv exch 255 and 2 string dup 0 5 -1 roll put dup 1 4 -1 roll put}image

```

The very 1st line was not included in count as it just serves to produce more "pleasing" output. Command (`gs` in Linux)

```
gswin64c -q -g200x200 source.ps

```

(again, image size on command line is only for better looking square tile, instead of scaled non-proportionately to A4 (or Letter) default page).

For golfing purposes, long repeatedly used operators could be re-defined as short-named procedures, or entire source compactly written as binary tokens, though result would be not very readable. I have better idea: to produce the same output, let's draw not one 2 ppx image, but **three** 1 ppx image masks to paint with 0.33, 0.66 and 1.0 ink, respectively. Then, e.g., if a bit is set in low-bits byte and I paint this pixel with light-gray, it won't interfere with painting later in dark-gray and/or black (if bit is set in high-bits byte).

```
currentpagedevice /PageSize get aload pop scale

<FF 00 7E FF 85 81 89 83 93 85 A5 8B C9 97 7E FF>

% 16 byte string on stack here
{} forall
16 -1 9 {
    dup index
    exch 1 sub index
    and
} for
23 -1 16 {
    -1 roll
} for
24 -8 roll

2 -1 0 {
    3 div setgray
    8 8 true [8 0 0 8 0 0]
    { 1 string dup 0 4 -1 roll put }
    imagemask
} for

```

I.e.:

```
{}forall 16 -1 9{dup index exch 1 sub index and}for 23 -1 16{-1 roll}for 24 -8 roll 2 -1 0{3 div setgray 8 8 true[8 0 0 8 0 0]{1 string dup 0 4 3 roll put}imagemask}for

```

There is bytes moving around stack instead of bits juggling, which is significantly less cumbersome, and shorter.
> 1 votes

# Answer
# Ruby, 101 bytes

Returns the lines of a PGM file. I'm sure that `each_slice` could be golfed out but I don't feel like it. Could be a byte shorter by removing the splat before `a.map` but I don't like returning a ragged array.

```
->a{["P2 8 8 3",*a.map{("%08b"%_1).chars}.each_slice(2).map{_1.transpose.map{|x|x.join.to_i 2}*" "}]}

```

Attempt This Online!
> 1 votes

# Answer
# Thunno 2 `N`, 22 bytes

```
ḃ8ṛ2ẇıṬ€JḂ;883`P2ƤƤðȷj

```

Try it online!

Port of noodle man's Japt answer.

#### Explanation

```
ḃ8ṛ2ẇıṬ€JḂ;883`P2ƤƤðȷj  # Implicit input
ḃ8ṛ                     # Convert each to binary and pad with zeros to length 8
   2ẇı    ;             # To each chunk of 2:
      Ṭ€J               #  Transpose and join each
         Ḃ              #  Then convert back from binary
           883          # Push 883
              `P2Ƥ      # Prepend "P2"
                  Ƥ     # And prepend this header
                   ðȷj  # Join each inner list on spaces
                        # Implicit output, joined on newlines

```
> 0 votes

---
Tags: code-golf, graphical-output
---


title: Spanning tree of a rectangular grid

text:
# Question
Title: Spanning tree of a rectangular grid
## Background

A spanning tree (Wikipedia) of an undirected graph is a subgraph that is a tree which includes all of the vertices of the original graph. The following is an example of a spanning tree of a 4-by-4 grid graph.

## Task

Given two positive integers `w` and `h`, output **any valid spanning tree of the grid graph** which has `w` vertices horizontally and `h` vertices vertically. There are lots of valid answers; just output one of them. Your code is even allowed to give different outputs across runs, as long as all of them are valid.

## Input and output

The input is two positive integers `w` and `h`.

The output is a representation of a spanning tree. **The output format is restricted to "a list of pairs of numbered vertices"**, in order to prevent various boring answers (as discussed in the sandbox). Also, the vertex numbering should be in **row-major order**, e.g.

```
0 - 1 - 2 - 3
|   |   |   |
4 - 5 - 6 - 7
|   |   |   |
8 - 9 - 10- 11

```

or

```
(0,0) - (0,1) - (0,2) - (0,3)
  |       |       |       |
(1,0) - (1,1) - (1,2) - (1,3)
  |       |       |       |
(2,0) - (2,1) - (2,2) - (2,3)

```

You can choose to use 0-based or 1-based indexing for vertices. Also, you may output nested or flattened arrays.

## Scoring & winning criterion

The standard rules apply. The shortest valid submission in bytes wins.

## Example I/O

### `w=3, h=2`

If you want to output the following graph

```
+-+-+
| |
+ +-+

```

The list-of-vertex-pairs representation will be (using 0-based indexing for example):

```
[(0, 1), (0, 3), (1, 2), (1, 4), (4, 5)]

```

or

```
[((0, 0), (0, 1)),
 ((0, 0), (1, 0)),
 ((0, 1), (0, 2)),
 ((0, 1), (1, 1)),
 ((1, 1), (1, 2))]

```

### `w=1, h=1`

The graph is a single vertex with no edges, and its only spanning tree is the graph itself. Your code should output an empty list (which means no edges).

# Answer
# K (ngn/k), 9 bytes

```
|\'2':+!:

```

Try it online!

this is a composition equivalent to the lambda `{|\'2'+!x}`. the trailing `:` forces `!` (and therefore the whole composition) to be monadic.

```
 !2 3         /odometer
(0 0 0 1 1 1
 0 1 2 0 1 2)
 +!2 3        /flip
(0 0
 0 1
 0 2
 1 0
 1 1
 1 2)
 2':+!2 3     /pairs (sliding window size 2)
((0 0;0 1)
 (0 1;0 2)
 (0 2;1 0)
 (1 0;1 1)
 (1 1;1 2))
 |\'2':+!2 3  /cumulative(\) max(|) each(')
((0 0;0 1)
 (0 1;0 2)
 (0 2;1 2)
 (1 0;1 1)
 (1 1;1 2))

```
> 6 votes

# Answer
# Python 2, 46 bytes

```
lambda w,h:zip(R(w-1)+R(w*h),R(1,w*h))
R=range

```

Try it online!

**49 bytes**

```
lambda w,h:[(i-w**(i>=w),i)for i in range(1,w*h)]

```

Try it online!

Both of these produce a list corresponding to a spanning tree like this (for `w=4, h=3`):

```
0--1--2--3
|  |  |  |
4  5  6  7
|  |  |  |
8  9  10 11

```
> 5 votes

# Answer
# APL (Dyalog Extended), 12 bytesSBCS

Full program. Prompts for `[h,w]` from stdin. Prints pairs of `[y,x]` coordinates.

```
2⍮/,↑⊢∘⌽\↓⍳⎕

```

Try it online!

prompt for numeric input from the console

an array of those dimensions containing the **ɩ**ndices of an array of those dimensions

split into list of rows

`⊢∘⌽\`boustrophedonise

combine rows into matrix

`,` ravel matrix into list

`2⍮/` adjacent pairs (lit. for every overlapping run of 2 elements, juxtapose the 2 elements)
> 3 votes

# Answer
# 05AB1E, ~~12~~ 10 bytes

```
*L©¹<Lì®¦ø

```

-2 bytes by porting *@xnor*'s Python 2 answer, but is 1-based instead. So it will output the graph in this format (i.e. `w=5, h=3`):

```
1--2--3--4--5
|  |  |  |  |
6  7  8  9  10
|  |  |  |  |
11 12 13 14 15

```

Try it online.

**Explanation:**

```
*           # Multiply the (implicit) width and height inputs with each other
 L          # Create a list in the range [1,w*h]
  ©         # Store this list in variable `®` (without popping)
   ¹<       # Push the width-input again, and decrease it by 1
     L      # Create a list in the range [1,w-1]
      ì     # Prepend it in front of the earlier list
       ®    # Push the list [1,w*h] from variable `®` again,
        ¦   # and remove the 1 to make it the range [2,w*h]
         ø  # Zip/transpose to create pairs of the two lists
            # (after which this list of pairs is output implicitly as result)

```

---

**Original 12 bytes answer:**

```
*LIä2Å€R}˜ü‚

```

1-based. Will output the graph in this format (i.e. `w=5, h=3`):

```
1--2--3--4--5
|
6--7--8--9--10
            |
11-12-13-14-15

```

Try it online.

**Explanation:**

```
*             # Multiply the (implicit) width and height inputs with each other
 L            # Create a list in the range [1,w*h]
  Iä          # Split it into the height-input amount of equal-length parts
    2Å€ }     # Apply to every 2nd (index % 2 == 0) item:
       R      #  Reverse the inner list
         ˜    # Then flatten it to a single list of integers again
          ü   # Apply to each overlapping pair of values:
           ‚  #  Pair them together
              # (after which this list of pairs is output implicitly as result)

```
> 2 votes

# Answer
# , 42 bytes

```
function(w,h)cbind(a<-1:(h*w-1),a+w^!a%%w)

```

Try it online!

Creates the spanning graph

```
1-2-3
    |
4-5-6
    |
7-8-9

```

Node `i` is connected to node `i+1` in general, or to node `i+w` if `i` is a multiple of `w`. This corresponds to a connecting node `i` to node `i+w^d` where `d=1` if `i` is a multiple of `w`, and `d=0` otherwise.
> 2 votes

# Answer
# APL (Dyalog Extended), 9 bytes

```
⌈\¨2⍮/,⍤⍳

```

Try it online!

Adám's golfing of my algorithm
> 2 votes

# Answer
# Ruby, ~~44~~ 41 bytes

crossed out 44 is still 44

```
->w,h{(1...w*h).map{|x|[x,x+=x%w<1?w:1]}}

```

Try it online!

1-based solution
> 1 votes

# Answer
# Rockstar, 215 bytes

```
g takes w,h
let j be 0
while j is less than h
let i be 0
while i is less than w
let c be j*w+i
let p be c-1
if i is 0
let p be c-w

if p is as high as 0
say "("+p+"-"+c+")"

build i up

build j up

```

It can be invoked like

```
g taking 3,2

```

with the output as

```
(0-1)
(1-2)
(0-3)
(3-4)
(4-5)

```

you can also try it online!
> 1 votes

# Answer
# Scala 3, 49 bytes

Attempt This Online!

```
(w,h)=>((0 to w-2)++(0 to w*h-1)).zip(1 to w*h-1)

```

The output `IndexedSeq[(Int, Int)])` is corresponding to a spanning tree like this (for w=4, h=3):

```
0--1--2--3
|  |  |  |
4  5  6  7
|  |  |  |
8  9  10 11

```
> 1 votes

# Answer
# JavaScript (V8), 68 bytes

Takes input as `(w)(h)`. Prints pairs of 0-based numbered vertices.

```
w=>g=(h,n=0,p=n)=>((n/w&1?n--:++n)%w?n:n=p+w)<w*h&&g(h,n,print(p,n))

```

Try it online!

Recursively creates the following pattern (here with \\$w=4\\$):

```
 0→ 1→ 2→ 3
          ↓
 4← 5← 6← 7
 ↓
 8→ 9→10→11
          ↓
   … ←14←15

```
> 0 votes

# Answer
# Jelly, 9 bytes

```
×ḶsUÐeFṡ2

```

Explanation:

```
×ḶsUÐeFṡ2 the main and only link, takes the dimensions as input
×         multiply the dimensions
 Ḷ        create the range of 0..h*w-1
  s       split into chunks of length w, I have no idea how does this part refer to w
    Ðe    at even indices
   U      reverse the chunks
      F   flatten
       ṡ2 split in overlapping slices of length 2 (path -> edge list)

```

The tree is actually a snake-like path:

```
01234
98765
ABCDE

```

Try it online!
> 0 votes

# Answer
# Charcoal, 22 bytes

```
ＮθＮηＦ×θη¿ιＩ⟦⎇﹪ιθ⊖ι⁻ιθι

```

Try it online! Link is to verbose version of code. Outputs using the following format:

```
0-1
|
2-3
|
4-5

```

Alternative solution, also 22 bytes:

```
ＮθＮηＦ×θη¿ιＩ⟦⎇‹ιθ⊖ι⁻ιθι

```

Try it online! Link is to verbose version of code. Outputs using the following format:

```
0-1
| |
2 3
| |
4 5

```

Bonus version:

```
ＮθＦＮＦθ«Ｊ⊗κ⊗ι¿∧κ∨¬ι‽←+-↑✂+|⁰⊕ι

```

Try it online! Link is to verbose version of code.
> 0 votes

---
Tags: code-golf, grid, graph-theory
---