title: Is this Sequence Graphic?

text:
# Question
Title: Is this Sequence Graphic?
A graphic sequence is a sequence of positive integers each denoting the number of edges for a node in a simple graph. For example the sequence `2 1 1` denotes a graph with 3 nodes one with 2 edges and 2 with one connection.

Not all sequences are graphic sequences. For example `2 1` is not a graphic sequence because there is no way to connect two nodes so that one of them has two edges.

---

# Task

You will take a sequence of integers by *any reasonable* method. This includes, *but is not limited to*, an array of integers and its size, a linked list of unsigned integers, and a vector of doubles. You may assume that there will be no zeros in the input. You may also assume the input is sorted from least to greatest or greatest to least.

You must output whether or not the sequence is a graphic sequence. A truthy value if it is a falsy value otherwise.

---

# Goal

This is the goal is to minimize the number of bytes in your program

# Testcases

*Sorted greatest to least*

```
                  -> True
3 3 3 2 2 2 1 1 1 -> True
3 3 2 2 1 1       -> True
3 3 2             -> False
8 1 1 1 1 1 1 1 1 -> True
1 1 1 1           -> True
1 1 1             -> False
9 5 4             -> False

```

# Answer
# Mathematica, 25 bytes

```
<<Combinatorica`
GraphicQ

```

Yeah, another builtin. (Takes the input as a list of positive integers.) Requires loading the `Combinatorica` package.
> 7 votes

# Answer
# Python 2 (exit code), 53 bytes

```
l=input()
while any(l):l.sort();l[~l[-1]]-=1;l[-1]-=1

```

Try it online!

Outputs via exit code.

Uses a version of the Havel-Hakimi algorithm. Repeatedly decrements both the largest element `k` and the `k`'th largest element (not counting `k` itself), which corresponding to assigning an edge between the two vertices with those degrees. Terminates successfully when the list becomes all zeroes. Otherwise, if there's an index out of bounds, fails with error. Any negative values created also eventually lead to an out-of-bounds error.
> 6 votes

# Answer
## CJam (20 bytes)

```
{{W%(Wa*.+$_0a<!}g!}

```

Online test suite including a couple of extra tests I added to catch bugs in some of my attempts.

This is an anonymous block (function) which takes an array of integers on the stack and leaves `0` or `1` on the stack. It assumes that the input is sorted ascending.

The input array may not be empty, but may contain zeroes, in accordance with OP's answer to my query on the subject of empty inputs.

### Dissection

This follows OP's answer in implementing the Havel-Hakimi algorithm.

```
{          e# Define a block
  {        e#   Do-while loop (which is the reason the array must be non-empty)
           e#     NB At this point the array is assumed to be non-empty and sorted
    W%     e#     Reverse
    (Wa*.+ e#     Pop the first element and subtract 1 from that many subsequent
           e#     elements. If there aren't enough, it adds -1s to the end. That's
           e#     the reason for using W (i.e. -1) and .+ instead of 1 and .-
    $      e#     Sort, restoring that part of the invariant
    _0a<!  e#     Continue looping if array >= [0]
           e#     Equivalently, break out of the loop if it starts with a negative
           e#     number or is empty
  }g
  !        e#   Logical not, so that an empty array becomes truthy and an array
           e#   with a negative number becomes falsy
}

```
> 5 votes

# Answer
# Python 2, 108 bytes

Here is my implementation in Python. I'm sure it can be beaten by a more experienced golfer or mathematician. It implements the Havel-Hakimi algorithm.

```
def f(x):p=x[0]+1;x=sorted(x+[0]*p)[::-1];return~x[-1]and(p<2or f(sorted([a-1for a in x[1:p]]+x[p:])[::-1]))

```

Try it online!
> 2 votes

# Answer
# Haskell, ~~102 98 95~~ 94 bytes

```
import Data.List
f(x:r)=length r>=x&&x>=0&&(f.reverse.sort$take x(pred<$>r)++drop x r)
f x=1<3

```

Try it online! Usage: `f [3,3,2,2,1,1]`, returns `True` or `False`. Assumes that the input ~~contains no zeros and~~ is sorted in descending order, as allowed in the challenge.

**Explanation:**

```
import Data.List          -- import needed for sort
f (x:r) =                 -- x is the first list element, r the rest list
  length r >= x           -- the rest list r must be longer or equal x
  && x >= 0               -- and x must not be negative
  && (f .                 -- and the recursive call of f
      reverse . sort $    --    with the descendingly sorted list
      take x(pred<$>r)    --    of the first x elements of r subtracted by 1
      ++ drop x r         --    and the rest of r
     )                    -- must be true
f [] = True               -- if the list is empty, return True

```

Edit: This seems to follow the Havel-Hakimi mentioned in other answers, though I did not know of this algorithm when writing the answer.
> 2 votes

# Answer
# Jelly, 12 bytes

```
ṢṚḢ-€+ƊƊƬ>-Ȧ

```

A monadic Link accepting a list which yields `1` if the answers are consistent otherwise `0`.

**Try it online!** Or see the test-suite.

### How?

```
ṢṚḢ-€+ƊƊƬ>-Ȧ - Link: list of integers
        Ƭ    - collect up while results change:
       Ɗ     -   last three links as a monad i.e. f(L):
Ṣ            -     sort                      [min(L),...,max(L)]
 Ṛ           -     reverse                   [max(L),...,min(L)]
      Ɗ      -     last three links as a monad i.e. f([a,b,c,...,x]):
  Ḣ          -       pop head                          a
   -€        -       -1 for each                       [-1,-1,...,-1] (length a)
     +       -       add to head result (vectorises)   [b-1,c-1,...,x-1,-1,-1,...]
         >-  - greater than -1? (vectorises)
           Ȧ - Any and all? (0 if empty or contains a 0 when flattened, else 1)

```
> 2 votes

# Answer
# , 20 bytes

```
igraph::is_graphical

```

Mathematica isn't the only language with built-ins! ;-)

The `igraph` package needs to be installed. Takes input as a vector of integers.
> 2 votes

# Answer
# 05AB1E, ~~26~~ 25 bytes

```
D0*«¹v{R¬U¦X¹gn‚£`s<ì}0QP

```

Try it online!

**Explanation**

```
D0*«                       # extend the input list with as many zeroes as it has elements
    ¹v                     # len(input) times do:
      {R                   # sort in descending order
        ¬U¦X               # extract the first element of the list
            ¹gn‚           # pair it with len(input)^2
                £          # partition the list in 2 parts, the first the size of the
                           # extracted element, the second containing the rest of the list
                 `         # split these list to stack (the second on top)
                  s<       # decrement the elements of the first list by 1
                    ì      # prepend it to the rest of the list
                     }     # end loop
                      0Q   # compare each element in the resulting list with 0
                        P  # reduce list by multiplication

```
> 1 votes

# Answer
# JavaScript (ES6), ~~82 80~~ 76 bytes

```
f=([$,..._])=>1/$?_.length>=$&$>=0&f(_.map(a=>a-($-->0)).sort((a,b)=>b-a)):1

```

Thanks to ETHproductions for saving many bytes!

## Usage

```
f=([$,..._])=>1/$?_.length>=$&$>=0&f(_.map(a=>a-($-->0)).sort((a,b)=>b-a)):1
f([3,3,3,2,2,2,1,1,1])

```

## Output

```
1

```
> 1 votes

# Answer
# Ruby, 90 bytes

Ported from this question which turned out to be a duplicate of this. Uses Havel-Hakimi since that was the one mentioned in that question.

```
->a{b=1;(a.sort_by!(&:-@);i=a.shift;a.map!{|e|i>0&&e>0?(i-=1;e-1):e};b&&=i<1)while[]!=a;b}

```

Try it online!
> 0 votes

# Answer
# 05AB1E, 19 bytes

```
[D{RćD1‹#Å0<0ζO})dW

```

Port of *JonathanAllan*'s Jelly answer, so make sure to upvote him!!

Try it online or verify all test cases.

**Explanation:**

```
[            # Start an infinite loop:
 D           #  Duplicate the current list
             #  (which is the implicit input-list in the first iteration)
  {R         #  Sort it from highest to lowest
    ć        #  Extract the head; pop and push the remainder and head
     D1‹     #  If the head is 0 or negative:
        #    #   Stop the infinite loop
     Å0<     #  Create a list of the head amount of -1
        0ζ   #  Zip/transpose it with the remainder list, with 0 as filler
          O  #  Sum each pair
})           # After the loop: wrap everything on the stack into a list
  d          # Check for each value if it's non-negative (>= 0)
             # (resulting in 1/0 for truthy/falsey respectively)
   W         # Get the flattened minimum (so basically check if none are falsey)
             # (which is output implicitly as result)

```
> 0 votes

# Answer
# Stax, ~~14~~ 12 bytes

```
ε▼ü*æε<%)4‼♂

```

Run and debug it

This program handles empty and unsorted inputs.
> 0 votes

---
Tags: code-golf, sequence, decision-problem, graph-theory
---


title: Point out a string character

text:
# Question
Title: Point out a string character
# Introduction

In many programming languages, within syntax exceptions, it is often pointed out to the programmer exactly which character or line is the culprit. This challenge will be a bit of a modification of that - specifically, using an arrow to point out any specific character of an input string.

# The challenge

Your job is to:

* Define a function that takes two parameters.
* This function will print the string to `stdout` (or an acceptable alternative), along with pointing out the index of the string requested.
* The index is zero-based, meaning index 0 is actually he first character of the string.
* If a half index is passed in, you are to use a double arrow (`/\` instead of `^`) to point out the middle of the two characters.

Don't quite get what I mean? Here's some test cases:

`f("hello world", 3)`:

```
hello world
   ^
   l

```

`f("Code Golf", 0)`:

```
Code Golf
^
C

```

`f("MY STRING!", 4.5)`:

```
MY STRING!
    /\
    TR

```

You may use any language. No input from `stdin` \- must be through a function. Do not use any of the common loopholes. And most importantly, have fun!

# Leaderboard

You can view the leaderboard for this post by expanding the widget/snippet below. In order for your post to be included in the rankings, you need a header (`# header text`) with the following info:

* The name of the language (end it with a comma `,` or dash `-`), followed by...
* The byte count, as the last number to appear in your header.

For example, `JavaScript (ES6), 72 bytes` is valid, but `Fortran, 143 bytes (8-bit)` is invalid because the byte count is not the last number in the header (your answer will be recognized as 8 bytes - don't take advantage of this).

```
<iframe src="https://xmikee1.github.io/ppcg-leaderboard/?id=186018" width="100%" height="100%" style="border: none;">Oops, your browser is too old to view this content! Please upgrade to a newer version of your browser that supports HTML5.</iframe><style>html,body{margin:0;padding:0;height:100%;overflow:hidden}</style>
```

# Answer
> 2 votes
# Python 2, ~~78~~ ~~77~~ ~~75~~ 74 bytes

```
def f(s,i):j=int(i);x='\n'+j*' ';print s+x+'/^\\'[i==j::2]+x+s[j:(i>j)-~j]

```

Try it online!

<sub>-1 byte, thanks to Arnauld</sub>

# Answer
> 1 votes
# 05AB1E, ~~25~~ ~~24~~ 23 bytes

```
…^/\ć‚Y.ïè©XY.$®g£‚YúXš

```

Function taking `X` as string and `Y` as number, and returning a list of string-lines.

Try it online.

**Explanation:**

```
…^/\         # Push string "^/\"
    ć        # Extract head; pop and push remainder "/\" and head "^"
     ‚       # Pair them together: ["/\","^"]
      Y.ï    # Check if number `Y` is an integer (1 if truthy; 0 if falsey)
         è   # Use that to index into the pair ("^" if integer; "/\" if decimal)
          ©  # Store it in the register (without popping)
XY.$         # Remove the first `int(Y)` characters from string `X`
    ®g       # Get the length of the string we saved in the register
      £      # Leave that many leading characters from the string
‚            # Pair it with the earlier "^" or "/\"
 Yú          # Pad both with `int(Y)` amount of leading spaces
Xš           # Prepend string `X` to this list
             # (which is returned implicitly as result)

```

The function definition is:

```
"…^/\ć‚Y.ïè©XY.$®g£‚YúXš"ˆ

```

Which can then be called like this:

```
"MY STRING!"U  4.5V ¯`.V»,

```

# Answer
> 1 votes
# C (gcc), ~~165~~ ~~125~~ ~~101~~ ~~99~~ ~~90~~ 85 bytes

-40 Bytes @Kevin Cruijssen
-24 Bytes @Arnauld
-2 Bytes
-9 Bytes @attinat
-5 Bytes @ceilingcat

```
t,u;a(char*s,float i){t=i;u=i>t;printf("%s\n%*s\n%*.*s",s,t+u,L" ^尯"+u,t+u,++u,s+t);}

```

Try it online!

# Answer
> 1 votes
# Pepe, 229 bytes

This took very long to make. Probably my longest Pepe code yet. Everything could be so much easier if not the third output line. I didn't write in Pepe for a long while so I'm proud of it.

*Note: This is not a valid answer because the specs require it to be a function – but there are no functions in Pepe, officially.*

```
REEeReeeReeERREeeRREeEEerREEreeeEeEEEEreeEeEEEeeREeREEEerREEreeEeEEEEeREerEeeEeeeeerrEEeeeErereeeREEEERREEEEEEeReEReeErereeeRREEEEEEEREEEeRrErrEEREEEEReREEEeREEEEereerreErEereeREEEEReEereRrEeEEeRrEEEEEEErEEEerrEEREEEEReReEerEeree

```

Try it online!

Non-minified code, with comments, if you can understand it...

```
# The line
REEe   # Take input
Reee   # Output it
ReeE   # End line

# Index
RREee    # Take the number [n]
RREeEEe  # Floor in a copy

# Function [n]
rREE

  reeeEeEEEE reeEeEEEee  # Output /\

REe  # End

# Move pointer to last item
REEEe

# Function floor[n], overrides [n] if it's an integer
rREE

  reeEeEEEEe  # Output ^

REe

# Line 2 – spaces
rEeeEeeeee  # A space
rrEEeeeE    # Repeat it [n] times
re          # Remove one
reee        # Output

# Line 2 – pointer
REEEE      # Go to first item
RREEEEEEe  # Copy to other stack
ReE        # Call it
ReeE       # End the line

# Line 3 – spaces
re     # Remove the item
reee   # Output

# Line 3 – letters
RREEEEEEE  # Move the index to other stack
REEEe      # Move R pointer to the end
RrE        # Prepend 0
rrEE       # Label 0
  REEEE      # Go to the first item
  Re         # Pop it
  REEEe      # Go to the last item
  REEEEe     # Decrement
  ree        # Recurse while unequal
  rreE       # Equal, end
    # This is a flag I've added because I thought that I should add something in its place
    # I never thought it will be useful. But apparently it is. For recursion.
rEe
ree        # Call if unequal
REEEE      # Move to first item
ReEe       # Output it
re         # Pop the 0
RrEeEEe    # Floor the first item in a copy
RrEEEEEEE  # Move the item to the other stack
rEEEe      # Move to the end
rrEE       # Label floor[n]
  REEEE      # Move to first item of R
  Re         # Remove it
  ReEe       # Output the next one
rEe        # End
ree        # Enter it if [n] is not an integer

```

# Answer
> 0 votes
# JavaScript (ES8),  ~~65~~  63 bytes

Takes input as `(string)(position)`.

```
s=>n=>s+(x=`
`.padEnd(n+1))+(n%1?'/\\'+x+s[~~n++]:'^'+x)+s[~~n]

```

Try it online!

---

# JavaScript (ES8), 39 bytes

*This version is based on the challenge description, without the 3rd line. The original version above includes it, like suggested by the test cases. Awaiting OP clarification.*

Takes input as `(string)(position)`.

```
s=>n=>s+`
`.padEnd(n+1)+(n%1?'/\\':'^')

```

Try it online!

# Answer
> 0 votes
# Jelly, 22 bytes

```
⁾/\”^%?1,ịṭ€Ḟ’⁶xƲ{;@W}

```

Try it online!

A dyadic link which takes the position as its left argument and the string as its right. It returns a list of Jelly strings (presumed to be an ‘acceptable alternative’) representing the output. The TIO link outputs these to stdout separated by newlines.

This is currently using 1-indexing since that is the norm for Jelly. If 0-indexing is a must, here’s an alternative dyadic link:

# Jelly, 23 bytes

```
⁾/\”^%?1,‘ị¥ṭ€Ḟ⁶xƊ{;@W}

```

Try it online!

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), ~~100~~ 98 bytes

```
a=>b=>a+(b>(i=(int)b)?"/\\":"^").PadLeft((v=b>i?2:1)+i)+'\n'+a.Substring(i,v).PadLeft(v+i);int i,v

```

Try it online!

# Answer
> 0 votes
# Java 11, 103 bytes

```
(s,n)->{int i=(int)n;var t="\n"+" ".repeat(i);return s+t+(n>i?"/\\":"^")+t+s.substring(i,n>i?i+2:i+1);}

```

Try it online.

# Answer
> 0 votes
# Python 3.8 (pre-release), 72 bytes

Very similar to @TFeld's answer, but makes use of Python 3.8's handy `:=` lambda assignment operator.

```
f=lambda s,i:s+(x:='\n'+' '*(j:=int(i)))+'/^\\'[i==j::2]+x+s[j:(i>j)-~j]

```

Try it online!

# Answer
> 0 votes
# Stax, 21 bytes

```
ë└¥1ç4┴îdΩ8½öyε∙µ$%T▐

```

Run and debug it

---
Tags: code-golf, string
---


# Question
Title: Make Plan 9 Cat Turing Complete in as Few Bytes as Possible
Your task is to modify the original Plan 9 cat tool for UNIX, in order to make it a fully turing complete language interpreter. You may make use of ANSI escape codes and the backspace character (\x08) to aid in this.

You must submit:

* A modified version of the Plan 9 cat tool
* A hexdump of the turing machine that can be run like so: `cat turing_machine` where `turing_machine` is the file you wrote.

Your score is the number of bytes you changed in the Plan 9 cat source code (where replacing a character counts as two bytes because you have to remove it and then replace it).

Here is the Plan 9 cat source code, taken from here.

```
#include <u.h>
#include <libc.h>

void
cat(int f, char *s)
{
    char buf[8192];
    long n;

    while((n=read(f, buf, (long)sizeof buf))>0)
        if(write(1, buf, n)!=n)
            sysfatal("write error copying %s: %r", s);
    if(n < 0)
        sysfatal("error reading %s: %r", s);
}

void
main(int argc, char *argv[])
{
    int f, i;

    argv0 = "cat";
    if(argc == 1)
        cat(0, "<stdin>");
    else for(i=1; i<argc; i++){
        f = open(argv[i], OREAD);
        if(f < 0)
            sysfatal("can't open %s: %r", argv[i]);
        else{
            cat(f, argv[i]);
            close(f);
        }
    }
    exits(0);
}

```

The headers in the above source are u.h and libc.h. Your code must conform to the C99 standard.

# Answer
> 5 votes
# ~~266~~ ~~256~~ ~~250~~ ~~245~~ 149 bytes (probably)

Thanks to @someone for suggesting using a cyclic tag system (originally I was using a modified version of Brainfuck).

Real computers aren't actually Turing-complete, because they have a finite amount of memory, whereas a Turing-machine has an infinite amount of memory. This is an implementation of a cyclic tag system with 9999 bytes of memory (although you could very easily change that), and with an initial word of `1` (I'm not entirely sure if cyclic tag systems with a fixed initial word are Turing-complete, but they probably are). The length of the program must be ≤8192, in this format:

```
00 (the first byte is ignored)
01 01 02 00 (first rule: 001 (null character to mark end))
02 02 02 01 02 00 (second rule: 11101)
03 (marks end of program)

```

There is no I/O. The added code should be C99-compliant (provided the input code doesn't use more than 9999 bytes of memory at once), but I'm pretty sure you can't (portably) declare `main` as `void` in C99.

```
#include <u.h>
#include <libc.h>

void
cat(int f, char *s)
{
    char buf[8192],m[9999];
    long n;

    while((n=read(f, buf, (long)sizeof buf))>0){char m[9999],*M=m+9998,*s=m,*e=m+1,*i=buf;*m=2;m[1]=0;do{for(i++;*i;i++){if(*i>2)i=buf+1;if(*s>1){*e++=*i;if(e>M)e=s;}}if(++s>M)s=m;}while(*s);
        /*if(write(1, buf, n)!=n)
            sysfatal("write error copying %s: %r");*/}
    if(n < 0)
        sysfatal("error reading %s: %r", s);
}

void
main(int argc, char *argv[])
{
    int f, i;

    argv0 = "cat";
    if(argc == 1)
        cat(0, "<stdin>");
    else for(i=1; i<argc; i++){
        f = open(argv[i], OREAD);
        if(f < 0)
            sysfatal("can't open %s: %r", argv[i]);
        else{
            cat(f, argv[i]);
            close(f);
        }
    }
    exits(0);
}

```

Slightly de-golfed, and printing each step:

```
#include <u.h>
#include <libc.h>

void
cat(int f, char *s)
{
    char buf[8192];
    size_t n;

    while((n=read(f, buf, (long)sizeof buf))>0) {
        char mem[9999];
        *mem=2;mem[1]=0;
        char* mem_end = &mem[9998];
        char*start=mem,*end=mem+1,*i=buf;
        do {
            for (char* p = start; p < end; p++) {
                printf("%d",*p - 1);
            }
            printf("\n");
            for (i++;*i;i++) {
                if(*i>2)i = buf+1;
                if (*start > 1){
                    *end++=*i;
                    if (end > mem_end)
                        end = mem;
                }
            }
            if (++start>mem_end)start=mem;
        } while (*start);
        /*if(write(1, buf, n)!=n)
            sysfatal("write error copying %s: %r");*/
    }
    if(n < 0)
        sysfatal("error reading %s: %r", s);
}

void
main(int argc, char *argv[])
{
    int f, i;

    argv0 = "cat";
    if(argc == 1)
        cat(0, "<stdin>");
    else for(i=1; i<argc; i++){
        f = open(argv[i], OREAD);
        if(f < 0)
            sysfatal("can't open %s: %r", argv[i]);
        else{
            cat(f, argv[i]);
            close(f);
        }
    }
    exits(0);
}

```

The following Python script converts any cyclic tag system into code which is accepted by this program:

```
productions =   [[0,0,1],
                 [0],
                 [0,0],
                 [0,1,1,1]]
f = open("turing_machine","w")
f.write("\0") # First byte is ignored
for production in productions:
    for c in production:
        f.write(chr(c+1))
    f.write("\0")
f.write("\3")
f.close()

```

When you run the output of this program with the de-golfed version, you get:

```
1
001
01
1
0111
111
110
1000
0000111
000111
00111
0111
111
11001
10010
001000
01000
1000
0000
000
00
0

```

---
Tags: code-challenge, interpreter, c, programming-puzzle
---


title: Surface of the 3x3x3 cube as a graph

text:
# Question
Title: Surface of the 3x3x3 cube as a graph
Your task is to generate a graph with 54 vertices, each corresponds to a facet on a Rubik's cube. There is an edge between two vertices iff the corresponding facets share a side.

### Rules

* You may choose to output an adjacency list, adjacency matrix, edge list, or any reasonable format to represent a graph in an algorithm. (A visual graph readable by a human is generally not a reasonable format in an algorithm in most cases.)
* You may make either every vertex adjacent to itself, or none adjacent to itself.
* You may either include both directions for each edge (count one or two times for self-loops), or output exactly one time for each edge, but not mix the ways.
* You may renumber the vertices, skip some numbers, or even use non-number labels for the vertices in any way you want. You should also post the numbering if it isn't obvious, so others could check your answer in easier ways.
* This is code-golf. Shortest code in bytes wins.

### Example output

This is the numbering of vertices used in the example:

```
          0  1  2
          3  4  5
          6  7  8
 9 10 11 18 19 20 27 28 29 36 37 38
12 13 14 21 22 23 30 31 32 39 40 41
15 16 17 24 25 26 33 34 35 42 43 44
         45 46 47
         48 49 50
         51 52 53

```

Output as an adjacency list (vertex number before each list is optional):

```
0 [1 3 9 38]
1 [2 4 0 37]
2 [29 5 1 36]
3 [4 6 10 0]
4 [5 7 3 1]
5 [28 8 4 2]
6 [7 18 11 3]
7 [8 19 6 4]
8 [27 20 7 5]
9 [10 12 38 0]
10 [11 13 9 3]
11 [18 14 10 6]
12 [13 15 41 9]
13 [14 16 12 10]
14 [21 17 13 11]
15 [16 51 44 12]
16 [17 48 15 13]
17 [24 45 16 14]
18 [19 21 11 6]
19 [20 22 18 7]
20 [27 23 19 8]
21 [22 24 14 18]
22 [23 25 21 19]
23 [30 26 22 20]
24 [25 45 17 21]
25 [26 46 24 22]
26 [33 47 25 23]
27 [28 30 20 8]
28 [29 31 27 5]
29 [36 32 28 2]
30 [31 33 23 27]
31 [32 34 30 28]
32 [39 35 31 29]
33 [34 47 26 30]
34 [35 50 33 31]
35 [42 53 34 32]
36 [37 39 29 2]
37 [38 40 36 1]
38 [9 41 37 0]
39 [40 42 32 36]
40 [41 43 39 37]
41 [12 44 40 38]
42 [43 53 35 39]
43 [44 52 42 40]
44 [15 51 43 41]
45 [46 48 17 24]
46 [47 49 45 25]
47 [33 50 46 26]
48 [49 51 16 45]
49 [50 52 48 46]
50 [34 53 49 47]
51 [52 44 15 48]
52 [53 43 51 49]
53 [35 42 52 50]

```

# Answer
> 11 votes
# APL (Dyalog Classic), ~~34~~ 30 bytes

-4 thanks to jimmy23013

```
4≥+/¨|∘.-⍨,(⍳3)∘.⌽7 ¯1∘.,○⍳3 3

```

Try it online!

outputs an adjacency matrix with each vertex adjacent to itself

`⍳3 3` generate an array of `(0 0)(0 1)(0 2)(1 0)(1 1)(1 2)(2 0)(2 1)(2 2)`

multiply all by π

`7 ¯1∘.,` prepend 7 or -1 in all possible ways

`(⍳3)∘.⌽` rotate coord triples by 0 1 2 steps in all possible ways

`+/¨|∘.-⍨,` compute manhattan distance between each pair

`4≥` it must be no greater than 4 for neighbouring facets

# Answer
> 6 votes
# Ruby, 60 bytes

```
i=0;("$$5$$1$Hu"*6).bytes{|j|p [(j/18+i+=1)%54,(j%18+i)%54]}

```

Try it online!

Improved version of my original answer. We split the surface of the cube into squares of 9 (instead of rectangles of 18 as before) and use a magic string rather than a formula to generate the offsets. The output is a list of the nodes below and to the right of each node in the (revised) map below, as before.

**Output map in base 10** as shown in the output

(each node is linked to the nodes below and to the right)

```
0  3  6  9 10 11
1  4  7 12 13 14
2  5  8 15 16 17
        18 21 24 27 28 29
        19 22 25 30 31 32
        20 23 26 33 34 35
                 36 39 42 45 46 47
                 37 40 43 48 49 50
                 38 41 44 51 52 53

```

**Output map in base 9** (to show more clearly how it works.)

Note that each square of 9 has the same first digit. The last digits repeat 0,1,2 on the free edge and 0,3,6 on the attached edge (alternating between horizontal and vertical.)

In one direction the next node is 3 higher (except when crossing to the next square, when it is 3,5 or 7 higher) and in the other direction it is 1 higher (except when crossing to the next square, when it is \[base 10\] `18, 14 or 10` higher = \[base 9\] `20, 16 or 12` higher.)

This info is encoded into the magic string, where the ASCII code of each character is `18*[2,4 or 6]+[17,13,10 or 0]`. Incrementing `i` at the beginning of each iteration boosts these values by 1.

```
00 03 06 10 11 12
01 04 07 13 14 15
02 05 08 16 17 18
         20 23 26 30 31 32
         21 24 27 33 34 35
         22 25 28 36 37 38
                  40 43 46 50 51 52
                  41 44 47 53 54 55
                  42 45 48 56 57 59

```

# Ruby, 79 bytes

```
54.times{|i|p [(i%6<5?i+1:i+18-i/6%3*7)%54,(i+=i%18<12?6:[18-i%6*7,3].max)%54]}

```

Try it online!

Prints a representation of a unidirectional graph, as a list of the vertices to the right of and below each vertex as shown in the map below.

```
 0  1  2  3  4  5
 6  7  8  9 10 11
12 13 14 15 16 17
         18 19 20 21 22 23
         24 25 26 27 28 29
         30 31 32 33 34 35
                  36 37 38 39 40 41
                  42 43 44 45 46 47
                  48 49 50 51 52 53

```

# Answer
> 5 votes
## Python 2.7, 145

```
def p(n):l=(3-n%2*6,n/6%3*2-2,n/18*2-2);k=n/2%3;return l[k:]+l[:k]
r=range(54)
x=[[sum((x-y)**2for x,y in zip(p(i),p(j)))<5for i in r]for j in r]

```

Try it online!

Defines an adjacency matrix `x` as a list of lists of boolean values. Facets count as being adjacent to themselves.

`p(n)` computes the coordinates of the center of the nth facet of a 3x3x3 cube whose facets are 2 units across. Adjacency is determined by testing if 2 facets have a square distance under 5 (adjacent facets have square distance at most 4, non-adjacent facets have square distance at least 6).

# Answer
> 4 votes
# Charcoal, 48 bytes

```
Ｆ⁷Ｆ⁷Ｆ⁷⊞υ⟦ικλ⟧≔Φυ⁼Φ﹪ι⁶¬﹪λ²⟦⁰⟧υＩＥυΦＬυ⁼²ΣＥ§υλ↔⁻ν§ιξ

```

Try it online! Link is to verbose version of code. Explanation:

```
Ｆ⁷Ｆ⁷Ｆ⁷⊞υ⟦ικλ⟧

```

Generate all sets of 3-dimensional coordinates in the range `[0..6]` for each dimension.

```
≔Φυ⁼Φ﹪ι⁶¬﹪λ²⟦⁰⟧υ

```

Keep only those coordinates that are centres of `2x2` squares on one of the faces `x=0`, `y=0`, `z=0`, `x=6`, `y=6`, `z=6`.

```
ＩＥυΦＬυ⁼²ΣＥ§υλ↔⁻ν§ιξ

```

For each coordinate, print the indices of those coordinates whose taxicab distance is 2.

The vertices are numbered as follows:

```
         33 34 35
         21 22 23
          9 10 11
36 24 12  0  1  2 13 25 37 47 46 45
38 26 14  3  4  5 15 27 39 50 49 48
40 28 16  6  7  8 17 29 41 53 52 51
         18 19 20
         30 31 32
         42 43 44

```

# Answer
> 4 votes
# Wolfram Language 190 bytes

The following returns all of the graph edges in terms of the actual coordinates (assuming each mini-cube is 2 units at the edge and the Rubik's cube has its bottom left vertex at the origin).

```
t=Table;h[a_,b_,c_]:=t[{x,y,z},{a,1,5,2},{b,1,5,2},{c,0,6,6}];Partition[Sort[a=Cases[DeleteCases[Tuples[Flatten[{h[x,z,y],h[y,z,x],h[x,y,z]},3],{2}],{x_,x_}],x_/;ManhattanDistance@@x==2]],4]

(* output *)
{{{{0,1,1},{0,1,3}},{{0,1,1},{0,3,1}},{{0,1,1},{1,0,1}},{{0,1,1},{1,1,0}}},{{{0,1,3},{0,1,1}},{{0,1,3},{0,1,5}},{{0,1,3},{0,3,3}},{{0,1,3},{1,0,3}}},{{{0,1,5},{0,1,3}},{{0,1,5},{0,3,5}},{{0,1,5},{1,0,5}},{{0,1,5},{1,1,6}}},{{{0,3,1},{0,1,1}},{{0,3,1},{0,3,3}},{{0,3,1},{0,5,1}},{{0,3,1},{1,3,0}}},{{{0,3,3},{0,1,3}},{{0,3,3},{0,3,1}},{{0,3,3},{0,3,5}},{{0,3,3},{0,5,3}}},{{{0,3,5},{0,1,5}},{{0,3,5},{0,3,3}},{{0,3,5},{0,5,5}},{{0,3,5},{1,3,6}}},{{{0,5,1},{0,3,1}},{{0,5,1},{0,5,3}},{{0,5,1},{1,5,0}},{{0,5,1},{1,6,1}}},{{{0,5,3},{0,3,3}},{{0,5,3},{0,5,1}},{{0,5,3},{0,5,5}},{{0,5,3},{1,6,3}}},{{{0,5,5},{0,3,5}},{{0,5,5},{0,5,3}},{{0,5,5},{1,5,6}},{{0,5,5},{1,6,5}}},{{{1,0,1},{0,1,1}},{{1,0,1},{1,0,3}},{{1,0,1},{1,1,0}},{{1,0,1},{3,0,1}}},{{{1,0,3},{0,1,3}},{{1,0,3},{1,0,1}},{{1,0,3},{1,0,5}},{{1,0,3},{3,0,3}}},{{{1,0,5},{0,1,5}},{{1,0,5},{1,0,3}},{{1,0,5},{1,1,6}},{{1,0,5},{3,0,5}}},{{{1,1,0},{0,1,1}},{{1,1,0},{1,0,1}},{{1,1,0},{1,3,0}},{{1,1,0},{3,1,0}}},{{{1,1,6},{0,1,5}},{{1,1,6},{1,0,5}},{{1,1,6},{1,3,6}},{{1,1,6},{3,1,6}}},{{{1,3,0},{0,3,1}},{{1,3,0},{1,1,0}},{{1,3,0},{1,5,0}},{{1,3,0},{3,3,0}}},{{{1,3,6},{0,3,5}},{{1,3,6},{1,1,6}},{{1,3,6},{1,5,6}},{{1,3,6},{3,3,6}}},{{{1,5,0},{0,5,1}},{{1,5,0},{1,3,0}},{{1,5,0},{1,6,1}},{{1,5,0},{3,5,0}}},{{{1,5,6},{0,5,5}},{{1,5,6},{1,3,6}},{{1,5,6},{1,6,5}},{{1,5,6},{3,5,6}}},{{{1,6,1},{0,5,1}},{{1,6,1},{1,5,0}},{{1,6,1},{1,6,3}},{{1,6,1},{3,6,1}}},{{{1,6,3},{0,5,3}},{{1,6,3},{1,6,1}},{{1,6,3},{1,6,5}},{{1,6,3},{3,6,3}}},{{{1,6,5},{0,5,5}},{{1,6,5},{1,5,6}},{{1,6,5},{1,6,3}},{{1,6,5},{3,6,5}}},{{{3,0,1},{1,0,1}},{{3,0,1},{3,0,3}},{{3,0,1},{3,1,0}},{{3,0,1},{5,0,1}}},{{{3,0,3},{1,0,3}},{{3,0,3},{3,0,1}},{{3,0,3},{3,0,5}},{{3,0,3},{5,0,3}}},{{{3,0,5},{1,0,5}},{{3,0,5},{3,0,3}},{{3,0,5},{3,1,6}},{{3,0,5},{5,0,5}}},{{{3,1,0},{1,1,0}},{{3,1,0},{3,0,1}},{{3,1,0},{3,3,0}},{{3,1,0},{5,1,0}}},{{{3,1,6},{1,1,6}},{{3,1,6},{3,0,5}},{{3,1,6},{3,3,6}},{{3,1,6},{5,1,6}}},{{{3,3,0},{1,3,0}},{{3,3,0},{3,1,0}},{{3,3,0},{3,5,0}},{{3,3,0},{5,3,0}}},{{{3,3,6},{1,3,6}},{{3,3,6},{3,1,6}},{{3,3,6},{3,5,6}},{{3,3,6},{5,3,6}}},{{{3,5,0},{1,5,0}},{{3,5,0},{3,3,0}},{{3,5,0},{3,6,1}},{{3,5,0},{5,5,0}}},{{{3,5,6},{1,5,6}},{{3,5,6},{3,3,6}},{{3,5,6},{3,6,5}},{{3,5,6},{5,5,6}}},{{{3,6,1},{1,6,1}},{{3,6,1},{3,5,0}},{{3,6,1},{3,6,3}},{{3,6,1},{5,6,1}}},{{{3,6,3},{1,6,3}},{{3,6,3},{3,6,1}},{{3,6,3},{3,6,5}},{{3,6,3},{5,6,3}}},{{{3,6,5},{1,6,5}},{{3,6,5},{3,5,6}},{{3,6,5},{3,6,3}},{{3,6,5},{5,6,5}}},{{{5,0,1},{3,0,1}},{{5,0,1},{5,0,3}},{{5,0,1},{5,1,0}},{{5,0,1},{6,1,1}}},{{{5,0,3},{3,0,3}},{{5,0,3},{5,0,1}},{{5,0,3},{5,0,5}},{{5,0,3},{6,1,3}}},{{{5,0,5},{3,0,5}},{{5,0,5},{5,0,3}},{{5,0,5},{5,1,6}},{{5,0,5},{6,1,5}}},{{{5,1,0},{3,1,0}},{{5,1,0},{5,0,1}},{{5,1,0},{5,3,0}},{{5,1,0},{6,1,1}}},{{{5,1,6},{3,1,6}},{{5,1,6},{5,0,5}},{{5,1,6},{5,3,6}},{{5,1,6},{6,1,5}}},{{{5,3,0},{3,3,0}},{{5,3,0},{5,1,0}},{{5,3,0},{5,5,0}},{{5,3,0},{6,3,1}}},{{{5,3,6},{3,3,6}},{{5,3,6},{5,1,6}},{{5,3,6},{5,5,6}},{{5,3,6},{6,3,5}}},{{{5,5,0},{3,5,0}},{{5,5,0},{5,3,0}},{{5,5,0},{5,6,1}},{{5,5,0},{6,5,1}}},{{{5,5,6},{3,5,6}},{{5,5,6},{5,3,6}},{{5,5,6},{5,6,5}},{{5,5,6},{6,5,5}}},{{{5,6,1},{3,6,1}},{{5,6,1},{5,5,0}},{{5,6,1},{5,6,3}},{{5,6,1},{6,5,1}}},{{{5,6,3},{3,6,3}},{{5,6,3},{5,6,1}},{{5,6,3},{5,6,5}},{{5,6,3},{6,5,3}}},{{{5,6,5},{3,6,5}},{{5,6,5},{5,5,6}},{{5,6,5},{5,6,3}},{{5,6,5},{6,5,5}}},{{{6,1,1},{5,0,1}},{{6,1,1},{5,1,0}},{{6,1,1},{6,1,3}},{{6,1,1},{6,3,1}}},{{{6,1,3},{5,0,3}},{{6,1,3},{6,1,1}},{{6,1,3},{6,1,5}},{{6,1,3},{6,3,3}}},{{{6,1,5},{5,0,5}},{{6,1,5},{5,1,6}},{{6,1,5},{6,1,3}},{{6,1,5},{6,3,5}}},{{{6,3,1},{5,3,0}},{{6,3,1},{6,1,1}},{{6,3,1},{6,3,3}},{{6,3,1},{6,5,1}}},{{{6,3,3},{6,1,3}},{{6,3,3},{6,3,1}},{{6,3,3},{6,3,5}},{{6,3,3},{6,5,3}}},{{{6,3,5},{5,3,6}},{{6,3,5},{6,1,5}},{{6,3,5},{6,3,3}},{{6,3,5},{6,5,5}}},{{{6,5,1},{5,5,0}},{{6,5,1},{5,6,1}},{{6,5,1},{6,3,1}},{{6,5,1},{6,5,3}}},{{{6,5,3},{5,6,3}},{{6,5,3},{6,3,3}},{{6,5,3},{6,5,1}},{{6,5,3},{6,5,5}}},{{{6,5,5},{5,5,6}},{{6,5,5},{5,6,5}},{{6,5,5},{6,3,5}},{{6,5,5},{6,5,3}}}}

```

The work of generating the points on each external facet is done by the function, `h`. It has to be called 3 times to generate the points at x=0, x=6; y=0, y=6; and z=0,z=6.

Each facet point that is a Manhattan distance of 2 units from another will be connected to the respective point.

We can display the graph edges visually by the following; `a` is the list of graph edges that are represented below as arrows.

```
Graphics3D[{Arrowheads[.02],Arrow/@a},Boxed->False,Axes-> True]

```

The following shows the Rubik's cube, the points on the external facets, and 8 graph edges.

Red dots are located on facets at y = 0 and y = 6; blue and gray dots are on facets at x = 6 and x = 0, respectively; black dots are on facets at z=6 and z=0.

# Answer
> 2 votes
# Rust \- 278 bytes

```
fn main(){let mut v=vec![];for x in vec![-2,0,2]{for y in vec![-2,0,2]{for z in vec![-2,2]{v.push([-1,z,x,y]);v.push([0,x,y,z]);v.push([1,x,z,y]);}}}for r in 0..54{print!("\n{} ",r);for s in 0..54{if (0..4).map(|n|v[r][n]-v[s][n]).map(|d|d*d).sum::<i32>()<5{print!("{} ",s)}}}}

```

Try on play.rust-lang.org

This is big, but the smallest code for a compiled language (so far). It creates an adjacency list. Its very similar to cardboard\_box 's python answer but I wanted to see if Quaternions could work.

Step 1: Construct 54 Quaternions, each representing a single facet.

Step 2: for each Quaternion, list all other Quaternions with Quadrance (aka squared distance, aka squared norm of the difference) \<= 4.

Quaternions are built like so: The imaginary vectors i j k are points on the shell of a grid, from -2,-2,-2 to 2,2,2, step 2. The real part w is always -1, 0, or 1, so that facets on opposite sides of the cube have the same real part, but adjacent sides have different real parts. The real part allows distinguishing different 'sides' of the cube through calculation.

Quaternion numbering (pseudo isometric 3d view of a cube):

```
   ->i  ^j  \k

                  -2,+2,+2   +0,+2,+2  +2,+2,+2
                  -2,+0,+2   +0,+0,+2  +2,+0,+2
                  -2,-2,+2   +0,-2,+2  +2,-2,+2
                       w=0

   -2,+2,+2       -2 +2 +2   +0 +2 +2   +2 +2 +2     +2,+2,+2
   -2,+0,+2                                          +2,+0,+2
   -2,-2,+2       -2 -2 +2   +0 -2 +2   +2 -2 +2     +2,-2,+2

     -2,+2,+0       -2 +2 +0   +0 +2 +0   +2 +2 +0     +2,+2,+0
     -2,+0,+0                                          +2,+0,+0
     -2,-2,+0       -2 -2 +0   +0 -2 +0   +2 -2 +0     +2,-2,+0

       -2,+2,-2       -2 +2 -2   +0 +2 -2   +2 +2 -2     +2,+2,-2
       -2,+0,-2             w=1                          +2,+0,-2
       -2,-2,-2       -2 -2 -2   +0 -2 -2   +2 -2 -2     +2,-2,-2
           w=-1             w=1                              w=-1

                       -2,+2,-2   +0,+2,-2  +2,+2,-2
                       -2,+0,-2   +0,+0,-2  +2,+0,-2
                       -2,-2,-2   +0,-2,-2  +2,-2,-2
                            w=0

```

Indexed numbering (unfolded cube):

```
                    16 34 52
                    10 28 46
                     4 22 40
         48 30 12   14 32 50  15 33 51
         42 24  6    8 26 44   9 27 45
         36 18  0    2 20 38   3 21 39
                     1 19 37
                     7 25 43
                    13 31 49
                     5 23 41
                    11 29 47
                    17 35 53

```

# Answer
> 2 votes
# JavaScript (ES6, Browser), 153 bytes

```
for(F=n=>(A=[n%9/3|0,n%3]).splice(n/18,0,(n/9&1)*3-.5)&&A,i=0;i<54;i++)for([a,b,c]=F(i),j=0;j<54;Math.hypot(a-d,b-e,c-f)>1||alert([i,j]),j++)[d,e,f]=F(j)

```

Try it online!

This is modified to reduce 5 bytes by making same points adjacent, i.e. \\$||\mathbf{A-B}||\leq1\\$.

# JavaScript (ES6, Browser), 158 bytes

```
for(F=n=>(A=[n%9/3|0,n%3]).splice(n/18,0,(n/9&1)*3-.5)&&A,i=0;i<54;i++)for([a,b,c]=F(i),j=0;j<54;Math.hypot(a-d,b-e,c-f)>1||i-j&&alert([i,j]),j++)[d,e,f]=F(j)

```

Try it online! (simulates `alert` with `console.log`)

Maps the center of all 54 facets to the 3-d space and calculates whether \\$0\<||\mathbf{A-B}||\leq1\\$ for every pair of points. Outputs all directed edges as pairs of numbers `[a, b]`. The vertex map is

```
47 50 53
46 49 52
45 48 51
20 23 26 11 14 17 35 32 29  8  5  2
19 22 25 10 13 16 34 31 28  7  4  1
18 21 24  9 12 15 33 30 27  6  3  0
36 39 42
37 40 43
38 41 44

```

---
Tags: code-golf, kolmogorov-complexity, graph-theory, rubiks-cube
---


title: Tips for golfing in SmileBASIC

text:
# Question
Title: Tips for golfing in SmileBASIC
SmileBASIC deserves more attention. I've only seen 3 users here (including myself!) providing SB answers, and while that doesn't surprise me, it disappoints me. It being a paid lang as well as being a BASIC dialect certainly turns people off, but for those who own it it's actually pretty flexible and, surprisingly, golfable. I figured I'd open this tips thread for it and see what comes up.

I expect 12Me21 to visit frequently :)

# Answer
# Replace `string!=""` with `string>""`

SB allows you to do greater/less comparisons on strings, based on their codepoints. However, the empty string is considered the *smallest string there is.*

So for situations where you do `string!=""` you can use either `string>""` or `""<string`, since every string is greater than `""` and `""` is less than every string. Depending on whether you use `<` or `>` depends on if the statement needs whitespace before or after to be valid syntax, which can also save you bytes.

For example:

```
WHILE S$!=""

```

can be turned into

```
WHILE S$>""

```

and further golfed to

```
WHILE""<S$

```
> 11 votes

# Answer
# Using `?`, `.`, `@`, and unclosed strings

Many dialects of BASIC support `?` for printing, and SB is no exception. Having an extremely short text output function is a big advantage.

In SmileBASIC, `.` is evaluated to `0.0`, so it can be used in place of 0 to save space. For example: `SPSET 0,21` can be `SPSET.,21`, saving 1 byte. (`SPSET0,21` is invalid because `SPSET0` could be a user defined function) `EXEC.` is an extremely short way to make a program loop forever (but it resets all your variables, so it's not always usable)

Labels (used for `GOTO`, `GOSUB`, and reading `DATA`) are represented as `@LABEL` in SmileBASIC. When used in an expression, they are actually treated as strings. For example, `BGMPLAY"@305C"` can be written as `BGMPLAY@305C`

Strings are automatically closed at the end of a line (or the end of the program). `?"Hello, World!"` can be written as `?"Hello, World!`. This can also be used to make programs more readable by splitting them into multiple lines without changing the length: `?"Meow"BEEP 69` can be

```
?"Meow
BEEP 69

```
> 6 votes

# Answer
# Use string indexing instead of `MID$`

The `MID$` function is a common function in many BASICs to get a substring from somewhere in the middle of a string. However, if you just need to get the character at some index, using string indexing is far shorter. For example:

```
PRINT MID$("ABC",2,1)
PRINT "ABC"[2]

```

Both of these print C. Strings support array-like indexing on a character basis, so if you only need to check one character at a time, this is the best way to do it.
> 3 votes

# Answer
# Use the syntax highlighter!

SmileBASIC's code editor has a built in syntax highlighter, that can be used to determine whether code will work or not. For example, if you try to do `BEEP0`, it will not highlight it, because there needs to be a space between a function and a digit. However `BEEP.` works, because . is not a digit.

Normally code like `X=7BEEP` is valid, since functions can't start with a number, so SB assumes that `7` and `BEEP` are separate. However. `X=7END` is NOT allowed (and not highlighted), because it tries to interpret `7E...` as a number, but since there's no digit after the E, it fails, causing an error. Normally this would be pretty hard to figure out, but with a very reliable syntax highlighter, it's much easier to tell what you can and can't do.

My SmileBASIC syntax highlighter is designed to (hopefully) perfectly match the behavior of SB, so you can use it to check if code is valid.

```
<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <script src="https://12Me21.github.io/sbhighlight3/sbhighlight.js"></script>
  <link rel="stylesheet" type="text/css" href="https://12Me21.github.io/sbhighlight3/style.css">
  <link rel="stylesheet" type="text/css" href="https://12Me21.github.io/external/smilebasicfont.css">
  <script>
   function update(event){
    $code.textContent=$input.innerText;
    //must be innerText since contentedible and textContent are too dumb to understand linebreaks
    //contenteditable adds <br>s which textContent ignores
    //whyyyyy
    applySyntaxHighlighting($code,true);
   }

   function setCaretPosition(elem,caretPos){
    if(elem){
     if(elem.createTextRange) {
      var range=elem.createTextRange();
      range.move('character',caretPos);
      range.select();
     }else{
      if(elem.selectionStart){
       elem.focus();
       elem.setSelectionRange(caretPos,caretPos);
      }else
       elem.focus();
     }
    }
   }
  </script>
  <style>
   #editcontainer{
    position: absolute;
   }
   #editcontainer>pre{
    position: absolute;
    left: 0;
    top: 0;

   }
   pre.csssucks *{
    color:transparent !important;
    background-color:transparent !important;
    caret-color: white;
   }
   pre.csssucks {
    color:transparent !important;
    background-color:transparent !important;
    caret-color: white;
    border-color:transparent;
    padding-right: 50ch;
   }
  </style>
 </head>
 <body>
  Use SB font:<input type="checkbox" autocomplete="off" onchange="$code.dataset.sbfont=$input.dataset.sbfont=this.checked;update()"></input>
  <button onclick="update()">force update</button>
  <hr>
  <div id="editcontainer">
   <pre id="$code">test</pre>
   <pre id="$input" class="csssucks" contenteditable="true" spellcheck="false" onkeydown="setTimeout(function(){update(event)},2);">test</pre>
  </div>
 </body>
</html>
```
> 2 votes

# Answer
# When to use `:` (or not)

The `:` character is used as a statement-breaker in SB. Basically, you use it to stack statements on one line like so:

```
PRINT "HELLO!":PRINT "GOODBYE!"

```

Otherwise, your average statement is broken by a newline:

```
PRINT "HELLO!"
PRINT "GOODBYE!"

```

In reality, you often don't need to use the colon at all. So long as statements can be broken into syntactically valid tokens, the parser tends to figure out when one ends and the other starts. The same often goes for whitespace.

```
PRINT"HELLO!"PRINT"GOODBYE!"

```

Of course, this doesn't always work. There are always ambiguous cases and invalid syntaxes where you have to explicitly break statements. Take for example:

```
PRINT "HELLO";END

```

The semicolon means that `PRINT` is expecting another expression to print out, unless the statement breaks there (we use dangling semicolons to suppress the newline.) Here it assumes `END` is supposed to be a value, despite being a keyword, and tries to print it, resulting in an error. Thus, we have to explicitly break this statement, be it the colon or the newline.

In general, if something seems ambiguous, try it to see if it works. If it doesn't, break the statement. In addition, anything that would produce invalid syntax isn't highlighted correctly as 12Me21 mentioned.
> 2 votes

# Answer
# Avoid the MOD operator

The modulus operator is really long, and should be avoided if possible.

If you're getting characters from a string, you can just repeat the string instead:

```
"ABC"[X MOD 3]
("ABC"*9)[X] (assuming X will always be less than 27)

```

Sometimes you can save 1 character with `AND` instead:

```
X MOD 4
3AND X

```
> 1 votes

# Answer
# Omitting `OUT` return values

An `OUT` form function is one with multiple returns; you specify the variables to accept the return values after the `OUT` keyword. An example using `DTREAD`:

```
DTREAD OUT yearVar,monthVar,dayVar

```

But what if you only want one of the values, like the current month? You can "ignore" the rest of the values by simply not writing any variable name to accept them! You do, however, have to leave in the commas (aside from the occasional optional return.)

```
DTREAD OUT ,monthVar,

```

Which can be further golfed to

```
DTREAD OUT,M,

```
> 0 votes

# Answer
# Use `LAST()`

Now that SmileBASIC 4 is out in Japan, we can check out some of the potential golf savings. One that immediately jumps out to me is the new `LAST()` function, which returns the last index of an array or string. You can save one byte.

```
LEN(v)-1 'old way
LAST(v)  'new way

```
> 0 votes

---
Tags: code-golf, tips, basic
---


# Question
Title: Convert alphanumeric (base-36) sentences into hexadecimal (base-16) sentences
I use "sentence" here loosely to mean "any sequence of words separated by spaces" and "words" to mean "sequences of alphanumeric (hexatrigesimal) characters unseparated by spaces".

---

Conversion is from base-36 (0123456789abcdefg...) or (0123456789ABCDEFG...)

Conversion to base-16 (0123456789abcdef) or (0123456789ABCDEF)

**Bonus -1** off your byte score if you are case-insensitive on input

**Bonus -1** off your byte score if you are insensitive to non-alphanumeric characters (ignore them, except space)

---

Conversion of sentences

E.g. if your input sentence is "The meaning of life is 31313" then your out put should convert the following base-36 "words" into base-16 numbers (the, meaning, of, life, is, 31313) and then output them in order.

**Bonus -1** off your byte score for retaining spaces in output sentence

## Test Cases

You may convert these to your preferred single-case form if you choose not to opt for the case-insensitive bonus, strings end after spaces. Assume input will never start with a space.

---

```
Input text:

"The meaning of life is 31313"

Output: ("9542 B59F1602C 36F F508A 2A4 4DA897") - with or without spaces, with lower or upper case letters

```

**Bonus -1** off your byte score for removing **leading zeroes** i.e. "9542" not "000009542".

---

```
Input text:

"Jet fuel can't melt steel beams"

Output: ("6245 B47AD 8C0F9 FF371 2E28A2D 1241854")

```

---

```
Input text:

"fhs8230982t90u20's9sfd902 %2'+13jos32*'ej eos"

Output: ("74510A686B453A2B1933C7AADA25DD2 BB8E18A11AEB 4A5C")

```

## The Winner

This is , so the fewest bytes wins (including **bonus -1** bytes). :)

Can accept the inputs in any way that works, as long as your code can solve arbitrary problems like the test cases.

# Answer
# Japt `-S`, 6 - 3 = 3 bytes

```
¸®n36G

```

Saved two bytes thanks to @Shaggy

Try it
> 2 votes

# Answer
# Perl 6, 28 bytes - 2 = 26

```
{S:g{\S+}=:36(~$/).base(16)}

```

Try it online!
> 2 votes

# Answer
# MATL array, 9 - 1 = 8 bytes

```
Yb36ZA1YA

```

Try it online!

Case-insensitive, but turns spaces into line breaks.

# MATL inline, 20-2 = 18 bytes (inelligible)

```
Yb36ZA1YAO10Z(!999e!

```

Try it online!

Takes case-insensitive and preserve-spaces bonuses, (last test case fails due to implicit size assumptions = inelligible submission)

```
Yb     % Split the input at spaces, place the results in a cell array
36ZA   % convert from base-36
1YA    % Convert to hexadecimal. Gives a char array

O10Z(  % Assign char 0 to 10th column. Adds "Spaces"
!999e! % Reshape in row-major order as a 999-column char array
       % Implicitly display. Display 0 as space.

```

(I hope Luis Mendo comes and improves on this, because I got most of this from his answers here, here, here and sundar's answer here.)
> 2 votes

# Answer
# Ruby `-p`, 23-1 = 22 bytes

Only uses the case-insensitive bonus.

```
$_=$_.to_i(36).to_s(16)

```

Try it online!

## Ruby `-p`, 33-2 = 31 bytes

Takes case-insensitive and preserve-spaces bonuses.

```
gsub(/\w+/){$&.to_i(36).to_s(16)}

```

Try it online!

# Ruby `-p`, 46-3 = 43 bytes

Takes all 3 bonuses.

```
gsub(/\S+/){$&.gsub(/\W/){}.to_i(36).to_s(16)}

```

Try it online!
> 1 votes

# Answer
# Gema, 20 characters

```
<A>=@radix{36;16;$1}

```

Sample run:

```
bash-4.4$ gema '<A>=@radix{36;16;$1}' <<< 'The meaning of life is 31313'
9542 B59F1602C 36F F508A 2A4 4DA897

```

Try it online!
> 1 votes

# Answer
# 05AB1E, score 3 (4 bytes \- 1 bonus)

```
#₆öh

```

Bonus -1: no leading 0s, since this is done implicitly.
Outputs as a list of converted words.

Try it online.

---

# 05AB1E, score 8 (12 bytes \- 4 bonus)

```
u#εžKÃ}₆öhðý

```

All four bonuses:
-1 for no leading 0s, since this is done implicitly;
-1 case-insensitivity by first converting to uppercase with `u`;
-1 for retaining spaces in the output by joining the list by spaces with `ðý`;
-1 for ignoring every character apart from `[A-Za-z0-9 ]`, by keeping `[A-Za-z0-9]` after the split\_on\_spaces with `εžKÃ}`

Try it online.

**Explanation:**

```
#             # Split the (implicit) input-string on spaces
 ₆ö           # Convert each string from base-36 to integers
   h          # Convert those integers to hexadecimal
              # (and output the list implicitly as result)

u             # Convert the (implicit) input to uppercase
 #            # Split it on spaces
  ε           # Map each string to:
   žK         #  Push builtin string "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
     Ã        #  And only keep those characters in the mapped string
      }₆ö     # After the map: convert each string from base-36 to integer
         h    # Convert those integer to hexadecimal
          ðý  # And join them by spaces
              # (after which the result is output implicitly)

```
> 1 votes

# Answer
# Python 2, 47 - 2 = 45 bytes

```
lambda S:[hex(int(s,36))[2:]for s in S.split()]

```

Try it online!

Because case insensitive. And also leading `0`s.
> 0 votes

# Answer
# Perl 5 `-Mbigint -MList::Util=reduce -p`, 92 - 4 = 88 bytes

```
y/_/*/;s|\S+|Math::BigInt::as_hex reduce{$a*36+$b}map{7x/\d/+ord(uc)-55}$&=~/\w/g|ge;s/0x//g

```

Try it online!

Qualifies for all 4 bonuses (case insensitive, keeps spaces, ignores punctuation, no leading 0s). Handles even large test cases properly, including the last one.
> 0 votes

# Answer
# Charcoal, 14 bytes - 1, score 13

```
⪫Ｅ⪪Ｓ ⍘⍘ι³⁶¦¹⁶

```

Try it online! Link is to verbose version of code. Only qualifies for the leading zeros bonus. Explanation:

```
   Ｓ            Input string
  ⪪             Split on spaces
 Ｅ              Map over words
       ι        Current word
      ⍘ ³⁶      Convert from base 36
     ⍘     ¹⁶   Convert to base 16
⪫               Join on spaces
                Implicitly print

```
* If output of the hex numbers on separate lines is acceptable, then the first and last characters can be removed for a 2-byte saving.
* Case insensitive input is possible at a cost of 1 byte, which would not affect the score.
* Preservation of multiple spaces is possible at a cost of 2 bytes, unless the current misbehaviour is a Charcoal bug, in which case it would work once the bug is fixed.
* Skipping of punctuation is possible at a cost of 4 bytes. (Currently the only supported case is a single trailing `.`)
> 0 votes

# Answer
# Java, 94-2 = 92 bytes

These "bonuses" are too expensive to intentionally claim. I get case insensitive and leading zeros for free though.

```
s->{for(var w:s.split(" "))System.out.print(new java.math.BigInteger(w,36).toString(16)+" ");}

```

TIO
> 0 votes

# Answer
# Ecmascript 2020, score 90 - 3 = 87

Likely it would be there, already works in Firefox 68+ and Chrome 67+.

```
s=>s.replace(/\w+/g,x=>[...x].reduce((r,x)=>36n*r+BigInt(parseInt(x,36)),0n).toString(16))

```

Bonuses:

* Bonus -1 off your byte score if you are case-insensitive on input
* Bonus -1 off your byte score for retaining spaces in output sentence
* Bonus -1 off your byte score for removing leading zeroes i.e. "9542" not "000009542".

Test:

```
f=s=>s.replace(/\w+/g,x=>[...x].reduce((r,x)=>36n*r+BigInt(parseInt(x,36)),0n).toString(16))

console.log([
["The meaning of life is 31313", "9542 B59F1602C 36F F508A 2A4 4DA897"],
["Jet fuel can't melt steel beams", "6245 B47AD 8C0F9 FF371 2E28A2D 1241854"],
["fhs8230982t90u20's9sfd902 %2'+13jos32*'ej eos", "74510A686B453A2B1933C7AADA25DD2 BB8E18A11AEB 4A5C"],
["  123   1234   tyu ", "  55B   C0D0   97B6 "],
].map(([t,k])=>f(t.replace(/(?!\s|_)\W/g,"")).toUpperCase()==k))
```
> 0 votes

---
Tags: code-golf, base-conversion, alphabet, cryptography, hexadecimal
---


# Question
Title: Is there are exactly one partition, given length of partition and maximum number?
It is Restricted Integer Partitions, but with maximum number.

# Question

Three positive integers are given. First number is number to divide, second number is length of partition, and third number is maximum number. First number is always largest, and bigger than other two.

For example, `5, 2, 3`. Then, make partition of `5` which have `2` parts, and maximum number you can use is `3`. Note that you don't have to use `3` : maximum number can be `2` or `1`.

In this case, there is only one partition : `3, 2`.

Partition is unordered : which means `3 + 2` and `2 + 3` is same.

But in case like `7, 3, 3`, there are two partition : `3, 3, 1` and `3, 2, 2`.

To make it sure, **You can use third number as largest number, but you don't have to use it.** So `5, 4, 3` is true.

Question is : Is there are more than one partition, given length and maximum number?

Output is `True` or `1` or whatever you want when there is only one partition, and `False` or `0` or whatever you want where there are more than one partition, or no partition.

# Winning condition

This is code golf, so code with shortest byte wins.

# Examples

Input -\> Output

```
7, 6, 2 -> True (2+1+1+1+1+1) : 1 partitions
5, 4, 4 -> True (2+1+1+1) : 1 partitions
5, 4, 3 -> True (2+1+1+1) : 1 partitions
5, 4, 2 -> True (2+1+1+1) : 1 partitions
5, 3, 2 -> True (2+2+1) : 1 partitions
7, 2, 3 -> False no partitions
7, 2, 2 -> False no partitions
7, 2, 1 -> False no partitions
9, 5, 3 -> False (3+3+1+1+1), (3+2+2+1+1), (2+2+2+2+1) : 3 partitions
6, 3, 3 -> False (3+2+1), (2+2+2) : 2 partitions

```

# Answer
# Python 2, 38 bytes

```
lambda n,k,m:m>n-k<2or-1<k*m-n<2+2/m*k

```

Try it online!

Characterizes the cases where there's only one legal partition.

Consider the partitions of \\$n\\$ into exactly \\$k\\$ parts each between \\$1\\$ and \\$m\\$ inclusive. There's only two ways to for there to be only one such partition.

* The number \\$n\\$ is close to as small as possible (\\$n=k\\$ or \\$n=k+1)\\$ or as large as possible (\\$n=mk-1\\$ or \\$n=mk)\\$ for such a partitions. This leave only enough "wiggle room" for only one partition in each case:
    + \\$n=1+1+\cdots +1+1\\$.
    + \\$n=2+1+\cdots+1+1\\$.
    + \\$n=m+m+\cdots+m+(m-1)\\$.
    + \\$n=m+m+\cdots+m+m\\$.
* We allow only \\$m=2\\$ maximum, forcing a unique partition made of 1's and 2's. Such a partition requires \\$k \leq n \leq 2k\\$.

The challenge lets us assume that \\$n\>k\\$, so we can omit the \\$n=k\\$ case and \\$k \leq n\\$ check, and, as feersum observed, can let us check \\$n=k+1\\$ as \\$n\<k+2\\$. The \\$m=1\\$ case makes it impossible to make a partition with \\$n\>k\\$, so we make sure it's always rejected. This gives the condition

> \\$n \in \\{ k+1, mk-1, mk\\}\\$and \\$ m\>1\\$, or \\$n \leq 2k \\$ and \\$m=2\\$
> 7 votes

# Answer
# Wolfram Language (Mathematica), ~~39~~ 38 bytes

-1: first argument \> other arguments (no length-1 partitions)

```
1==Tr[1^IntegerPartitions[#,{#2},#3]]&

```

Try it online!
> 2 votes

# Answer
# Jelly, (10?) 11 bytes

```
Œṗṁ«⁵ɗƑƇL⁼1

```

A full program which accepts `N numberOfParts maximalSizeOfAnyPart` as arguments and prints `1` if exactly one solution exists and `0` otherwise.

**Try it online!**

### How?

```
Œṗṁ«⁵ɗƑƇL⁼1 - Main Link: N, numberOfParts
Œṗ          - integer partitions (of N)
       Ƈ    - keep those (P) for which:
      Ƒ     -   is invariant under:
     ɗ      -     last three links as a dyad - i.e. f(P, numberOfParts):
  ṁ         -       mould (P) like (numberOfParts)
    ⁵       -       3rd argument (maximalSizeOfAnyPart)
   «        -       minimum (vectorises)
        L   - length
          1 - literal one
         ⁼  - equal?
            - implicit print

```

---

If we may print `1` if exactly one solution exists and `0` OR nothing otherwise then `Œṗṁ«⁵ɗƑƇMỊ` is a 10 byte full program.
> 2 votes

# Answer
# 05AB1E, 8 bytes

```
ÅœIù€à@O

```

Try it online!

Outputs truthy when there’s exactly one partition, falsy otherwise. (All numbers except 1 are falsy in 05AB1E, which makes this convenient).

```
Åœ                    # integer partitions of the first input
  Iù                  # keep only those with length equal to the second input
    €à                # take the maximum of each one
      @               # test if the third input >= each one
       O              # sum

```
> 2 votes

# Answer
# Jelly, 7 bytes

```
œċ§ċ⁵=1

```

Try it online!

A full program taking the arguments in the order maximum part, number of parts, sum (i.e. reversed from original question).

### Explanation

```
œċ      | Combinations with replacement (using maximum part size and number of parts)
   §    | Sum (vectorises)
    ċ⁵  | Count occurrences of desired integer from question
     =1 | Check if equal to 1

```
> 1 votes

---
Tags: code-golf, integer-partitions
---


# Question
Title: Convert between Korean two-set keyboard and qwerty keyboard
# Introduction

It is somewhat like DVORAK Keyboard layout , but MUCH harder.

Let's talk about the Korean keyboard first. As you can see in Wikipedia, there is a Kor/Eng key to change between Korean and English key sets.

Koreans sometime type wrong : they attempt to write in Korean on a qwerty keyboard or in English on a two-set keyboard.

So, here's the problem : if given Korean characters typed in two-set keyboard, convert it to alphabetic characters typed in qwerty keyboard. If given alphabetic characters typed in qwerty, change it to two-set keyboard.

# Two-set Keyboard

Here is the two-set keyboard layout :

```
ㅂㅈㄷㄱㅅㅛㅕㅑㅐㅔ
 ㅁㄴㅇㄹㅎㅗㅓㅏㅣ
  ㅋㅌㅊㅍㅠㅜㅡ

```

and with shift key :

```
ㅃㅉㄸㄲㅆㅛㅕㅑㅒㅖ

```

just the top row changes while the others do not.

# About Korean Characters

if it ended here, it could be easy, but no. When you type

```
dkssud, tprP!

```

output is not shown in this way:

```
ㅇㅏㄴㄴㅕㅇ, ㅅㅔㄱㅖ!

```

but in this way :

```
안녕, 세계!(means Hello, World!)

```

and it makes things much harder.

Korean Characters separate into three parts : 'Choseong(consonant)', 'Jungseong(Vowel)', and 'Jongseong(consonant in the end of syllable : can be blank)', and you have to separate it.

Fortunately, there is way to do that.

# How to separate

There are 19 Choseong, 21 Jungseong, and 28 Jongseong(with blank), and 0xAC00 is '가', first character of the Korean characters. Using this, we can separate Korean characters into three parts. Here is the order of each and its position in two-set keyboard.

choseong order :

```
ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ
r R s e E f a q Q t T d w W c z x v g

```

jungseong order :

```
ㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅣ
k o i O j p u P h hk ho hl y n nj np nl b m ml l

```

jongseong order :

```
()ㄱㄲㄳㄴㄵㄶㄷㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅄㅅㅆㅇㅈㅊㅋㅌㅍㅎ
()r R rt s sw sg e f fr fa fq ft fx fv fg a q qt t T d w c z x v g

```

Let's say `(unicode value of some character) - 0xAC00` is `Korean_code`, and index of Choseong, Jungseong, Jongseong is `Cho`, `Jung`, `Jong`.

Then, `Korean_code` is `(Cho * 21 * 28) + Jung * 28 + Jong`

Here is the javascript code which separate Korean character from this Korean website, for your convenience.

```
var rCho = [ "ㄱ", "ㄲ", "ㄴ", "ㄷ", "ㄸ", "ㄹ", "ㅁ", "ㅂ", "ㅃ", "ㅅ", "ㅆ", "ㅇ", "ㅈ", "ㅉ", "ㅊ", "ㅋ", "ㅌ", "ㅍ", "ㅎ" ];
var rJung =[ "ㅏ", "ㅐ", "ㅑ", "ㅒ", "ㅓ", "ㅔ", "ㅕ", "ㅖ", "ㅗ", "ㅘ", "ㅙ", "ㅚ", "ㅛ", "ㅜ", "ㅝ", "ㅞ", "ㅟ", "ㅠ", "ㅡ", "ㅢ", "ㅣ" ];
var rJong = [ "", "ㄱ", "ㄲ", "ㄳ", "ㄴ", "ㄵ", "ㄶ", "ㄷ", "ㄹ", "ㄺ", "ㄻ", "ㄼ", "ㄽ", "ㄾ","ㄿ", "ㅀ", "ㅁ", "ㅂ", "ㅄ", "ㅅ", "ㅆ", "ㅇ", "ㅈ", "ㅊ", "ㅋ", "ㅌ", "ㅍ", "ㅎ" ];
var cho, jung, jong;
var sTest = "탱";
var nTmp = sTest.charCodeAt(0) - 0xAC00;
jong = nTmp % 28; // Jeongseong
jung = ((nTmp - jong) / 28 ) % 21 // Jungseong
cho = ( ( (nTmp - jong) / 28 ) - jung ) / 21 // Choseong

alert("Choseong:" + rCho[cho] + "\n" + "Jungseong:" + rJung[jung] + "\n" + "Jongseong:" + rJong[jong]);

```

# When assembled

1. Note that , , , , , ,  is a combination of other jungseongs.

```
ㅗ+ㅏ=ㅘ, ㅗ+ㅐ=ㅙ, ㅗ+ㅣ=ㅚ, ㅜ+ㅓ=ㅝ, ㅜ+ㅔ=ㅞ, ㅜ+ㅣ=ㅟ, ㅡ+ㅣ=ㅢ

```
2. Choseong is necessary. That means, if `frk` is given, which is `ㄹㄱㅏ`, it can change in two way : `ㄺㅏ` and `ㄹ가`. Then, you have to convert it into a way which has choseong. If `jjjrjr` given, which is `ㅓㅓㅓㄱㅓㄱ`, leading s don't have anything that can be choseong, but the fourth  has  that can be choseong, so it's changed into `ㅓㅓㅓ걱`.

Another example : `세계`(`tprP`). It can be changed to `섹ㅖ`(`(ㅅㅔㄱ)(ㅖ)`), but because choseong is necessary, it's changed into `세계`(`(ㅅㅔ)(ㄱㅖ)`)

# Examples

input 1

```
안녕하세요

```

output 1

```
dkssudgktpdy

```

input 2

```
input 2

```

output 2

```
ㅑㅞㅕㅅ 2

```

input 3

```
힘ㄴㄴ

```

output 3

```
glass

```

input 4

```
아희(Aheui) is esolang which you can program with pure Korean characters.

```

output 4

```
dkgml(모뎌ㅑ) ㅑㄴ ㄷ내ㅣ뭏 조ㅑ초 ㅛㅐㅕ ㅊ무 ㅔ갷ㄱ므 쟈소 ㅔㅕㄱㄷ ㅏㅐㄱㄷ무 촘ㄱㅁㅊㅅㄷㄱㄴ.

```

input 5

```
dkssud, tprP!

```

output 5

```
안녕, 세계!

```

input 6

```
ㅗ디ㅣㅐ, 째깅! Hello, World!

```

output 6

```
hello, World! ㅗ디ㅣㅐ, 째깅!

```

**Shortest code wins.**(in bytes)

# New rule for you convenience

You can dismiss characters like `A` which do not have its counterpart in two-set keyboard. so `Aheui` to `Aㅗ뎌ㅑ` is OK. But, if you change `Aheui` to `모뎌ㅑ`, you can get -5 point, so you can earn 5 bytes.

You can separate two jungseongs(like  to `ㅗ+ㅏ`). like `rhk` to `고ㅏ`, or `how` to `ㅗㅐㅈ`. But if you combine it(like `rhk` to  or `how` to `ㅙㅈ`), you can earn additional -5 points.

# Answer
# Jelly, ~~296~~ 264 bytes

```
Ẏœṣjƭƒ
“ȮdȥŒ~ṙ7Ṗ:4ȦịØ¹ʂ ="÷Ƥi-ẓdµ£f§ñỌ¥ẋaḣc~Ṡd1ÄḅQ¥_æ>VÑʠ|⁵Ċ³(Ė8ịẋs|Ṇdɼ⁼:Œẓİ,ḃṙɠX’ṃØẠs2ḟ€”A
“|zƒẉ“®6ẎẈ3°Ɠ“⁸)Ƙ¿’ḃ2’T€ị¢
¢ĖẈṪ$ÞṚƊ€
3£OŻ€3¦ŒpFḟ0Ɗ€J+“Ḥœ’,ƲyO2£OJ+⁽.[,Ʋ¤y¹ỌŒḊ?€µ¢ṖŒpZF€’ḋ588,28+“Ḥþ’Ʋ0;,ʋ/ṚƲ€ñṣ0ḊḢ+®Ṫ¤Ɗ;ṫ®$Ɗ¹Ḋ;⁶Ṫ⁼ṁ@¥¥Ƈ@¢ṪẈṪ‘;Ʋ€¤ḢƲ©?€ṭḢƲF2£żJ+⁽.[Ɗ$ẈṪ$ÞṚ¤ñỌ

```

Try it online!

A full program that takes a string as its argument and returns a string (which is implicitly printed). This works in three passes: first it converts all Korean characters to lists of code points for the Latin letters. Then it identifies and builds the compound Korean characters. Finally, it turns any remaining stray Latin letters to the Korean equivalent. Note that other characters and Latin letters that don’t appear in the spec (e.g. `A`) are left alone.

If conversion to lower case of capital letters outside spec is needed, this can be done at a cost of an additional 10 bytes.

### Explanation

**Helper link 1**: dyadic link with arguments x and y. x is a list of pairs of search and replace sublists. y will have each search sublist replaced with the corresponding replace sublist

```
Ẏ      | Tighten (reduce to a single list of alternating search and replace sublists)
     ƒ | Reduce using y as starting argument and the following link:
    ƭ  | - Alternate between using the following two links:
 œṣ    |   - Split at sublist
   j   |   - Join using sublist

```

**Helper link 2**: List of Latin characters/character pairs in the order that corresponds to the Unicode order of the Korean characters

```
“Ȯ..X’          | Base 250 integer 912...
      ṃØẠ       | Base decompress into Latin letters (A..Za..z)
         s2     | Split into twos
           ḟ€”A | Filter out A from each (used as filler for the single characters)

```

**Helper link 3**: Lists of Latin characters used for Choseong, Jungseong and Jongseong

```
“|...¿’        | List of base 250 integers, [1960852478, 2251799815782398, 2143287262]
       ḃ2      | Convert to bijective base 2
         ’     | Decrease by 1
          T€   | List of indices of true values for each list
            ị¢ | Index into helper link 2

```

**Helper link 4**: Above lists of Latin characters enumerated and sorted in decreasing order of length

```
¢         | Helper link 3 as a nilad
       Ɗ€ | For each list, the following three links as a monad
 Ė        | - Enumerate (i.e. prepend a sequential index starting at 1 to each member of the list)
    $Þ    | - Sort using, as a key, the following two links as a monad
  Ẉ       |   - Lengths of lists
   Ṫ      |   - Tail (this will be the length of the original character or characters)
      Ṛ   | - Reverse

```

**Main link**: Monad that takes a Jelly string as its argument and returns the translated Jelly string

*Section 1*: Convert morphemic blocks to the Unicode codepoints of the corresponding Latin characters

*Section 1.1*: Get the list of Latin character(s) needed to make the blocks

```
3£      | Helper link 3 as a nilad (lists of Latin characters used for Choseong, Jungseong and Jongseong)
  O     | Convert to Unicode code points
   Ż€3¦ | Prepend a zero to the third list (Jongseong)

```

*Section 1.2*: Create all combinations of these letters (19×21×28 = 11,172 combinations in the appropriate lexical order)

```
Œp      | Cartesian product
     Ɗ€ | For each combination:
  F     | - Flatten
   ḟ0   | - Filter zero (i.e. combinations with an empty Jonseong)

```

*Section 1.3*: Pair the Unicode code points of the blocks with the corresponding list of Latin characters, and use these to translate the morphemic blocks in the input string

```
       Ʋ   | Following as a monad
J          | - Sequence from 1..11172
 +“Ḥœ’     | - Add 44031
      ,    | - Pair with the blocks themelves
        y  | Translate the following using this pair of lists
         O | - The input string converted to Unicode code points

```

*Section 2*: Convert the individual Korean characters in the output from section 1 to the code points of the Latin equivalent

```
          ¤  | Following as a nilad
2£           | Helper link 2 (list of Latin characters/character pairs in the order that corresponds to the Unicode order of the Korean characters)
  O          | Convert to Unicode code points
         Ʋ   | Following as a monad:
   J         | - Sequence along these (from 1..51)
    +⁽.[     | - Add 12592
        ,    | - Pair with list of Latin characters
           y | Translate the output from section 1 using this mapping

```

*Section 3*: Tidy up untranslated characters in the output from section 2 (works because anything translated from Korean will now be in a sublist and so have depth 1)

```
  ŒḊ?€  | For each member of list if the depth is 1:
¹       | - Keep as is
 Ọ      | Else: convert back from Unicode code points to characters
      µ | Start a new monadic chain using the output from this section as its argument

```

*Section 4*: Convert morphemic blocks of Latin characters into Korean

*Section 4.1*: Get all possible combinations of Choseong and Jungseong

```
¢    | Helper link 4 (lists of Latin characters enumerated and sorted in decreasing order of length)
 Ṗ   | Discard last list (Jongseong)
  Œp | Cartesian product

```

*Section 4.2*: Label each combination with the Unicode code point for the base morphemic block (i.e. with no Jongseong)

```
                       Ʋ€ | For each Choseong/Jungseong combination
Z                         | - Transpose, so that we now have e.g. [[1,1],["r","k"]]
 F€                       | - Flatten each, joining the strings together
                    ʋ/    | - Reduce using the following as a dyad (effectively using the numbers as left argument and string of Latin characters as right)
                Ʋ         |   - Following links as a monad
   ’                      |     - Decrease by 1
    ḋ588,28               |     - Dot product with 21×28,28
           +“Ḥþ’          |     - Add 44032
                 0;       |     - Prepend zero; used for splitting in section 4.3 before each morphemic block (Ż won’t work because on a single integer it produces a range)
                   ,      |     - Pair with the string of Latin characters
                      Ṛ   |   - Reverse (so we now have e.g. ["rk", 44032]

```

*Section 4.3*: Replace these strings of Latin characters in the output from section 3 with the Unicode code points of the base morphemic block

```
ñ   | Call helper link 1 (effectively search and replace)
 ṣ0 | Split at the zeros introduced in section 4.2

```

Section 4.4: Identify whether there is a Jongseong as part of each morphemic block

```
                                        Ʋ | Following as a monad:
Ḋ                                         | - Remove the first sublist (which won’t contain a morphemic block; note this will be restored later)
                                     €    | - For each of the other lists Z returned by the split in section 4.3 (i.e. each will have a morphemic block at the beginning):
                                  Ʋ©?     |   - If the following is true (capturing its value in the register in the process)
             Ḋ                            |     - Remove first item (i.e. the Unicode code point for the base morphemic block introduced in section 4.3)
              ;⁶                          |     - Append a space (avoids ending up with an empty list if there is nothing after the morphemic block code point)
                                          |       (Output from the above will be referred to as X below)
                                ¤         |       * Following as a nilad (call this Y):
                        ¢                 |         * Helper link 4
                         Ṫ                |         * Jongseong
                              Ʋ€          |         * For each Jongseong Latin list:
                          Ẉ               |           * Lengths of lists
                           Ṫ              |           * Tail (i.e. length of Latin character string)
                            ‘             |           * Increase by 1
                             ;            |           * Prepend this (e.g. [1, 1, "r"]
                     ¥Ƈ@                  |     - Filter Y using X from above and the following criteria
                Ṫ                         |       - Tail (i.e. the Latin characters for the relevant Jongseong
                 ⁼ṁ@¥                     |       - is equal to the beginning of X trimmed to match the relevant Jongseong (or extended but this doesn’t matter since no Jongseong are a double letter)
                                  Ḣ       |       - First matching Jongseong (which since they’re sorted by descending size order will prefer the longer one if there is a matching shorter one)
           Ɗ                              | - Then: do the following as a monad (note this is now using the list Z mentioned much earlier):
      Ɗ                                   |   - Following as a monad
 Ḣ                                        |     - Head (the Unicode code point of the base morphemic block)
  +®Ṫ¤                                    |     - Add the tail of the register (the position of the matched Jongsepng in the list of Jongseong)
       ;                                  |   - Concatenate to:
        ṫ®$                               |     - The rest of the list after removing the Latin characters representing the Jongseong
            ¹                             | - Else: leave the list untouched (no matching Jongseong)
                                       ṭ  | - Prepend:
                                        Ḣ |   - The first sublist from the split that was removed at the beginning of this subsection

```

*Section 5*: Handle remaining Latin characters that match Korean ones but are not part of a morphemuc block

```
F                   | Flatten
                ¤   | Following as a nilad
 2£                 | - Helper link 2 (Latin characters/pairs of characters in Unicode order of corresponding Korean character)
          $         | - Following as a monad
   ż     Ɗ          |   - zip with following as a monad
    J               |     - Sequence along helper link 2 (1..51)
     +⁽.[           |     - Add 12592
             $Þ     | - Sort using following as key
           Ẉ        |   - Lengths of lists
            Ṫ       |   - Tail (i.e. length of Latin string)
               Ṛ    | - Reverse
                 ñ  | Call helper link 1 (search Latin character strings and replace with Korean code points)
                  Ọ | Finally, convert all Unicode code points back to characters and implicitly output

```
> 6 votes

# Answer
# JavaScript (Node.js), ~~587~~ ~~582~~ ~~575~~ ~~569~~ ~~557~~ ~~554~~ ~~550~~ 549 bytes

tfw you didn't know that `string.charCodeAt() == string.charCodeAt(0)`.

```
s=>s.replace(eval(`/[ㄱ-힣]|${M="(h[kol]?|n[jpl]?|ml?|[bi-puyOP])"}|([${S="rRseEfaqQtTdwWczxvg"}])(${M}((s[wg]|f[raqtxvg]|qt|[${S}])(?!${M}))?)?/g`,L="r,R,rt,s,sw,sg,e,E,f,fr,fa,fq,ft,fx,fv,fg,a,q,Q,qt,t,T,d,w,W,c,z,x,v,g,k,o,i,O,j,p,u,P,h,hk,ho,hl,y,n,nj,np,nl,n,m,ml,l".split`,`,l=L.filter(x=>!/[EQW]/.test(x)),I="indexOf"),(a,E,A,B,C,D)=>a<"~"?E?X(E):A&&C?F(43193+S[I](A)*588+L[I](C)*28+l[I](D)):X(A)+X(C)+X(D):(b=a.charCodeAt()-44032)<0?L[b+31439]||a:S[b/588|0]+L[30+b/28%21|0]+["",...l][b%28],F=String.fromCharCode,X=n=>n?F(L[I](n)+12593):"")

```

Try it online!

547 if characters outside alphabets and korean jamos can be ignored.

Okay I struggled for so long to write this, but this should work. ~~No Korean jamo/syllable is used because they are too expensive (3 bytes per use).~~ Used in the regular expression to save bytes.

```
s=>                                                    // Main Function:
 s.replace(                                            //  Replace all convertible strings:
  eval(
   `/                                                  //   Matching this regex:
    [ㄱ-힣]                                             //   ($0) All Korean jamos and syllables
    |${M="(h[kol]?|n[jpl]?|ml?|[bi-puyOP])"}           //   ($1) Isolated jungseong codes
    |([${S="rRseEfaqQtTdwWczxvg"}])                    //   ($2) Choseong codes (also acts as lookup)
     (                                                 //   ($3) Jungseong and jongseong codes:
      ${M}                                             //   ($4)  Jungseong codes
      (                                                //   ($5)  Jongseong codes:
       (                                               //   ($6)
        s[wg]|f[raqtxvg]|qt                            //          Diagraphs unique to jongseongs
        |[${S}]                                        //          Or jamos usable as choseongs
       )
       (?!${M})                                        //         Not linked to the next jungseong
      )?                                               //        Optional to match codes w/o jongseong
     )?                                                //       Optional to match choseong-only codes
   /g`,                                                //   Match all
   L="(...LOOKUP TABLE...)".split`,`,                  //   Lookup table of codes in jamo order
   l=L.filter(x=>!/[EQW]/.test(x)),                    //   Jongseong lookup - only first half is used
   I="indexOf"                                         //   [String|Array].prototype.indexOf
  ),
  (a,E,A,B,C,D)=>                                      //   Using this function:
   a<"~"?                                              //    If the match is code (alphabets):
    E?                                                 //     If isolated jungseongs code:
     X(E)                                              //      Return corresponding jamo
    :A&&C?                                             //     Else if complete syllable code:
     F(43193+S[I](A)*588+L[I](C)*28+l[I](D))           //      Return the corresponding syllable
    :X(A)+X(C)+X(D)                                    //     Else return corresponding jamos joined
   :(b=a.charCodeAt()-44032)<0?                        //    Else if not syllable:
    L[b+31439]||a                                      //     Return code if jamo (if not, ignore)
   :S[b/588|0]+L[30+b/28%21|0]+["",...l][b%28],        //    Else return code for the syllable
  F=String.fromCharCode,                               //   String.fromCharCode
  X=n=>                                                //   Helper function to convert code to jamo
   n?                                                  //    If not undefined:
    F(L[I](n)+12593)                                   //     Return the corresponding jamo
   :""                                                 //    Else return empty string
 )

```
> 3 votes

# Answer
# Wolfram Language (Mathematica), ~~405~~ ~~401~~ 400 bytes

```
c=CharacterRange
p=StringReplace
q=StringReverse
r=Reverse
t=Thread
j=Join
a=j[alphabet@"Korean",4520~c~4546]
x=j[#,r/@#]&@t[a->Characters@"rRseEfaqQtTdwWczxvgkoiOjpuPh"~j~StringSplit@"hk ho hl y n nj np nl b m ml l r R rt s sw sg e f fr fa fq ft fx fv fg a q qt t T d w c z x v g"]
y=t[""<>r@#&/@Tuples@TakeList[Insert[a,"",41]~p~x~p~x,{19,21,28}]->44032~c~55203]
f=q@p[q@#,#2]&
g=f[#,r/@y]~p~x~f~y&

```

Try it online!

Slightly ungolfed

To test this in Mathematica just replace `alphabet` with `Alphabet`; however, TIO doesn't support the Wolfram Cloud so I defined `Alphabet["Korean"]` in the header.

We first decompose all Hangul syllables to the Hangul alphabet, then swap Latin and Hangul characters, then recompose the syllables.
> 2 votes

# Answer
# Java 19, ~~1133~~ ~~1126~~ 1133 bytes

```
s->{String r="",k="ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ ㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅣ ㄱㄲㄳㄴㄵㄶㄷㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅄㅅㅆㅇㅈㅊㅋㅌㅍㅎ",K[]=k.split(" "),a="r R s e E f a q Q t T d w W c z x v g k o i O j p u P h hk ho hl y n nj np nl b m ml l r R rt s sw sg e f fr fa fq ft fx fv fg a q qt t T d w c z x v g";var A=java.util.Arrays.asList(a.split(" "));k=k.replace(" ","");int i,z,y,x=44032;for(var c:s.toCharArray())if(c>=x&c<55204){z=(i=c-x)%28;y=(i=(i-z)/28)%21;s=s.replace(c+r,r+K[0].charAt((i-y)/21)+K[1].charAt(y)+(z>0?K[2].charAt(z-1):r));}for(var c:s.split(r))r+=c.charAt(0)<33?c:(i=k.indexOf(c))<0?(i=A.indexOf(c))<0?c:k.charAt(i):A.get(i);for(i=r.length()-1;i-->0;r=z>0?r.substring(0,i)+(char)(K[0].indexOf(r.charAt(i))*588+K[1].indexOf(r.charAt(i+1))*28+((z=K[2].indexOf(r.charAt(i+2)))<0?0:z+1)+x)+r.substring(z<0?i+2:i+3):r)for(z=y=2;y-->0;)z&=K[y].contains(r.charAt(i+y)+"")?2:0;for(var p:"ㅗㅏㅘㅗㅐㅙㅗㅣㅚㅜㅓㅝㅜㅔㅞㅜㅣㅟㅡㅣㅢ".split("(?<=\\G...)"))r=r.replace(p.substring(0,2),p.substring(2));return r;}

```

Outputs with capital letters `ASDFGHJKLZXCVBNM` unchanged, since `.toLowerCase()` costs more than the -5 bonus.

Back +7 bytes as a bug-fix for non-Korean characters above unicode value 20,000 (thanks *@NickKennedy* for noticing).

Try it online.

**Explanation:**

```
s->{                         // Method with String as both parameter and return-type
  String r="",               //  Result-String, starting empty
         k="ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ ㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅣ ㄱㄲㄳㄴㄵㄶㄷㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅄㅅㅆㅇㅈㅊㅋㅌㅍㅎ",
                             //  String containing the Korean characters
         K[]=k.split(" "),   //  Array containing the three character-categories
         a="r R s e E f a q Q t T d w W c z x v g k o i O j p u P h hk ho hl y n nj np nl b m ml l r R rt s sw sg e f fr fa fq ft fx fv fg a q qt t T d w c z x v g";
                             //  String containing the English characters
  var A=java.util.Arrays.asList(a.split(" "));
                             //  List containing the English character-groups
  k=k.replace(" ","");       //  Remove the spaces from the Korean String
  int i,z,y,                 //  Temp integers
      x=44032;               //  Integer for 0xAC00
  for(var c:s.toCharArray()) //  Loop over the characters of the input:
    if(c>=x&c<55204){        //   If the unicode value is in the range [44032,55203]
                             //   (so a Korean combination character):
      z=(i=c-x)%28;          //    Set `i` to this unicode value - 0xAC00,
                             //    And then `z` to `i` modulo-28
      y=(i=(i-z)/28)%21;     //    Then set `i` to `i`-`z` integer divided by 28
                             //    And then `y` to `i` modulo-21
      s=s.replace(c+r,       //    Replace the current non-Korean character with:
        r+K[0].charAt((i-y)/21)
                             //     The corresponding choseong
         +K[1].charAt(y)     //     Appended with jungseong
         +(z>0?K[2].charAt(z-1):r));}
                             //     Appended with jongseong if necessary
  for(var c:s.split(r))      //  Then loop over the characters of the modified String:
    r+=                      //   Append to the result-String:
       c.charAt(0)<33?       //    If the character is a space:
        c                    //     Simply append that space
       :(i=k.indexOf(c))<0?  //    Else-if the character is NOT a Korean character:
         (i=A.indexOf(c))<0? //     If the character is NOT in the English group List:
          c                  //      Simply append that character
         :                   //     Else:
          k.charAt(i)        //      Append the corresponding Korean character
       :                     //    Else:
        A.get(i);            //     Append the corresponding letter
  for(i=r.length()-1;i-->0   //  Then loop `i` in the range (result-length - 2, 0]:
      ;                      //    After every iteration:
       r=z>0?                //     If a group of Korean characters can be merged:
          r.substring(0,i)   //      Leave the leading part of the result unchanged
          +(char)(K[0].indexOf(r.charAt(i))
                             //      Get the index of the first Korean character,
                   *588      //      multiplied by 588
                  +K[1].indexOf(r.charAt(i+1))
                             //      Get the index of the second Korean character,
                   *28       //      multiplied by 28
                  +((z=K[2].indexOf(r.charAt(i+2)))
                             //      Get the index of the third character
                    <0?      //      And if it's a Korean character in the third group:
                      0:z+1) //       Add that index + 1
                  +x         //      And add 0xAC00
                 )           //      Then convert that integer to a character
          +r.substring(z<0?i+2:i+3)
                             //      Leave the trailing part of the result unchanged as well
         :                   //     Else (these characters cannot be merged)
          r)                 //      Leave the result the same
     for(z=y=2;              //   Reset `z` to 2
         y-->0;)             //   Inner loop `y` in the range (2, 0]:
       z&=                   //    Bitwise-AND `z` with:
         K[y].contains(      //     If the `y`'th Korean group contains
           r.charAt(i+y)+"")?//     the (`i`+`y`)'th character of the result
          2                  //      Bitwise-AND `z` with 2
         :                   //     Else:
          0;                 //      Bitwise-AND `z` with 0
                             //   (If `z` is still 2 after this inner loop, it means
                             //    Korean characters can be merged)
  for(var p:"ㅗㅏㅘㅗㅐㅙㅗㅣㅚㅜㅓㅝㅜㅔㅞㅜㅣㅟㅡㅣㅢ".split("(?<=\\G...)"))
                             //  Loop over these Korean character per chunk of 3:
    r=r.replace(p.substring(0,2),
                             //   Replace the first 2 characters in this chunk
         p.substring(2));    //   With the third one in the result-String
  return r;}                 //  And finally return the result-String

```
> 2 votes

---
Tags: code-golf, keyboard
---


# Question
Title: Using the smallest number of bytes of code, write a program that produces this image
# Context:

Gynvael Coldwind, a famous security researcher, published a contest in his blog post (that is now complete). The goal was similar to the one described here, but with certain restrictions depending on which of the three allowed programming languages was chosen. I found the exercise fun and wanted to extend the challenge to all programming languages allowed.

# Goal:

The goal of this golf is to write a program as short as possible that generates a **PNG** file which, after converting to bitmap shares the same resolution and pixel color values as the following image (alternate link, SHA256: ab18085a27c560ff03d479c3f32b289fb0a8d8ebb58c3f7081c0b9e1895213b6):

# Rules:

1. The program must work offline, i.e. when the language runtime/interpreter is installed, no internet connectivity is installed to build/run the program,
2. The program may not rely on any external libraries (only use standard library of your language, as opposed to adding libraries from pip/npm/cargo/maven/whatever repositories),
3. The program must complete its operation within 60 seconds on a regular desktop computer (i.e. no brute-forcing the results).

# Answer
> 6 votes
## C#, ~~849~~ ~~793~~ 771 bytes

```
using System;using System.Drawing;using System.IO;class P{static void Main(){dynamic x,y,i=new Bitmap(Bitmap.FromStream(new MemoryStream(Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAGAAAAA2BAMAAADKYYHhAAAAGFBMVEUAAABdAgSMAwb///+jBAfFgYLRgYOugIE5HrT9AAAA20lEQVR4AWKgHIwCQThAFmVECAsA2qsDk4qBGIzjD7qAn5ngvlvAJJ3AdyscTqAr3PqaQwMgVYATKvQPlED5kQaAng2QBVnoCywBVeFQqKu6im83gcP1GFgVqEMVqiIP25MIzRjlmgSPZNufK/Qj1wC+bSKk2w/gHkDUaFZrEXht+85jcDc6FAHcqgsqvX3fkCxfcFZiaK3xL8EckS0ArfVO8u31C4y+FAQBBgbLAOYE9v8HxgDAgiiPXgk6gPykz8ctOzPIgHl0f8mjB1aDGQuyxeDgx3KB37t6B3NXgUgfIi7ZAAAAAElFTkSuQmCC"),0,312))),d=new Bitmap(1920,1080),g=Graphics.FromImage(d);for(y=0;y<54;y++)for(x=0;x<96;x++)g.FillRectangle(new SolidBrush(i.GetPixel(x,y)),new Rectangle(x*20,y*20,20,20));d.Save("s.png");}}

```

Tested with the following code:

```
class P
{
    static void Main()
    {
        Bitmap a = new Bitmap(@"c:\projects\confidence_2019_golf.png");
        Bitmap b = new Bitmap(@"c:\projects\s.png");

        Console.WriteLine(a.Width + ", " + b.Width);
        Console.WriteLine(a.Height + ", " + b.Height);

        for (int y=0; y<a.Height; y++)
        {
            for (int x=0; x<a.Width; x++)
            {
                Color ca = a.GetPixel(x, y);
                Color cb = b.GetPixel(x, y);

                if (ca.R != cb.R || ca.G != cb.G || ca.B != cb.B)
                {
                    Console.WriteLine(x + ", " + y);
                    Console.WriteLine(ca.R + ", " + ca.G + ", " + ca.B);
                    Console.WriteLine(cb.R + ", " + cb.G + ", " + cb.B);
                }
            }
        }
    }
}

```

Ungolfed:

```
using System;
using System.Drawing;
using System.IO;
class P
{
    static void Main()
    {
        dynamic x = 0;
        dynamic y = 0;
        dynamic b = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAGAAAAA2BAMAAADKYYHhAAAAGFBMVEUAAABdAgSMAwb///+jBAfFgYLRgYOugIE5HrT9AAAA20lEQVR4AWKgHIwCQThAFmVECAsA2qsDk4qBGIzjD7qAn5ngvlvAJJ3AdyscTqAr3PqaQwMgVYATKvQPlED5kQaAng2QBVnoCywBVeFQqKu6im83gcP1GFgVqEMVqiIP25MIzRjlmgSPZNufK/Qj1wC+bSKk2w/gHkDUaFZrEXht+85jcDc6FAHcqgsqvX3fkCxfcFZiaK3xL8EckS0ArfVO8u31C4y+FAQBBgbLAOYE9v8HxgDAgiiPXgk6gPykz8ctOzPIgHl0f8mjB1aDGQuyxeDgx3KB37t6B3NXgUgfIi7ZAAAAAElFTkSuQmCC");
        dynamic i = new Bitmap(Bitmap.FromStream(new MemoryStream(b, 0, 312)));
        dynamic d = new Bitmap(1920, 1080);
        dynamic g = Graphics.FromImage(d);
        for (y = 0; y < 54; y++)
        {
            for (x = 0; x < 96; x++)
            {
                g.FillRectangle(new SolidBrush(i.GetPixel(x, y)), new Rectangle(x * 20, y * 20, 20, 20));
            }
        }
        d.Save(@"c:\projects\s.png");
    }
}

```

# Answer
> 4 votes
## HTML + Javascript, ~~607~~ ~~591~~ 527 bytes

Thank you Epicness and Someone.

HTML, 436 bytes

```
<img id=a src=data:;base64,UklGRgABAABXRUJQVlA4TPMAAAAvX0ANALXIcSTJkST68N2Xs2p6ZJgUYgEpOVBwcYtMwGKJpBDAL5EUqioEEAAFTf8n4Akeel/aoYdx8E3jdbec+Bj0CQIKAqIiKqjd3hEU1L/CRATRBWhApHdtTIzZysYT0r794RjJEja6QbvdpUT9W1xDMYkxMQYEjWM4HPkrhiZRGjZoojYx0THU87bTZpWN2U6bJGMxF1qbRQ69BMYY48POObP4kX5/5753WXNeKm2SAFRBVRKqWK2CKkjmvG1VVbHY7K+aM7lk5mS1qqlaq2raKuh/9u1jI0BVVQNzzmJ3VRVcNluTcPxlBPR/7f3rMRIA><a id=b download>SAVE<canvas id=c width=1920 height=1080

```

Javascript, 91 bytes

```
b.href=c.toDataURL((d=c.getContext`2d`).drawImage(a,d.imageSmoothingEnabled=0,0,1920,1080))

```

JSFiddle

# Answer
> 3 votes
# C# (Visual C# Interactive Compiler), 707 bytes

```
#r"System.Drawing"
using System.Drawing.Drawing2D;dynamic a=new Bitmap(new MemoryStream(Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAGAAAAA2BAMAAADKYYHhAAAAGFBMVEUAAABdAgSMAwb///+jBAfFgYLRgYOugIE5HrT9AAAA20lEQVR4AWKgHIwCQThAFmVECAsA2qsDk4qBGIzjD7qAn5ngvlvAJJ3AdyscTqAr3PqaQwMgVYATKvQPlED5kQaAng2QBVnoCywBVeFQqKu6im83gcP1GFgVqEMVqiIP25MIzRjlmgSPZNufK/Qj1wC+bSKk2w/gHkDUaFZrEXht+85jcDc6FAHcqgsqvX3fkCxfcFZiaK3xL8EckS0ArfVO8u31C4y+FAQBBgbLAOYE9v8HxgDAgiiPXgk6gPykz8ctOzPIgHl0f8mjB1aDGQuyxeDgx3KB37t6B3NXgUgfIi7ZAAAAAElFTkSuQmCC"))),b=new Bitmap(1920, 1080),c=Graphics.FromImage(b);c.InterpolationMode=(InterpolationMode)5;c.PixelOffsetMode=(PixelOffsetMode)4;c.DrawImage(a,0,0,1920,1080);b.Save("b.png");

```

Only compiles in the interactive window, saves the result in a file called `b.png`

# Answer
> 2 votes
# C (GCC/MinGW), ~~1439~~ ~~1406~~ ~~1386~~ ~~1382~~ ~~1092~~ ~~807~~ ~~806~~ ~~800~~ ~~789~~ ~~787~~ ~~786~~ 777 bytes

-33 -4 -11 -9 bytes thanks to ceilingcat

-6 bytes thanks to someone's idea

Edit: Why even dynamically calculate CRCs when the output is static? Dropping that part really slimmed things down.

Somewhat beefier than other entries, but such is C life.

Assumes `sizeof(unsigned int) == 4`, i.e. 32-bit integers, and little-endianness.

The earlier RLE scheme is replaced by a slightly more complex one. Most of the image (except the "CONFIDENCE" text) is stored as a series of rectangles. Each rectangle is stored as four characters holding (x1, y1) and (x2 + 1, y2 + 1). We start with the lowest colour in the palette and upon hitting a space character in the image data, we increase the palette index.

I have a feeling further compression could be had by storing colours slightly differently and exploiting the additive nature of the colours of overlapping areas.

The "CONFIDENCE" text is stored as a series of characters holding 6 significant bits, each one of which corresponds to a "pixel" in the text.

```
#define Y*Q++-31
*o,C,x,i,W=5760,H=1080,Z[]={262749,394124,459939,8487086,8552901,8618449,~0};S(b,D,C,B,A,c)char*b;{for(B*=20;B<D*20;B++)for(x=A*20;x<C*20;)bcopy(Z+c,b+B*W+x++*3,3);}(*X)()=fwrite;main(j){char*p=calloc(W,H),d[]="\0\x81\26~\xe9",*Q="&&<57)V;22?E;9LOI3eI[%o7_1yA 7)<;2275;2?EC9I;I3V;I;LI[3_7_1o7_7eA 72<5;9?;_3e7 C;E?G;I?M;O?W;Y?[;]?GAIEMAOEWAYEaAcE??CA?ECG]EaG]9_;]?_ALEMG ?9C;L9M;_9a;_?aAa;c?=A?EIELG I9L;";for(;*Q;)S(p,Y,Y,Y,Y,C+=*Q<33&&Y);for(X("\x89PNG\r\n\32\n\0\0\0\rIHDR\0\0\a\x80\0\0\48\b\2\0\0\0g\xb1V\24\0_\5VIDAT\b\35",1,43,o=fopen("a.png","wb"));i<240;i++)"FStuybLGitTTJfRAaTuUzjBGiTVTJrRAFSTtybLG"[i/6]-64>>i%6&1&&S(p,C+1,j+1,C=17+i/48,j=26+i/6%8*6+i%6,6);for(;H--;p+=X(p,1,W,o))*d=!H,X(d,1,6,o);X("*vC\6\xc7\xe3\20W\0\0\0\0IEND\256B`\x82",1,20,o);}

```

# Answer
> 1 votes
## HTML + javascript, 504 bytes - Not competing

I still need to get the colors sorted out.

HTML, 35 bytes

```
<canvas id=g width=1920 height=1080

```

Javascript, 469 bytes

```
d=g.getContext`2d`
d[f='fillRect'](0,0,1920,1080)
d[a='globalAlpha']=.4
d[l='fillStyle']=`#a00`
'//>7|@2G:|;;5;|DB9>|R<D>|d.<:|h:B8'.split`|`.map(x=>x.split``.map(c=>(c[w='charCodeAt']()-40)*20)).map(x=>d[f](...x))
d[l]='#fff'
d[a]=1
q=(h,x,y,p,z)=>{b=atob(h).split``;for(var n in b){for(j=8;j--;)b[n][w]()&1<<j&&d[f](x+(n%p*8+j)*z,y+((n/p)|0)*z,z,z);}}
q('xkTXucgcKU1RiikFIVVXuiocKWVRiiwFxkTRucgc',520,340,6,20)
d[a]=.4
q('xgADKKEEKKEEBgADISEEISEExgAD',600,520,3,40)

```

JSFiddle

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