title: Simulate a Cisco Ping

text:
# Question
Title: Simulate a Cisco Ping
# Premise:

For those in networking, you've most likely sent a ping to or from some device to make sure everything's properly connected. Cisco, a popular company in networking\[citation needed\], has a command for it in their IOS that looks like this:

(Image source)

Your challenge is to graphically recreate a portion of this. The portions we are skipping are the first line (`Type escape sequence to abort.`) entirely, along with the IP address and round-trip times.

You will start by outputting the following:

```
Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:

```

You will then simulate the echo requests going out. Each request will start by waiting 2 seconds and then generating the response. A successful echo response is represented by a `!`, a failed one by `.`. We won't actually be sending packets but to represent packet loss, your program must randomly choose between the two options with a non-zero chance for each. This line will start empty and each tick will add another character.

After the fifth echo, the percentage line will be outputted and the program should then terminate. The percentage line will be in the format of

```
Success rate is $p percent ($s/5)

```

where `$p` is in regex `0|20|40|60|80|100` and `$s` is the number of successful echos. The screen must be updated after each wait period by either redrawing the new state or appending to the existing echo line. This includes the `Sending` line.

**Example run:** (The tick count should not be displayed and is there to clarify what the output should look like at each time step)

```
#Tick 0
Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:

#Tick 1
Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:
.

#Tick 2
Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:
.!

#Tick 3
Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:
.!.

#Tick 4
Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:
.!.!

#Tick 5
Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:
.!.!.
Success rate is 40 percent (2/5)

```

# Input:

No usable input provided.

# Output:

Any reasonable format. An example final output looks like this:

```
Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:
...!!
Success rate is 40 percent (2/5)

```

# Rules:

* You must either append to the echo line or redraw the screen after each tick.
* `!` and `.` do not have to be equally likely, just both possible.
* Successive runs must be able to generate different results
* Gifs or webms of your output would be cool. No bonus or anything for it though.
* Standard Loopholes forbidden
* This is

# Answer
> 5 votes
# C (gcc), 172 bytes

So, I shaved off a whopping 6 bytes off of this thing with some quite ridiculous trickery. Compile with `-DK=!sleep(2)-putchar(rand()%2?33:46)/46`. Depends on the `sleep()` function being defined in the system standard libraries. Does not loop or recurse.

```
p(n){puts("Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:");printf("\nSuccess rate is %i percent (%i/5)",n*20,n=K+K+K+K+K);}

```

Try it online!

## Explanation

This solution depends on three critical implementation/runtime details. First, the `sleep()` *must not be interrupted*, via e.g. a signal. Second, the additions and subtractions being resolved in order from left-to-right. Third, the arguments to `printf()` must be resolved right-to-left.

With that out of the way, let's sort through this thing.

```
p(n){ // Unfortunately, I need a variable to store the RNG result.
    // This is straight-forward printing of a line.
    puts("Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:");
    // So, resolving right-to-left, we have a) the K preprocessor macros,
    // b) the assigment of their sum to n, c) the percentage equivalent of
    // the fraction n/5 and d) a constant format string.
    // The summation of the K's is where the magic happens.
    printf("\nSuccess rate is %i percent (%i/5)",n*20,n=K+K+K+K+K);
}

```

The compiler argument

```
-DK=!sleep(2)-putchar(rand()%2?33:46)/46

```

So, starting from the left (i.e. like it should resolve), we have `sleep()`. `sleep()` returns the number of seconds left when it returns, so we expect the user (and other processes) to be kind and to not interrupt our sleep. We take the logical complement, and because in our case `sleep()` will always return `0`, the result is `1`. More on the significance later.

Next, we enter `putchar()`. `putchar()` prints a single 1-byte character, and returns the value of the byte. So, we get a random value inside, compute modulo-2 for a nice 50-50 split (albeit with horrible entropy), and then ternary-conditional it into our desired characters - `! (33)` and `. (46)`. Then we divide the return value of `putchar()` with `46`.

Now, that division will return `0` for `!` and `1` for `.` \- so we take 1 (from `!sleep()`) and subtract the result of the division from that. Presto!

Okay, there's a slight problem. When you write things to a buffer in C (i.e. `stdout`), it doesn't *necessarily* write to the receiving end immediately. In fact, when I was running this on my distro of choice, I discovered that it would only print the pings *after* the program terminated. However, given that *all the other* solutions in C are letting that slide, and that there probably exists at least *one* machine out there somewhere does *that* and fulfills all the other prerequisites (and one could always just "fix" that in the kernel...), I'm not going to mess with my score by `fflush()`ing `stdout`.

# Answer
> 4 votes
# APL (Dyalog Unicode), ~~147~~ 138 bytes

```
{5=≢⍵⊣⎕DL≢⎕←↑⌽'.!'[⍵]'Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:':⎕←('Success rate is',×∘20,'percent (','/5)',⍨⍕)+/⍵}¨1↓¨,\?6⍴2

```

Try it online!

This is a big Direct function. As with other answers, the TIO link will only output after the execution is completed. That said, @Adám has created a handy helper function so the timestamps can be visualized. That version of the code can be found here.

This answer uses `⎕IO←0`, which sets the **I**ndex **O**rigin of everything from 1 to 0.

Thanks to @ngn for the 9 bytes saved (and for ruining my explanation! Now I have to do it again `(ლಠ益ಠ)ლ`)

### How:

The function receives 1 fixed argument, which is  on the right.

As , we have `¨1↓¨,\?6⍴2`. This expression randomly chooses (`?`) between 0 and 1 6 times (`6⍴2` creates a 6 element vector of 2's). The results are concatenated (`,\`) to form a 6 element vector of 1 to 6 element vectors (e.g.: `1 0 1 0 1 1 0 1 1 0 0 1 1 0 1 0 1 1 0 1 0`). The first element of each is dropped (`1↓¨`), and then each resulting vector is passed as  (`¨`), running the function 6 times.

`{5=≢⍵⊣...:...}` is a conditional statement. If  has 5 elements (aka if it's the last iteration), it'll execute the code after the guard (`:`). The  assures the condition will be the last thing evaluated, so the program will always print the string before the guard.

`{...⎕DL≢⎕←↑⌽'.!'[⍵]'Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:'...}` creates a two-element vector formed by the indexed vector `'.!'[⍵]`, which will output the successes and failures, and the ping string itself. That vector is then reversed (monadic ) to the correct order, then mixed (monadic ) into a matrix. That matrix is then output to stdout (`⎕←`), and a **D**e**L**ay (`⎕DL`) is added. The argument to `⎕DL` is the number of elements in the matrix (), namely 2, creating a 2 second delay between function calls.

`{...:⎕←('Success rate is',×∘20,'percent (','/5)',⍨⍕)+/⍵}` creates the last string to be output. It'll sum the elements of the argument (`+/⍵`) and pass the result as argument to the tacit function inside the parenthesis. That function first prepends (dyadic `,`, followed by ) the stringified () argument with the string `'/5)'`, then appends that to the string `'percent ('`. Next, it'll append the resulting string to 20 times the argument (`×∘20`), and then append it to the rest of the output, which is sent to stdout via `⎕←`.

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

```
int i,p;for(Write("Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:\n");i++<5;Write(".!"[-p+(p+=new Random().Next(2))]))System.Threading.Thread.Sleep(2000);Write($"\nSuccess Rate is {p*20} percent ({p}/5)");

```

Try it online!

# Answer
> 3 votes
# Java (JDK), 227 bytes

```
()->{var o=System.out;int s=0,i=0;for(o.println("Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:");i++<5;Thread.sleep(2000))o.print(Math.random()>.5&&s++<9?"!":".");o.printf("\nSuccess rate is %d percent (%d/5)",s*20,s);}

```

Try it online!

---

**The ping in action**

---

**Explained**

```
()->{                               // Lambda taking no input
    var o=System.out;               // Assign System.out to a variable
    int s=0,i=0;                    // Initialise successes and loop ints
    for(o.println("Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:");
                                    // ^Print opening line
        i++<5;                      // Loop five times
        Thread.sleep(2000))         // Sleep for 2 seconds at the end of each loop
            o.print(                // Print out..
                Math.random()>.5    // ..if random number is greater than .5 (50%)
                    &&s++<9?        // ..and incremented successes
                        "!":".");   // ! for success and . for failure
    o.printf("\nSuccess rate is %d percent (%d/5)",s*20,s);
                                    //^Print formatted closing line
}

```

# Answer
> 2 votes
# PowerShell, ~~166~~ ~~162~~ 158 bytes

```
'Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:'
0..4|%{sleep 2;write-host -no '.!'[($x=0,1|Random)];$d+=$x}
"
Success rate is $($d*20) percent ($d/5)"

```

Try it online!

Really similar to the Python answer to TFeld. Timing doesn't work on TIO (TIO only outputs at program completion), but works locally.

The first line is just a string placed on the pipeline. The middle line loops from `0` to `4`, each iteration `sleep`ing for `2` seconds, then `write-host` with `-no`newline. We're writing out either a `!` or `.` chosen `Random`ly and stored into `$x`. We then increment `$d` based on `$x`.

The last line is another (multiline) string placed on the pipeline, with a little bit of calculation in the middle to come up with the percentage.

*-1 byte thanks to Veskah
-3 bytes thanks to Ciaran\_McCarthy*

# Answer
> 2 votes
# JavaScript + HTML, 203 + 9 = 212 bytes

```
<pre id=o

```

```
f=(x,y=0,g=z=>setTimeout(f,2e3,-~x,y+z),u=s=>o.innerText+=s)=>x?x<6?u(`.!`[n=new Date%2],g(n)):u(`
Success rate is ${y/20} percent (${y}/5)`):u`Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:`&g(0)

```

Try it

If `new Date` isn't random enough then add 8 bytes to use `Math.random()` instead (some other modifications have been made to allow it to run properly in a Snippet):

```
f=(x,y=0,g=z=>setTimeout(f,2e3,-~x,y+z),u=s=>o.innerText+=s)=>x?x<6?u(`.!`[n=Math.random()+.5|0],g(n)):u(`
Success rate is ${y/20} percent (${y}/5)`):u`Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:
`&g(0)
f()
```

```
<pre id=o></pre>
```

# Answer
> 1 votes
# Python 3, ~~221~~ ~~220~~ ~~216~~ ~~209~~ ~~208~~ 201 bytes

```
import time,random
p=print
p('Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:')
n=0
exec("time.sleep(2);i=random.choice('.!');n+=i<'#';p(end=i);"*5)
p(f'\nSuccess rate is {n*20} percent ({n}/5)')

```

Try it online!

Timing doesn't work in TIO, but works in console. (TIO outputs at the end of execution)

-7 bytes, thanks to Erik the Outgolfer

# Answer
> 1 votes
## JavaScript, 322 268 267 265 bytes

```
(f=(a,t,s)=>a--?new Promise(r=>setTimeout(r,2e3,s+='!.'[~~(Math.random()<.5)],t(`Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:`))).then(_=>t(s)||f(a,t,s)):t(`Success rate is ${s=s.match(/!/g),s=s?s.length*2:''}0 percent (${s/2}/5)`))(5,_=>console.log(_),'')
```

Try it online!

## JavaScript + HTML, 299 bytes

To meet output formatting requirement

```
(f=(a,t,s)=>a--?new Promise(r=>setTimeout(r,2e3,s+='!.'[~~(Math.random()<.5)])).then(_=>t(...s)&&f(a,t,s)):t(`\nSuccess rate is ${s=s.match(/!/g),s=s?s.length*2:''}0 percent (${s/2}/5)`))(5,t=(..._)=>p.innerHTML+=_.pop(),'',t(`Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:\n`))
```

```
<pre id=p></pre>
```

# Answer
> 1 votes
# Perl 6, 154 bytes

```
say "Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:";say
sum(map {sleep 2;.print;?/\!/},roll
5,<. !>).&{"\nSuccess rate is {$_*20} percent ($_/5)"}

```

Try it online!

# Answer
> 1 votes
# Clean, 305 bytes

```
import StdEnv,Math.Random
s::!Int->Int
s _=code {
ccall sleep "I:I"
}
t::!Int->Int
t _=code {
ccall time "I:I"
}
Start#l=take 5(map((bitand)1)(genRandInt(t 0)))
=("Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:\n",[if(e>0)'!''.'\\e<-l|s 2==0],"\nSuccess rate is ",20*sum l," percent (",sum l,"/5)")

```

Try it online!

# Answer
> 1 votes
# PHP, 161 bytes

```
<?="Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:
";for(;$x++<5;print$y?'!':'.')$z+=$y=rand()%2+sleep(2);echo"
Success rate is ",$z*20," percent ($z/5)";

```

Try it online!

`$ php fakeping.php`

```
Sending 5, 100-byte ICMP Echos, timeout is 2 seconds:
.!.!.
Success rate is 40 percent (2/5)

```

# Answer
> 1 votes
# C (gcc), ~~176~~ 174 bytes

```
f(i,j){for(puts("Sending 5, 100-byte ICMP Echos, timeout is 2 seconds"),j=i=5;sleep(2),i--;putchar(rand()%2?j--,33:46));printf("\nSuccess rate is %d percent (%d/5)",j*20,j);}

```

Try it online!

Saved 2 bytes thanks to Rogem

Ungolfed:

```
f(i,j) {
    for (puts("Sending 5, 100-byte ICMP Echos, timeout is 2 seconds"),
            j = i = 5; sleep(0), i--;
            putchar(rand() % 2 ? j--, 33 : 46));
    printf("\nSuccess rate is %d percent (%d/5)",j * 20, j);
}

```

# Answer
> 1 votes
# 05AB1E, 83 bytes

```
т’Sïà 5, ÿ-ÄÁ ICMP ®Ès, €º€Ä is 2 šÀ:’,„.!5ãΩDv.Z.Zy?}õ,'.¢xT*“íÞ„¼€ˆ ÿ‰» (ÿ/5)“.ª?

```

Try it online!

# Answer
> 1 votes
# Befunge-98 (PyFunge), 164 bytes

```
#va":sdnoces 2 si tuoemit ,sohcE PMCI etyb-001 ,5 gnidneS5"k,>0"2 peels"=k
>?1'!>,+\1+:4`!jv\'^'=1p
;>0'.^;")5/",,,@>$" si etar sseccuS"afk,,:2a**.'0+"( tnecrep"9k,

```

Try it online!

Unfortunately, I could only test it on TIO, where it returns everything after ten seconds, but it should work as expected.

---
Tags: code-golf, kolmogorov-complexity, random, animation
---


title: Vampire Compatibility

text:
# Question
Title: Vampire Compatibility
A little known fact about vampires is that they must drink the blood of victim that has a compatible donor blood type. The compatibility matrix for vampires is the same as the regular red blood cell donor/recipient matrix. This can be summarized by the following American Red Cross table

```
Type    You Can Give Blood To    You Can Receive Blood From
A+      A+, AB+                  A+, A-, O+, O-
O+      O+, A+, B+,AB+           O+, O-
B+      B+, AB+                  B+, B-, O+, O-
AB+     AB+                      everyone
A-      A+, A-, AB+, AB-         A-, O-
O-      everyone                 O-
B-      B+, B-, AB+, AB-         B-  O-
AB-     AB+, AB-                 AB-, A-, B-, O-

```

### Challenge

Write a function or program that takes a blood type as input and outputs two lists:

1. the unordered list of types that may receive donation of the input type
2. the unordered list of types that may give donation to the input type

If you write a function, then please also provide a test program to call that function with a few examples, so I can easily test it. In this case, the test program would not count towards your score.

### Input

Input must be a string representing exactly one of the 8 possible red blood cell types `O−` `O+` `A−` `A+` `B−` `B+` `AB−` `AB+`. Input may be given via the normal methods (STDIN, command-line args, function args, etc).

If any other input is given then the program/function must return empty output or throw an error. Normally strict input-checking is not great in questions, but I felt given the life-death implications of getting blood types wrong that I should add this rule.

### Output

Output will be two human-readable lists of blood types in whatever format is suitable for your language. In the special cases where one of the output list contains all 8 types, this list may optionally be replaced with a single item list containing `everyone`.

Normal output will go to one of the normal places (STDOUT, function return, etc).

### Other rules

* Standard loopholes are banned
* You may use whatever pre-existing 3rd party libraries you need, so long as they are not designed explicitly for this purpose.

### Examples

* For input `AB-`, the two output lists would be: `{AB+, AB-}, {AB-, A-, B-, O-}`
* For input `AB+`, the two output lists would be: `{AB+}, {O−, O+, A−, A+, B−, B+, AB−, AB+}` or `{AB+}, {everyone}`

---

Personal note: Please consider donating blood if you are able to. Without the transfusion I received a few years ago, I might not be here today, so I feel very grateful towards those who are able to donate!

# Answer
# Clip, 69

```
*cTx\{fFx`Tf[tFtx}T`[Fx[y!VVx"O-"Vy"O-"}[TC"A+ B+ AB+ O+ A- B- AB- O-

```

Input: `AB-`

Output: `{{"AB+", "AB-"}, {"A-", "B-", "AB-", "O-"}}`

## Explanation

A blood type `x` can give to `y` if all of `x`'s antigens are included in `y`. The program defines the function `F` as whether `x` can give to `y`, and `T` as the list of types.

```
*cTx                 .- If T contains x (the input)         -.
    \                .- Print                               -.
     {             ` .- a list of                           -.
      fFx`T          .- filter each t in T with F(x,t)      -.
           f[tFtx}T  .- filter each t in T with F(t,x)      -.

[Fx[y              } .- F is a function of x and y          -.
     !V              .- all letters of ... are included in ...   -.
       Vx"O-"        .- x, with O and - removed             -.
             Vy"O-"  .- y, with O and - removed             -.

[TC"A+ B+ AB+ O+ A- B- AB- O-   .- T is the list of types -.

```
> 9 votes

# Answer
# Java 8, 373

```
import java.util.*;void f(String s){List<String>l=new ArrayList(Arrays.asList("A+,B+,AB+,O+,A-,B-,AB-,O-".split(","))),m=new ArrayList(l);int i=l.contains(s)?1:0/0;l.removeIf(x->g(s,x)<1);m.removeIf(x->g(x,s)<1);System.out.print(l+","+m);}int g(String s,String t){for(char c:s.replaceAll("O|-","").toCharArray())if(!t.replaceAll("O|-","").contains(""+c))return 0;return 1;}

```

## Explanation

```
void f(String s) {
    List<String> l = new ArrayList(Arrays.asList("A+,B+,AB+,O+,A-,B-,AB-,O-".split(","))),
                 m = new ArrayList(l);
    int i = l.contains(s) ? 1 : 0 / 0;
    l.removeIf(x -> g(s, x) < 1);
    m.removeIf(x -> g(x, s) < 1);
    System.out.print(l + "," + m);
}

int g(String s, String t) {
    for (char c : s.replaceAll("O|-", "").toCharArray()) {
        if (!t.replaceAll("O|-", "").contains("" + c)) {
            return 0;
        }
    }
    return 1;
}

```

Run it here: http://repl.it/e98/1

Note that `static` had to be added to each method to call them from the main method.
> 6 votes

# Answer
# Pyth, 61 59 50

```
L-{b"O-"M!-yGyHJmsd*c"A O B AB"d"+-"I}zJfgzTJfgYzJ

```

Run it here.

Explanation:

```
L-{b"O-"                         Create function y(b) that makes a set from b's
                                 characters minus O and -.
M!-yGyH                          Create function g(G,H) that checks if y(G) is
                                 a subset of y(H).
J                                Assign to J...
 msd                             The concatenation of every element in...
    *c"A O B AB"d"+-"            The Cartesian product of A O B AB and + -.
I}zJ                             If input in J then...
    fgzTJ                        Print all elements e in J if g(input, e).
    fgYzJ                        Print all elements e in J if g(e, input).

```
> 5 votes

# Answer
# Prolog, ~~119~~ 110 bytes

```
u(A,B):-member(A:B,[a:ab,b:ab,o:a,o:b,o:ab]);A=B,member(A,[a,ab,b,o]).
g(X,Y):-(X= -A;X=A),(Y= -B;Y=B),u(A,B).

```

*Remarks*:

1. Blood types have the following properties: everytime you have a `-` (e.g. `a-`), you can give to the same people as the one who have positive equivalent of your group (e.g. `a`), as well as their negative counterpart (e.g. `a` gives to `ab`, so `a-` gives to `ab` and `ab-`). Based on this property, and *abusing the notations a little bit* to make use of the minus and plus operators, we can factor a lot of cases. *Please tell me if you find it acceptable*. If you prefer having the original (postfix) syntax, here is a non-golfed version:

```
blood(X):-member(R,['a+','o+','b+','ab+','a-','b-','ab-']).
give('o-',R):-blood(R).
give(X,X):-blood(X).
give('a+','ab+').
give('b+','ab+').
give('o+','a+').
give('o+','b+').
give('o+','ab+').
give('a-','a+').
give('a-','ab+').
give('a-','ab-').
give('b-','b+').
give('b-','ab+').
give('b-','ab-').
give('ab-','ab+').

```
2. This is Prolog, so the interactive environment allows to query everything as requested (see example below). Granted, we don't have lists strictly as an output, but this is equivalent. We also naturally handle error cases as a consequence.

## Example

```
donors(X,L) :- findall(Y,g(Y,X),L).
receivers(X,L) :- findall(Y,g(X,Y),L).

test :-
    member(X,[a,o,b,ab,-a,-o,-b,-ab]),
    donors(X,D),
    receivers(X,R),
    writeln(X:give_to(R):receive_from(D)),
    fail.
test.

```

Then, we execute `test`:

```
a : give_to([ab, a]) : receive_from([o, a])
o : give_to([a, b, ab, o]) : receive_from([o])
b : give_to([ab, b]) : receive_from([o, b])
ab : give_to([ab]) : receive_from([a, b, o, ab])
-(a) : give_to([+(ab), +(a), -(ab), -(a)]) : receive_from([-(o), -(a)])
-(o) : give_to([+(a), +(b), +(ab), +(o), -(a), -(b), -(ab), -(o)]) : receive_from([-(o)])
-(b) : give_to([+(ab), +(b), -(ab), -(b)]) : receive_from([-(o), -(b)])
-(ab) : give_to([+(ab), -(ab)]) : receive_from([-(a), -(b), -(o), -(ab)])

```

... which, without proper formatting, is the same matrix as the one given in the question.

## Details

The predicate `g/2` is the *give* relationship: `g(X,Y)` means *people of blood type X may give blood to people of blood type Y*.

Find receivers for group `a`:

```
[eclipse]: g(a,R).

R = ab
Yes (0.00s cpu, solution 1, maybe more) ? ;

R = a
Yes (0.00s cpu, solution 2)

```

Find receivers for `orange_juice` (should fail):

```
[eclipse] g(orange_juice,L).

No (0.00s cpu)

```

Find donors for `O-`:

```
[eclipse] g(X,-o).

X = -(o)
Yes (0.00s cpu)

```

Who can give what? :

```
[eclipse] g(X,Y).

.... 27 answers ....

```

We do not go into an infinite recursion loop (it was the case in preliminary tests).
> 4 votes

# Answer
# CJam, 64 bytes

```
"AB"_a+'O+"+-"m*:s:TT{}+Tqa#=a+T4=f&_)f{\-!}\)f-:!]{T]z::*La-p}/

```

The `m*:s` part comes from Martin's CJam answer. (I didn't read the other parts yet.)

There will be still some serious problems because they'll be never sure about the order of the two lists. And `Block ArrayList &` might be implemented in later versions of CJam.

### Explanation

```
"AB"_a+'O+         " Generate ['A 'B \"AB\" 'O]. ";
"+-"m*:s:T         " Generate the list of blood types and store in T. ";
T{}+
    Tqa#           " Find the input in T. ";
=                  " Find the blood type by the index.
                     If not found, return a block to cause an error. ";
a+                 " Append the verified input to T. ";
T4=                " AB+. ";
f&                 " Intersect each blood type with AB+. ";
_)f{\-!}           " Check emptiness of input - each item. ";
\)f-:!             " Check emptiness of each item - input. ";
]{                 " For both lists: ";
    T]z::*         " Replace items in T where there is a 0 with empty strings. ";
    La-            " Remove empty strings. ";
    p              " Print. ";
}/

```
> 4 votes

# Answer
# Javascript, 167

```
p=function(t){o="";if((x=(l="O- O+ B- B+ A- A+ AB- AB+".split(" ")).indexOf(t))<0)return;n=2;while(n--){y=8;while(y--)if([y,x][n]-(y&x)==0)o+=" "+l[y];o+=";"}return o}

```

ungolfed:

```
function p(btype){
    output = "";
    btypeList = "O- O+ B- B+ A- A+ AB- AB+".split(" ");

    btypeInt = btypeList.indexOf(btype);
    // thus we have the scheme
    // btypeInt = 0b(has A antigen)(has B antigen)(has rhesus antigen)

    if(btypeInt < 0) // i.e. broken blood type string
        return;

    for(receiving = 7; receiving >= 0; receiving--)
        if(giving - (receiving & btypeInt) == 0)
            // i.e. the receiving person has at least all the antigens of our donor
            output += " " + btypeList[receiving];

    output += ";";

    for(giving = 7; giving >= 0; giving--)
        if(btypeInt - (receiving & btypeInt) == 0)
            // i.e. the giving person has no antigens that our patient doesn't have
            output += " " + btypeList[receiving];

    return output;
}

```

testing function:

```
function tester(){
    btypeList = "O- O+ B- B+ A- A+ AB- AB+".split(" ");
    for(i=0; i<8; i++){
        console.log("Patient is " + btypeList[i])
        console.log(p(btypeList[i]))
    }
    console.log("Erroneous blood type => returns void:")
    console.log(p("asdf"))
}

```

Encoding the blood type in binary has the advantage that another antigen (e.g. the Kell antigen) is easily incorporated into the code by just adding another bit.

---

Donate blood in Zurich, CH: Blutspende Zürich
> 3 votes

# Answer
# CJam, 94 bytes

Wow, this is long... while I think I could probably golf this approach below 80, I think I might have done better by first computing the matrix and then simply picking out the correct row and column. Anyway, here it is:

```
'O'A'B"AB"]:A"+-"m*:sq_a@&!!*_)'++_&\"AB"&A{1$\-!},\;\m*::+p)'-+_&\"AB"&A1>{1$-!},'O+\;\m*::+p

```

Test it here.

I'll add an explanation when I'm done golfing.
> 2 votes

# Answer
# Groovy, 115

```
x={i=(l=('O-O+B-B+A-A+AB-AB+'=~/\w+./)[0..7]).indexOf(it);f=(0..7).&findAll;i<0?[]:[l[f{!(~it&i)}],l[f{!(it&~i)}]]}

```

The idea is to encode A, B and rhesus factor as one bit each. We can then inverse the bits to get all the antigens on the receiving side and use it to check that there is no corresponding antibodies on the giving side. This is more or less the same as the existing JavaScript solution.

Sample execution

```
groovy> println x("AB+")
groovy> println x("AB-")
groovy> println x("A+")
groovy> println x("A-")
groovy> println x("B+")
groovy> println x("B-")
groovy> println x("O+")
groovy> println x("O-")
groovy> println x("X")

[[AB+], [O-, O+, B-, B+, A-, A+, AB-, AB+]]
[[AB-, AB+], [O-, B-, A-, AB-]]
[[A+, AB+], [O-, O+, A-, A+]]
[[A-, A+, AB-, AB+], [O-, A-]]
[[B+, AB+], [O-, O+, B-, B+]]
[[B-, B+, AB-, AB+], [O-, B-]]
[[O+, B+, A+, AB+], [O-, O+]]
[[O-, O+, B-, B+, A-, A+, AB-, AB+], [O-]]
[]

```
> 2 votes

# Answer
# Ruby, 237 232 223 221 210 207 bytes

Fixed some extraneous backslashes in the regular expressions and made it so it just prints out the lists as opposed to storing them to variables and then printing them. Sometimes you miss the obvious things when trying to golf!

```
o=->b{Regexp.new b.gsub(?O,?.).gsub(?+,'.?\\\+').gsub'-','.?(\W)'};b=gets.chop;t=["A+","B+","AB+","O+","A-","B-","AB-","O-"];exit if !t.include? b;p t.reject{|x|!x.match o.(b)};p t.reject{|x|!b.match o.(x)}

```

Ungolfed:

```
#!/usr/bin/ruby
b=gets.chomp;
types = ["A+","A-","B+","B-","AB+","AB-","O+","O-"];
exit if !types.include?(b);
regex1 = Regexp.new b.gsub("O",".").gsub('+','.?\\\+').gsub('-','.?(\\\+|\\\-)')
donate = types.reject {|x|!x.match(regex1)};
p donate;
receive = types.reject {|x| regex2 = Regexp.new x.gsub("O",".").gsub('+','.?\\\+').gsub('-','.?(\\\+|\\\-)'); !b.match(regex2)};
p receive;

```

Basically, I construct a custom regular expression for the blood type entered to check if you can donate to another blood type. I then iterate through the blood types and apply that same regex to them and check if they can donate to the one specified.

This can probably be golfed down even more. This is my first time attempting code golf, heh.
> 1 votes

# Answer
## PHP - ~~215~~ ~~212~~ 206 bytes

```
function($t){$c=[9,15,12,8,153,255,204,136];if(($a=array_search($t,$l=split(1,'A+1O+1B+1AB+1A-1O-1B-1AB-')))===!1)die;foreach($l as$k=>$v){if($c[$a]&1<<$k)$x[]=$v;if($c[$k]&1<<$a)$y[]=$v;}var_dump($x,$y);}

```

Here is the ungolfed version:

```
function ($type)
{
    $typesList = ['A+', 'O+', 'B+', 'AB+', 'A-', 'O-', 'B-', 'AB-'];
    $donationCompatibilityList = [
        0b00001001,
        0b00001111,
        0b00001100,
        0b00001000,
        0b10011001,
        0b11111111,
        0b11001100,
        0b10001000,
    ];

    $idType = array_search($type, $typesList);
    if ($idType === false) {
        die;
    }

    $canGiveToList = [];
    $canReceiveFromList = [];
    foreach ($typesList as $currentIdType => $currentType)
    {
        if ($donationCompatibilityList[$idType] & 1 << $currentIdType ) {
            $canGiveToList[] = $currentType;
        }

        if ($donationCompatibilityList[$currentIdType ] & 1 << $idType) {
            $canReceiveFromList[] = $currentType;
        }
    }

    var_dump($canGiveToList, $canReceiveFromList);
}

```

Thanks to manatwork for saving 4 bytes.
> 1 votes

# Answer
# Python 2, 168 bytes

This is the same method as Blackhole's answer. Exits with an error if the parameter is not found in the list of types.

```
def f(t):l='A+ O+ B+ AB+ A- O- B- AB-'.split();c=[9,15,12,8,153,255,204,136];i=l.index(t);print[s for s in l if c[i]&1<<l.index(s)],[s for s in l if c[l.index(s)]&1<<i]

```

**Less golfed:**

```
def f(t):
    l = 'A+ O+ B+ AB+ A- O- B- AB-'.split()
    c = [9, 15, 12, 8, 153, 255, 204, 136]
    i = l.index(t)
    x = [s for s in l if c[i] & 1 << l.index(s)]
    y = [s for s in l if c[l.index(s)] & 1 << i]
    print x, y

```

Run it here: http://repl.it/eaB

I also tried a couple other slight changes, but couldn't get it any shorter...

```
#172 bytes
def f(t):l='A+ O+ B+ AB+ A- O- B- AB-'.split();c=[9,15,12,8,153,255,204,136];a=lambda x:l.index(x);i=a(t);print[s for s in l if c[i]&1<<a(s)],[s for s in l if c[a(s)]&1<<i]

#171 bytes
def f(t):l='A+ O+ B+ AB+ A- O- B- AB-'.split();c=[9,15,12,8,153,255,204,136];a=lambda x:l.index(x);print[s for s in l if c[a(t)]&1<<a(s)],[s for s in l if c[a(s)]&1<<a(t)]

```
> 1 votes

# Answer
# Python, 187 bytes

Different approach:

```
def D(a,b):X=lambda c:c in a and 1-(c in b);return(X('A')+X('B')+X('+'))<1
T="O- O+ A- A+ B- B+ AB- AB+".split()
X=lambda t:(0,([u for u in T if D(t,u)],[u for u in T if D(u,t)]))[t in T]

```

Can probably be golfed a bit more.

**Test:**

```
for t in T + ["zz"]:
    print t, X(t)

```

**Output:**

```
O- (['O-', 'O+', 'A-', 'A+', 'B-', 'B+', 'AB-', 'AB+'], ['O-'])
O+ (['O+', 'A+', 'B+', 'AB+'], ['O-', 'O+'])
A- (['A-', 'A+', 'AB-', 'AB+'], ['O-', 'A-'])
A+ (['A+', 'AB+'], ['O-', 'O+', 'A-', 'A+'])
B- (['B-', 'B+', 'AB-', 'AB+'], ['O-', 'B-'])
B+ (['B+', 'AB+'], ['O-', 'O+', 'B-', 'B+'])
AB- (['AB-', 'AB+'], ['O-', 'A-', 'B-', 'AB-'])
AB+ (['AB+'], ['O-', 'O+', 'A-', 'A+', 'B-', 'B+', 'AB-', 'AB+'])
zz 0

```
> 1 votes

# Answer
# PHP (287 bytes):

Yeah, this is pretty long, but it works as expected.

It may be possible to shorten a lot:

```
!preg_match('@^(AB?|B|O)[+-]$@',$t=$_GET[T])&&die("$t invalid");$S=array_flip($D=split(0,'O+0A+0B+0AB+0O-0A-0B-0AB-'));$L=[[1230,40],[13,1504],[23,2604],[3,$r=12345670],[$r,4],[1537,54],[2637,64],[37,7564]];for($j=0;$j<2;){foreach(str_split($L[$S[$t]][$j++])as$v)echo$D[$v].' ';echo'
';}

```

This is not easy to read and was't easy to write.

It works as intended, outputting the ones you can give to and the ones you can receive from on another line.

This requires a URL parameter `T=` with the type.
> 1 votes

# Answer
# CJam, 80 bytes

This is still too long. Probably I can shave off 4 to 5 bytes more.

```
U1023_XKC30D]2/La+"AB"a"OAB"1/+:Mr):P;a#=_P"+-":G&+!!{AfbMff=G1/Pf|]z{~m*:s}%}*`

```

For any invalid input, either prints an empty array, or throws an error.

Try it online here or run the whole test suite
> 1 votes

# Answer
# APL, 66

```
(↓⊃∧/(↓t∘.∊v)(≥,[.5]≤)¨t∊⊃v⌷⍨v⍳⊂⍞)/¨⊂v←,'+-'∘.,⍨('O'∘,,⊂)2↑t←'AB+'

```

Try it here.
> 1 votes

# Answer
# C, 224

```
#define d(x)for(i=0;i<8;i++)if((i x j)==j)printf("%s%s%s%c ",i&2?"A":"",i&4?"B":"",i&6?"":"0","-+"[i&1]);puts("");
main(i,j){char d[4],*c=&d;scanf("%s",c);j=(c[2]?c++,2:0)+(c[1]-'+'?0:1)+(*c>='A'?2:0)+(*c>'A'?2:0);d(&)d(|)}

```

De-golfed it shows:

```
/* j = 1*(has+) + 2*(hasA) + 4*(hasB) */
#define d(x) for(i=0;i<8;i++) \
                 if((i x j)==j) \
                      printf("%s%s%s%c ",i&2?"A":"",i&4?"B":"",i&6?"":"0","-+"[i&1]); \
             puts("");

main(i,j)
{
    char d[4], *c=&d;
    scanf("%s",c);

    j= (c[2]? (c++,2):0)            /* ABx */
            + (c[1]-'+'?0:1)
            + (c[0]>='A'?2:0)
            + (c[0]>'A'?2:0);

    // print possible receipients, and then donators
    d(&)
    d(|)
}

```
> 1 votes

# Answer
# Perl, 107 ~~112~~

Finally encoding the type names in numbers gave the shorter code.

```
#!perl -p
$x=y/AB+/421/r%9;@a=grep{~$x&$_%9||push@b,$_;!($x&~($_%9))}map{("$_-",$_.1)}0,2,4,42;$_="@a
@b";y/421/AB+/

```

Older version

```
#!perl -p
$x=y/AB+/421/r%9;@a=grep!($x&~$_),0..7;@b=grep!(~$x&$_),0..7;$_="@a
@b";s/\d/(map{("$_+","$_-")}0,A,B,AB)[$&]/eg

```
> 0 votes

# Answer
# Pyth, 58

Partly the same as orlp's solution, but somewhat different and completely self-designed.

```
M&n+eGeH"+-"!f!}T+H\OPGJsm,+d\++d\-c"O A B AB"dfgzYJfgZzJJ

```

## Explanation

```
M                          create a function g(G,H) that returns
  n+eGeH"+-"                 G[-1] + H[-1] is not "+-"
 &                          and
            !f!}T+H\OPG      chars of G[:-1] not in H + "O" is falsy (empty)
J                          J =
 s                          merge
  m                          map
   ,+d\++d\-                  lambda d: (d + "+", d + "-")
            c"O A B AB"d      over ["O", "A", "B", "AB"]
fgzYJ                      print all J's items x where g(input, x)
fgZzJ                      print all J's items x where g(x, input)

```
> 0 votes

# Answer
# J, 120 bytes

```
   f=.3 :';"1(2 8$,(s-:"*<y,'' '')#8 2 8$#:213472854600871062656691437010712264449x)#s=.<;.2''A+ B+ AB+ O+ A- B- AB- O- '''

   f 'A+'
A+ AB+
A+ O+ A- O-

   f 'AB-'
AB+ AB-
A- B- AB- O-

```

The function fails on invalid inputs. The big decimal number is the encoding of the full compatibility matrix.

(Very long solution for multiple reasons.)

Try it online here.
> 0 votes

# Answer
# 05AB1E, 29 bytes

```
„ABD`'O)„+-âJÐIkVāY&èê,āY~èê,

```

Try it online!
> 0 votes

---
Tags: code-golf, combinatorics, bitwise
---


title: Tips for golfing in TI-BASIC

text:
# Question
Title: Tips for golfing in TI-BASIC
What general tips do you have for golfing in TI-BASIC for the TI-83/84+ series calculators? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to TI-BASIC (e.g. "remove comments" is not an answer).

Please post one tip per answer.

# Answer
> 23 votes
Your calculator is pretty smart at inferring the end of lines for you, and thus you can omit quite a few characters.

```
:Disp "HELLO WORLD    //is the same as...
:Disp "HELLO WORLD"

```

`For(` loops have a syntax like this - `For(variable, start, end, increment)`, but you can omit the increment and it will use 1:

```
:For(A,1,5     //is the same as...
:For(A,1,5,1)

```

and you can omit ending parentheses (at the end of lines) across the board:

```
:Output(1,1,A
:int(A
:round(A
etc.

```

Tested on my TI-84 Silver Edition calculator

If you think this is more than one idea (inferring endings) then I'll split them up

# Answer
> 15 votes
# Use `Ans`

If you will only use an expression in the next line, don't store it to a variable! The special Ans variable is a one-byte token that stores the value of the last expression evaluated. Thus:

```
Xsin(A)->R
Disp R+tanh(R

```

can be

```
Xsin(A)
Disp Ans+tanh(Ans

```

saving two bytes.

# Answer
> 10 votes
# Use a lookup table encoded in floating-point numbers

A slightly advanced tip:

Small lookup tables are useful for code golf: it's very often that we need a function that maps, for example, 0 to 1, 1 to 2, 2 to 1, and everything else to 0. However, TI-BASIC arrays are not suited for this purpose: for one thing, they're one-based, and for another, a value cannot be extracted until the array is stored in `Ans` or a list variable.

In my answer here, I store a small lookup table in a magic constant in base 11. Simply list the values you want to use,

```
{0,-1,5,-1,-1,2,9,-1,8,6}

```

convert to a useful form

```
{1,0,6,0,0,3,10,0,9,7}

```

write in your desired base (base 11)

```
.106003A097

```

and convert to base 10

```
-1+int(11fPart(11^Ans.0954191904

```

The shortest array approach is 8 bytes longer!

```
{1,0,6,0,0,3,10,0,9,7}-1:Ans(X+1

```

TI-BASIC only stores floats to 14 decimal digits, so you can store up to 44ish bits but only 14 decimal digits.

This technique can often be improved further by using brute-force search to find a magic constant rather than base-N encoding. I'm still in the process of golfing the answer above, but the lengendary TI-BASIC golfer Weregoose used this method to generate the differences between numbers coprime with 30 (that is, a repeating list of `6, 4, 2, 4, 2, 4, 6, 2` ) on the wiki/forum TI-BASIC Developer with this snippet:

```
2+2iPart(3fPart(576e^(fPart(I/8

```

The magic constant 576 was found using Mathematica, but if you don't own a copy use a script in your favorite language.

# Answer
> 6 votes
# Skip unnecessary variable initialization

Current consensus is to allow all code to be run on a fresh interpreter. We can take advantage of this—all uninitialized real variables start at `0` in TI-BASIC, and `Xmin` starts as the possibly useful value `-10`. So if you ever need to take a running total in a program that doesn't take input from Ans, or you really need a `-10` in one less byte, this tip can help you.

# Answer
> 6 votes
Put repeated expressions equation variables.

EX:

```
Remainder(randInt(1,9),1
Remainder(randInt(1,9),5
Remainder(randInt(1,9),10

```

Can be:

```
"randInt(1,9→u
Remainder(u,1
Remainder(u,5
Remainder(u,10

```

Note: it is hard to find a good use for this, but that does not mean you should forget equation variables :P

Source: http://tibasicdev.wikidot.com/selfmodify

-c4ooo from Omnimaga

# Answer
> 5 votes
# Smaller list generation

If you need a list `{1,2,...,N}`, where N is, say, 42, the obvious way to create it is

```
seq(X,X,1,42.

```

However, one byte smaller than that is a neat hack using the `binomcdf(` (cumulative binomial distribution) command.

```
cumSum(binomcdf(41,0

```

This only works when N is a constant, because the savings comes from replacing N-1 with its value in the code.

There are two cases that allow even shorter code.

If you already have a list `L1` of dimension N:

```
cumSum(1 or L1

```

If you don't care about order:

```
randIntNoRep(1,N     ;random permutation of numbers from 1 to N

```

# Answer
> 5 votes
# Eliminate End statements for If blocks at the end of a program

Saves two bytes: one for the End and one for the linebreak. It also allows you to use the implied Disp on the last line, often saving an additional byte.

```
[code]
If A>5
Then
Output(1,1,Ans²+Ans+A
Disp 3ln(A
End
//end of program

```

Can be:

```
[code]
If A>5
Then
Output(1,1,Ans²+Ans+A
3ln(A
//end of program

```

# Answer
> 5 votes
# Know your idioms

Here are some snippets I commonly use in code golf:

* Convert to truth-value (0/1): `not(not(Ans`, or `Ans and 1`. Which one to use depends on the parentheses needed.
* Add one to a truth-value: `int(e^(Ans`. Saves an open-paren over `1+(Ans`. Very useful, because TI-BASIC has one-based arrays.
* Map `{0,1}` to `{1,-1}`: `cos(πAns`. Saves one byte over `1-2Ans`.

---

* Sign function of a number: `tanh(ᴇ9Ans`
* Round towards positive infinity: `-int(-Ans`
* Number of digits in a positive integer: `1+int(log(Ans`
* Complex number to list `{Re,Im}`: `imag(Ans{i,1`

---

* Convert string to list: `seq(inString("...",sub(Ans,X,1)),X,1,length(Ans` (where `...` is the search string)
* Chop off first element of a list: `ΔList(cumSum(Ans`
* Chop off last element of a list: `ΔList(cumSum(Ans)-Ans`
* Check if all elements of list `L1` are unique: `SortA(L1:min(ΔList(L1`
* Search for the number X in a list (returns first occurrence): `1+sum(not(cumSum(Ans=X`
* Mode of a list when a single mode exists, and the list has at most 10 elements: (ugly, but short): `median(Ans,10^(seq(sum(Ans=Ans(X)),X,1,dim(Ans`

# Answer
> 4 votes
If you find yourself using

```
0→G ;or any other variable
;other lines of code

```

Then, you could use (to save a byte):

```
DelVar G;other lines of code

```

This is because when you delete a variable (`G`), it becomes its default value, in this case, `0`. Then, you could put another line after the `DelVar` statement, *without a newline*. Be careful when putting crucial control statements directly after a `DelVar` statement.

(Tested on TI-84)

# Answer
> 4 votes
# Which list variables to use?

When using lists, avoid the default lists `L₁` through `L₆` in favor of named lists with one-letter names: `ᶫA` through `ᶫZ` (where  is the little L).

Either one costs two bytes to reference (though `L₁` is a single token, it is a two-byte token) but when storing values in a list, you can drop the  symbol, saving a byte:

```
{1,2,3,4,5→ᶫA

```

can be

```
{1,2,3,4,5→A

```

The calculator checks the data type of the expression when deciding where the result is stored.

Similarly, `Input A` or `Prompt A` will store to `ᶫA` if the user enters a list instead of a number.

Several other commands can be used without the , though most of them are rarely used in golfing. For example, `Matr►list(` allows the  to be removed in its third, fourth, and higher arguments.

The general rule is that, if the command takes a list *variable name* and not a list *expression*, and if there is no alternative syntax that could put a different kind of variable there, then the command *might* work with the  left off.

This doesn't work with modifying a single entry of a list: `1→ᶫA(3` cannot be changed to `1→A(3`.

Of course, the best list variable to use is always `Ans`.

# Answer
> 2 votes
# Know your variable assignment costs

If you use a `B`-byte expression `N` times, should you assign it to a variable?

`Ans` costs `1+N` bytes to use (one for the linebreak and one for each time it's used, so use Ans when `(B-1)*(N-1)>2`. There can be only one `Ans` per line, so try all values for `Ans` that might be useful.

Real variables (e.g. `X`) cost `3+N` bytes, so use them when `(B-1)*(N-1)>4`.

List variables cost `3+2N` bytes, so use them when `(B-2)*(N-1)>5`.

Equation variables are the least useful: they need `4+2N` bytes. Use them when `(B-2)*(N-1)>6`.

```
Min. bytes in an expression to save
 N \ var. | Ans | Real | List | Eqn
------------------------------------
 2           4     5      8      9
 3           3     4      5      6
 4           2     3      4      5

```

When a function evaluates to a list, store it to a list rather than an equation variable like `u`; this saves one byte.

Keep in mind that the presence or absence of close parentheses can often cause storing expressions to be advantageous if they're rearranged.

Now I'll contradict myself and say that one should write code on one line as much as possible. Why? Usually when there's a long repeated expression on a line, it can be simplified.

# Answer
> 1 votes
## int(rand over randInt(

X+int(Yrand is equal to or fewer bytes than randInt(X,Y as randInt is a 2 byte token. Some potential benefits:

X+ can be left out when lower bound is 0, saving two bytes

X+ is necessary before randInt( anyway in certain situations, for example random from a step function like {2,5,8,11}

X+int(Yrand(N can be used just as randInt(X,Y,N to generate a list of N random numbers

## Graphscreen initialization

To use functions like Line( easily with pixel coordinates it's necessary to initialize the graphscreen axes to square pixels and remove axes:

```
AxesOff
84→Xmin
72→Ymax
ZInteger

```

## Clamp

```
min(U,max(L,N

```

Where N is the number or algorithm and U and L are upper and lower bounds

## Is N in List

```
max(N={X,Y,Z

```

## More List math

```
L1*L2→L3

instead of

for(A,1,dim(L1
L1(A)*L2(A→L3(A
End

This also works for things like this:
not(L1
L1 and L2

```

## Output

Disp and Text( can both be chained, so Disp A,B will Display A then B on separate lines and Text(28,40,A,B will print A next to B on one line

If you only need to display a single thing at the end of a program you can drop the Disp command, the final line acts as an implicit Disp

## Tech from the optimal movement loop

A lot of these optimizations are part of the tech used to move a character around the screen in the fewest bytes

http://tibasicdev.wikidot.com/movement

## Token Size Lists

http://tibasicdev.wikidot.com/tokens

For help scoring

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


title: How short can you get?

text:
# Question
Title: How short can you get?
You are to write a program that, when given an integer between 1 and 5 (or 0 and 4 if you wish to use 0-indexing), outputs one of `Code`, `Golf`, `and`, `Coding` or `Challenges`. Each input can map to any of the five outputs. However, the mapping must be one to one (each input goes to a different output) and consistent when running the program multiple times.

For example, `1 -> Coding`, `2 -> Golf`, `3 -> and`, `4 -> Code` and `5 -> Challenges` is a perfectly acceptable mapping. The capitalisation and spelling of the outputs must match, but leading and trailing whitespace is perfectly acceptable.

Rather than , we will use a different scoring system (lets use `abcdef` as an example program):

* If your program works **whenever any single (\\$1\\$) character is removed**, your score is \\$1\\$.
    + So `bcdef`, `acdef`, `abdef`, `abcef`, `abcdf` and `abcde` should **all** work as program on their own
    + By "work", I mean that the program still fulfils the first two paragraphs of this challenge spec. The 5 possible inputs may be different to the unaltered program, and to each of the other altered programs, so long as they meet the rules above.
* If your program **still works whenever any pair (\\$2\\$) of consecutive characters are removed**, your score is \\$2\\$
    + So, to qualify for a score of \\$2\\$, `abcd`, `abcf`, `abef`, `adef` and `cdef` must all work according to the challenge spec
* And so on. If your program still works whenever any subset of length \\$n\\$ of consecutive characters is removed from it, your score is \\$n\\$.

The program with the largest \\$n\\$ wins. In order to compete, all programs must have a score of at least \\$1\\$. Your program must work for *all* \\$i \le n\\$ in order to qualify for a score of \\$n\\$. So in order to score \\$5\\$, your program must also score \\$1, 2, 3\\$ and \\$4\\$.

This is a Python program which will output all the possible alterations to your original program, along with the score they're worth.

# Answer
> 14 votes
# 8086 machine code (MS-DOS .COM), score 26 402

The file is 52 947 bytes long. The length was a product of what produced benign instruction sleds, and the maximum file size for .COM files (65 280 bytes -- 65 264 in case an interrupt happens before you can stop it).

Here in binary form, with repeating lines snipped out for obvious reasons:

```
00000000 : E9 67 67 67 67 67 67 67 67 67 67 67 67 67 67 67 : .ggggggggggggggg
00000010 : 67 67 67 67 67 67 67 67 67 67 67 67 67 67 67 67 : gggggggggggggggg
    <...>
00006720 : 67 67 67 67 67 90 D1 EE AD 93 AC E8 00 00 5A 2C : ggggg.........Z,
00006730 : 30 01 C2 3C 04 75 03 83 C2 02 D1 E0 D1 E0 01 C2 : 0..<.u..........
00006740 : 83 C2 1B B4 09 CD 21 CD 20 43 6F 64 65 24 47 6F : ......!. Code$Go
00006750 : 6C 66 24 61 6E 64 24 24 43 6F 64 69 6E 67 24 43 : lf$and$$Coding$C
00006760 : 68 61 6C 6C 65 6E 67 65 73 24 EB 9F 9F 9F 9F 9F : hallenges$......
00006770 : 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F : ................
    <...>
0000CE80 : 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F D1 : ................
0000CE90 : EE AD 93 AC E8 00 00 5A 2C 30 01 C2 3C 04 75 03 : .......Z,0..<.u.
0000CEA0 : 83 C2 02 D1 E0 D1 E0 01 C2 83 C2 1B B4 09 CD 21 : ...............!
0000CEB0 : CD 20 43 6F 64 65 24 47 6F 6C 66 24 61 6E 64 24 : . Code$Golf$and$
0000CEC0 : 24 43 6F 64 69 6E 67 24 43 68 61 6C 6C 65 6E 67 : $Coding$Challeng
0000CED0 : 65 73 24                                        : es$

```

In readable form:

```
org 0x100
cpu 8086

SLED_LEN    equ (0x6767 - (part1_end - part1) + 2)

db 0xe9
times SLED_LEN db 0x67

part1:
    nop
    shr si, 1       ; SI = 0x80
    lodsw           ; SI = 0x82
    xchg bx, ax     ; AX = 0
    lodsb           ; AL = first character of command line argument

    ; Load DX with IP, since we only know our strings' relative position
    call near .nextline
.nextline:
    pop dx

    sub al, '0'
    add dx, ax
    cmp al, 4
    jne .skip
    add dx, 2

.skip:
    shl ax, 1
    shl ax, 1
    add dx, ax

    add dx, 0x1b
    mov ah, 0x09
    int 0x21
    int 0x20

p1_msg0 db "Code$"
p1_msg1 db "Golf$"
p1_msg2 db "and$$"
p1_msg3 db "Coding$"
p1_msg4 db "Challenges$"

part1_end:

part2:
    db 0xeb
    times SLED_LEN db 0x9f

    shr si, 1       ; SI = 0x80
    lodsw           ; SI = 0x82
    xchg bx, ax     ; AX = 0
    lodsb           ; AL = first character of command line argument

    ; Load DX with IP, since we only know our strings' relative position
    call near .nextline
.nextline:
    pop dx

    sub al, '0'
    add dx, ax
    cmp al, 4
    jne .skip
    add dx, 2

.skip:
    shl ax, 1
    shl ax, 1
    add dx, ax

    add dx, 0x1b
    mov ah, 0x09
    int 0x21
    int 0x20

p2_msg0 db "Code$"
p2_msg1 db "Golf$"
p2_msg2 db "and$$"
p2_msg3 db "Coding$"
p2_msg4 db "Challenges$"

```

# Rundown

This is a slightly adapted variation on a previous answer of mine.

The active part is duplicated so that there is always one untouched by radiation. We select the healthy version by way of jumps. Each jump is a near jump, and so is only three bytes long, where two last bytes are the displacement (i.e. distance to jump, with sign determining direction). This displacement is replicated over and over, forming a long NOP sled of sorts.

We can divide the code into four parts which could be irradiated: jump 1, code 1, jump 2, and code 2. The idea is to make sure a clean code part is always used. If one of the code parts is irradiated, the other must be chosen, but if one of the jumps is irradiated, both code parts will be clean, so it will not matter which one is chosen.

The reason for having two jump parts is to detect irradiation in the first part by jumping over it. If the first code part is irradiated, it means we will arrive off mark, somewhere in the second NOP sled. If we make sure that such a botched landing selects code 2, and a proper landing selects code 1, we're golden.

For both jumps, we duplicate the displacement word, making each jump part one opcode followed by a massive repetition of the displacement. This ensures that irradiation somewhere in the sled will still make the jump valid, as long as at least two bytes of the sled remains. Irradiation in the first byte will stop the jump from happening at all, since the following sled will form a completely different instruction.

Take the first jump:

```
E9 67 67 67 67 ...      jmp +0x6767 / dw 0x6767 ...

```

If either of the `0x67` bytes are removed, it will still jump to the same place, as long as at least one word remains. If the `0xE9` byte is removed, we will instead end up with

```
67 67 67 67...

```

each of which is a address-size override prefix. The CPU will gladly chomp them all down, and then we fall through to code 1, which must be clean, since the damage was in jump 1.

If the jump is taken, we land at the second jump:

```
EB 9F 9F 9F 9F ...       jmp -0x61 / db 0x9f

```

If this byte sequence is intact, and we land right on the mark, that means that code 1 was clean, and this instruction jumps back to that part. The replicated displacement byte guarantees this, even if it is one of these displacement bytes that were damaged.

The astute reader will notice that this instruction jumps too far back, but that's alright, since if we hit the jump, then part1's NOP sled must be wholly intact, making a slightly longer jump backwards okay.

If we either land off the mark (because of a damaged code 1 or jump 1) or the `0xEB` byte is the damaged one, the remaining bytes will also here be benign:

```
9F 9F 9F 9F ...          lahf / lahf

```

Whichever the case, if we end up executing that sled of instructions, we know that either jump 1, code 1, or jump 2 were irradiated, which makes a fall-through to code 2 safe.

## Testing

Testing proved problematic. I've done some tests on certain corner-cases and a few random ones, but I have to find a better way for exhaustive testing. It should not be a problem up to the above-mentioned score.

The following program was used to automatically create all versions of the .COM file for a certain gap size. It also creates a BAT file that can be run in the target environment, which runs each irradiated binary, and pipes their outputs to separate text files. Comparing the output files to validate is easy enough, but DOSBox does not have `fc`, so it was not added to the BAT file.

```
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    FILE *fin, *fout, *fbat;
    int fsize;
    char *data;
    int gapsize = 1;

    if (!(fin = fopen(argv[1], "rb")))
    {
        fprintf(stderr, "Could not open input file \"%s\".\n", argv[1]);
        exit(1);
    }

    if (!(fbat = fopen("tester.bat", "w")))
    {
        fprintf(stderr, "Could not create BAT test file.\n");
        exit(2);
    }

    if (argc > 2)
    {
        gapsize = atoi(argv[2]);
    }

    fseek(fin, 0L, SEEK_END);
    fsize = ftell(fin);
    fseek(fin, 0L, SEEK_SET);

    if (!(data = malloc(fsize)))
    {
        fprintf(stderr, "Could not allocate memory.\n");
        exit(3);
    }

    fread(data, 1, fsize, fin);

    fprintf(fbat, "@echo off\n");

    for (int i = 0; i <= fsize - gapsize; i++)
    {
        char fname[512];

        sprintf(fname, "%06d.com", i);

        for (int j = 0; j < 5; j++)
            fprintf(fbat, "%s %d >> %06d.txt\n", fname, j, i);

        fout = fopen(fname, "wb");

        fwrite(data, 1, i, fout);
        fwrite(data + i + gapsize, 1, fsize - i - gapsize, fout);

        fclose(fout);
    }

    free(data);
    fclose(fin);
    fclose(fbat);
}

```

---
Tags: code-challenge, kolmogorov-complexity, radiation-hardening
---


title: Inverse Look-and-Say

text:
# Question
Title: Inverse Look-and-Say
# Background

The Look and Say Sequence is built up by reading off the digits of previous entries in the sequence, counting the number of digits in groups of the same digit. For example:

```
1 => 11 # (one 1)
11 => 21 # (two 1s)
21 => 1211 # (one 2, then one 1)
1211 => 111221 # (one 1, then one 2, then two 1s)

```

This sequence was the subject of various previous challenges. A simple Python 3 implementation of the generating function is:

```
>> from itertools import groupby
>> def look_and_say(obj):
      return "".join(f"{len(list(group))}{digit}" for digit, group in groupby(str(obj)))

```

Try it online!

# Challenge

The purpose of this challenge is to implement an inverse Look and Say function. **Given a Look and Say representation of a non-negative integer, your code should return the *smallest* non-negative integer for which the input is its Look and Say**. Note that this is not the same as general Run Length Decoding, since the output must encode back *precisely* to the input: see the examples below for some of the subtleties involved.

This is , so shortest code in bytes wins, with all the standard loopholes forbidden. Input can be passed in (or returned) as either an integer or a string.

# Test cases

```
10 => 0 # (1 zero)
12 => 2 # (1 two)
123 => 333333333333 # (12 threes)
1234 => 2444 # (1 two, 3 fours)
1232 => 222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222 # (123 twos, since 2222 would return 42 not 1232)
2019 => 999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999 # (201 nines, since the only non-negative starting with 0 is 0)
2109 => 999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999 # (210 nines, since 11 would return 21 not 2109)
123456 => 244466666
123454 => 333333333333444444444444444444444444444444444444444444444 # (12 threes, 45 fours)
124234 => 2222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222444 (124 twos, 3 fours, which is smaller than the alternatives)

```

# Invalid inputs

Since there are no integers which have the following Look and Say representations, the behaviour for these inputs is undefined:

```
1
3
20
100
1010
10010

```

# Answer
> 10 votes
# 05AB1E, 11 bytes

```
∞<ÅΔÅγs.ιJQ

```

Try it online!

Computes the look and say of all integers until finding one that matches the input. Will timeout for large outputs.

# Answer
> 8 votes
# JavaScript (ES6), 111 bytes

```
f=([x,y,...s],p,o=O='',m='')=>x?y?f([y,...s],p,o,m+=x,+m&&y^p&&f(s,y,o+y.repeat(m))):O||0:!O||O[o.length]?O=o:0

```

Try it online!

### Commented

```
f = (                     // f is a recursive function taking:
  [x, y,                  //   x, y = next two characters from the input string
         ...s],           //   s[]  = array of remaining characters
  p,                      //   p    = previous repeated digit, initially undefined
  o =                     //   o    = current output
  O = '',                 //   O    = shortest output so far
  m = ''                  //   m    = current multiplier, as a string
) =>                      //
  x ?                     // if x is defined:
    y ?                   //   if y is defined:
      f(                  //     do an unconditional recursive call:
        [y, ...s], p, o,  //       where y is put back in the input
        m += x,           //       and x is appended to m
        +m &&             //       if m is not zero'ish
        y ^ p &&          //       and y is not equal to p:
        f(                //         do another recursive call:
          s, y,           //           where p is updated to y
          o + y.repeat(m) //           and y is appended to o, m times
        )                 //       end of inner recursive call
      )                   //     end of outer recursive call
    :                     //   else:
      O || 0              //     return O, or 0 if it's empty
  :                       // else:
    !O || O[o.length] ?   //   if O is still empty or o is shorter than O:
      O = o               //     update O to o
    :                     //   else:
      0                   //     do nothing

```

# Answer
> 5 votes
# Jelly, 13 bytes

```
DŒrUDF⁼³µ1#@0

```

Try it online!

A full program that takes a list of digits and returns the first number that generates that as its look-and-say. Tries all numbers until one matches so will be slow for some inputs.

# Alternatives

## Jelly, 25 bytes

```
DŒṖṪxḌƊ€F$€ḌDŒrUƊDF⁼ʋƇDṢḢ

```

Try it online!

A monadic link taking an integer. Generates all possible inverse look-and-says (including invalid ones) and then tests them by seeing whether generating a look-and-say results in the input. Returns the smallest valid one.

## Jelly, 30 bytes

```
ŒṖUZḢEƲƝẸ$ÐḟṪxḌƊ€€ẠƇF€ḌD$ƑƇḌṢḢ

```

Try it online!

A monadic link taking a list of digits. Generates all possible inverse look-and-says (including invalid ones) and then tests them by seeing whether they violate any rules. Returns the smallest valid one.

Thanks to @ØranJohansen for pointing out a problem with the last two.

# Answer
> 2 votes
# Python 2, ~~200~~ ~~166~~ 165 bytes

```
lambda n:min(int(r)for r in b(n)if str(int(r))==r)
b=lambda n:[int(n[:i])*n[i]+v for i in range(1,len(n))for v in b(n[i+1:])if int(n[:i])*(n[i]!=v[:1])]if n else['']

```

Try it online!

# Answer
> 1 votes
# Ruby, 81 bytes

```
->n{(0..1/0.0).find{|r|r.to_s.chars.chunk{|w|w}.map{|a,b|[b.size,a]}*''==n.to_s}}

```

Try it online!

Brute force approach, could be 5 bytes shorter on a newer version of Ruby, but it doesn't matter because it's slow as hell for most numbers.

# Answer
> 1 votes
# Japt, 16 bytes

Brute force approach that'll crap out for larger outputs.

```
@¥Xò¦ ËÎiDlÃq}as

```

Try it

```
@¥Xò¦ ËÎiDlÃq}as     :Implicit input of integer U
@                    :Function taking an integer string X as argument
 ¥                   :  Test U for equality with
  Xò                 :  Partition X on
    ¦                :    Inequality
      Ë              :  Map each D
       Î             :    First character of D
        i            :    Prepend
         Dl          :    Length of D
           Ã         :  End map
            q        :  Join
             }       :End function
              a      :Return the first integer that returns true when passed through that function
               s     :After converting it to a string

```

# Answer
> 0 votes
# Charcoal, 67 bytes

```
⊞υ⟦0ωＳ⟧Ｆυ«≔§ι²θＦ∨‹θ1Ｌθ¿∧κ⁻§θκ§ι⁰⊞υ⟦§θκ⁺§ι¹×§θκＩ…θκ✂θ⊕κ⟧»Ｉ⌊ＥΦυ¬⊟ιＩ⊟ι

```

Try it online! Link is to verbose version of code. Generates all integers with the given look-and-say sequence and outputs the minimum thereof. Explanation:

```
⊞υ⟦0ωＳ⟧

```

Start by pushing a list of three items to the predefined list. The first item (initially `0`) represents the previous repeated digit (thus preventing the generated number from beginning with `0`), the second item (initially an empty string) represents the integer so far (as a string), while the third item (initially the whole input) represents the remaining input to process.

```
Ｆυ«

```

Loop over the list. This automatically iterates over additional items as they are pushed to the list.

```
≔§ι²θ

```

Get the remaining input into a dedicated variable. This saves several bytes as this variable is used multiple times. It does force me to wrap the block in braces, but this is offset by allowing me to use an `if` to save a byte.

```
Ｆ∨‹θ1Ｌθ

```

Loop over the string, but if it begins with a zero, only loop once (which gets ignored anyway, but this is a byte golfer than not looping at all).

```
¿∧κ⁻§θκ§ι⁰

```

Ignore the first character of the string (because there is no number to multiply it by), and also any character equal to the previously processed digit for this entry.

```
⊞υ⟦§θκ⁺§ι¹×§θκＩ…θκ✂θ⊕κ⟧

```

Push the next potential step to the list, comprising the current digit, the integer so far with the current digit repeated the prefix number of times, and the suffix.

```
»Ｉ⌊ＥΦυ¬⊟ιＩ⊟ι

```

After all possible steps have been processed, filter those that consumed the input exactly, and output the smallest resulting value.

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


title: Interpreted arithmetic

text:
# Question
Title: Interpreted arithmetic
A little known fact is that if you turn on enough language extensions (ghc) Haskell becomes a dynamically typed interpreted language! For example the following program implements addition.

```
{-# Language MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, UndecidableInstances #-}

data Zero
data Succ a

class Add a b c | a b -> c
instance Add Zero a a
instance (Add a b c) => Add (Succ a) b (Succ c)

```

This doesn't really look like Haskell any more. For one instead of operating over objects, we operate over types. Each number is it's own type. Instead of functions we have type classes. The functional dependencies allows us to use them as functions between types.

So how do we invoke our code? We use another class

```
class Test a | -> a
 where test :: a
instance (Add (Succ (Succ (Succ (Succ Zero)))) (Succ (Succ (Succ Zero))) a)
  => Test a

```

This sets the type of `test` to the type 4 + 3. If we open this up in ghci we will find that `test` is indeed of type 7:

```
Ok, one module loaded.
*Main> :t test
test :: Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero))))))

```

---

## Task

I want you to implement a class that multiplies two Peano numerals (non-negative integers). The Peano numerals will be constructed using the same data types in the example above:

```
data Zero
data Succ a

```

And your class will be evaluated in the same way as above as well. You may name your class whatever you wish.

You may use any ghc language extensions you want at no cost to bytes.

## Test Cases

These test cases assume your class is named `M`, you can name it something else if you would like.

```
class Test1 a| ->a where test1::a
instance (M (Succ (Succ (Succ (Succ Zero)))) (Succ (Succ (Succ Zero))) a)=>Test1 a

class Test2 a| ->a where test2::a
instance (M Zero (Succ (Succ Zero)) a)=>Test2 a

class Test3 a| ->a where test3::a
instance (M (Succ (Succ (Succ (Succ Zero)))) (Succ Zero) a)=>Test3 a

class Test4 a| ->a where test4::a
instance (M (Succ (Succ (Succ (Succ (Succ (Succ Zero)))))) (Succ (Succ (Succ Zero))) a)=>Test4 a

```

---

## Results

```
*Main> :t test1
test1
  :: Succ
       (Succ
          (Succ
             (Succ
                (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero)))))))))))
*Main> :t test2
test2 :: Zero
*Main> :t test3
test3 :: Succ (Succ (Succ (Succ Zero)))
*Main> :t test4
test4
  :: Succ
       (Succ
          (Succ
             (Succ
                (Succ
                   (Succ
                      (Succ
                         (Succ
                            (Succ
                               (Succ
                                  (Succ
                                     (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero)))))))))))))))))

```

*Draws inspiration from Typing the technical interview*

# Answer
> 10 votes
# ~~130~~ 121 bytes

<sup>-9 bytes thanks to Ørjan Johansen</sup>

```
type family a+b where s a+b=a+s b;z+b=b
type family a*b where s a*b=a*b+b;z*b=z
class(a#b)c|a b->c
instance a*b~c=>(a#b)c

```

Try it online!

This defines closed type families for addition `(+)` and multiplication `(*)`. Then a type class `(#)` is defined that uses the `(*)` type family along with an equality constraint to convert from the world of type familes to the world of typeclass prolog.

# Answer
> 7 votes
# 139 bytes

```
class(a+b)c|a b->c;instance(Zero+a)a;instance(a+b)c=>(s a+b)(s c)
class(a*b)c|a b->c;instance(Zero*a)Zero;instance((a*b)c,(b+c)d)=>(s a*b)d

```

Try it online!

Defines a type operator `*`. Equivalent to the Prolog program:

```
plus(0, A, A).
plus(s(A), B, s(C)) :- plus(A, B, C).
mult(0, _, 0).
mult(s(A), B, D) :- mult(A, B, C), plus(B, C, D).

```

Potato44 and Hat Wizard saved 9 bytes each. Thanks!

# Answer
> 2 votes
# Family-Version, 115 bytes

```
type family(a%b)c where(a%b)(s c)=s((a%b)c);(s a%b)z=(a%b)b;(z%b)z=z
class(a#b)c|a b->c
instance(a%b)Zero~c=>(a#b)c

```

Try it online!

This is uses a closed type family like potato44's. Except unlike the other answer I use only 1 type family.

```
type family(a%b)c where
  -- If the accumulator is Succ c:
  -- the answer is Succ of the answer if the accumulator were c
  (a%b)(s c)=s((a%b)c)
  -- If the left hand argument is Succ a, and the right hand is b
  -- the result is the result if the left were a and the accumulator were b
  (s a%b)z=(a%b)b
  -- If the left hand argument is zero
  -- the result is zero
  (z%b)z=z

```

This defines an operator on three types. It essentially implements `(a*b)+c`. Whenever we want to add our right hand argument to the total we instead put it in the accumulator.

This prevents us from needing to define `(+)` at all. Technically you can use this family to implement addition by doing

```
class Add a b c | a b -> c
instance (Succ Zero % a) b ~ c => Add a b c

```

# Class-Version, 137 bytes

```
class(a#b)c d|a b c->d
instance(a#b)c d=>(a#b)(f c)(f d)
instance(a#b)b d=>(f a#b)Zero d
instance(Zero#a)Zero Zero
type(a*b)c=(a#b)Zero c

```

Try it online!

This class version loses some ground to the family version, however it is still shorter than the shortest class version here. It uses the same approach as my family version.

---
Tags: code-golf, arithmetic, haskell, compile-time
---


# Question
Title: Simplify the following C ascii graphing function
This wasn't originally intended for code-golf, just as a little debugging routine to roughly visualize something "goofy" going on in a model of some (irrelevant here) physical process. But when I saw how surprisingly short it was, compared to my expectations, I just wondered if it can be further shortened. And that's primarily with respect to #statements (rather than #chars just by shortening variable names).

So, the function's `void asciigraph ( double *f, int n )` where `f[]` contains `n` doubles representing values of some more-or-less continuous function to be illustrated/graphed on your terminal. My implementation is below, along with a test driver, whose output is below that. Can you do better/shorter?...

```
#include <stdio.h>
#include <math.h>
/* --- entry point --- */
void asciigraph ( double *f, int n ) {
  int    row=0,nrows=24, col=0,ncols=78;
  double bigf=0.0;
  for ( col=0; col<n; col++ )
    if ( fabs(f[col]) > bigf ) bigf = fabs(f[col]);
  for ( row=0; row<nrows; row++ ) {
    double yval = bigf*((double)(nrows/2-row))/((double)(nrows/2));
    for ( col=0; col<ncols; col++ )
      printf("%c",(yval*f[(col*(n-1))/(ncols-1)]>=yval*yval? '*':' '));
    printf("\n"); }
  } /* --- end-of-function asciigraph() --- */

#ifdef TESTDRIVE
int main ( int argc, char *argv[] ) {
  double f[999], pi=3.14159;        /* stored function to be graphed */
  int    i=0, N=511;            /* f[] index */
  void   asciigraph();
  for ( i=0; i<N; i++ ) {
    double x = 2.0*pi*((double)i)/((double)(N-1));
    f[i] = .5*sin(2.*x+pi/3.) + 1.*sin(1.*x+pi/2.); }
  asciigraph(f,N);
  } /* --- end-of-function main() --- */
#endif

```

Try it online!

Compile it (for linux) as `cc -DTESTDRIVE asciigraph.c -lm -o asciigraph` and then the sample output is

```
******                                                                      **
********                                                                  ****
*********                                                                *****
**********                                                              ******
***********                                                            *******
************                                                          ********
*************                                                        *********
*************                                                       **********
**************                                                     ***********
***************                                                   ************
****************                                                 *************
******************************************************************************
                  *********************************************
                  *******************************************
                   *****************************************
                    *********************          *****
                     *****************
                       ************
                         ********

```

So, the eleven lines comprising asciigraph() above can be reduced two ways: **(a)** just "syntactically compressing" the code (e.g., put the final `}` on the same line as the final statement), or **(b)** by finding a niftier algorithm than mine, which compares each f-value to the yval "level line" (in which case maybe your algorithm wouldn't need to find that bigf at all). Obviously (I'd think it's obvious), the "niftier algorithm" approach is what I'm more interested in.

Replacing the test driver with the following will yield a moving wave:

```
int main ( int argc, char *argv[] ) {
  double f[999], pi=3.14159;            /* stored function to be graphed */
  double t=0.0, dt=0.05, w1=16.,w2=3.;  int Nt=50;
  int    i=0, N=511;                    /* f[] index */
  void   asciigraph();
  while ( --Nt > 0 ) {
    for ( i=0; i<N; i++ ) {
      double x = 2.0*pi*((double)i)/((double)(N-1));
      f[i] = .75*sin(2.*x+pi/3.+w1*t) + 1.*sin(1.*x+pi/2.+w2*t); }
    system("sleep 0.25; clear");
    asciigraph(f,N);
    t += dt; }
  } /* --- end-of-function main() --- */

```

# Answer
# C (gcc), ~~164 167~~ 162 bytes

```
r,c;void asciigraph(f,n,b,y)double*f,b,y;{for(b=0,r=n;r--;)b=fmax(b,fabs(f[r]));for(;++r<24;puts(""))for(y=b-b/12*r,c=0;c<78;)putchar("* "[y*f[c++*~-n/77]<y*y]);}

```

Try it online!

Thanks to @Arnauld for -4 and @JohnForkosh for the bugfix.

Slightly golfed less

```
r,c;
void asciigraph(f,n,b,y)double*f,b,y;{
  for(b=0,r=n;r--;)
    b=fmax(b,fabs(f[r]));
  for(;++r<24;puts(""))
    for(y=b-b/12*r,c=0;c<78;)
      putchar("* "[y*f[c++*~-n/77]<y*y]);
}

```
> 5 votes

---
Tags: ascii-art, tips, c
---


title: Chopping Unicode Bytes

text:
# Question
Title: Chopping Unicode Bytes
# Introduction

Each Unicode codepoint can be represented as a sequence of up to 4 bytes. Because of this, it is possible to interpret some 2, 3, or 4-byte characters as multiple 1-byte characters. (See here for a UTF-8 to bytes converter).

# Challenge

Given a UTF-8 character, output it split into a sequence of 1-byte characters. If the character is 1-byte already, return it unchanged.

* Your program must take one, and exactly one, UTF-8 character as input. You may use any input method you wish, as long as it has been decided on meta that is is a valid method. You cannot take input as a bytearray or series of bytes; then the challenge would just be converting hex to ASCII.
* Your program must output one or more ASCII 1-byte characters. Again, any output method is allowed as long as it has been marked valid on meta. Edit: As per the conversation in the comments, output should be in Code Page 850.

Note: see this post for valid I/O methods.

# Example I/O

> `܀ (0x700)`
> `▄Ç (0xdc 0x80)`
>
> `a (0x61)`
> `a (0x61)`
>
> `聂 (0x8042)`
> `Þüé (0xe8 0x81 0x82)`

# Rules

This is , so shortest answer in bytes wins!

# Answer
# C# (Visual C# Interactive Compiler), ~~73~~ 85 bytes

```
a=>Encoding.UTF8.GetBytes(a).Select(b=>Encoding.GetEncoding(850).GetString(new[]{b}))

```

Try it online!

+12 bytes to use the updated code page
> 2 votes

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


# Question
Title: Determine the Winner of a Game of Australian Football
In Australian Football, goals are worth 6 points and behinds are worth 1 point. Scores may include the number of goals and behinds, as well as the total score. Given the number of goals and behinds for two different teams, determine which team won the game.

Take four integers `g1, b1, g2, b2` as input, and output two distinct values for whether the first team or the second team inputted won. Input format is flexible, but input order must allow it to be obvious which team is first. For example, `g1, g2, b1, b2` would be allowed, but `b1, g2, g1, b2` would not.

## Test Cases

Test cases will use `true` for the first team winning and `false` for the second team winning. Input is in the format `(g1,b1),(g2,b2)`.

```
(1,0),(0,1)        true
(2,0),(0,11)       true
(10,8),(11,1)      true
(0,0),(1,0)        false
(100,100),(117,0)  false
(7,7),(5,12)       true
(2,0),(0,13)       false

```

As an example, for input `(10,8),(11,1)`, team 1 scored 10 goals and 8 behinds, for a total of \\$10\*6+8\*1=68\\$ points, while team 2 scored \\$11\*6+1\*1=67\\$ points, so team 1 wins.

No input will be a draw - your program's behavior on draw input does not matter.

# Answer
> 7 votes
# Jelly, 3 bytes

```
ḅ6M

```

A monadic Link accepting a list of lists of integers, `[[g1,b1],[g2,b2]]`, which yields a list `[1]` or `[2]`.
(Draws would yield `[1,2]`)

...Or a full program printing `1` or `2`.

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

### How?

```
ḅ6M - Link: list of lists of integers, X
 6  - literal six
ḅ   - convert (X) from base 6 (vectorises)
  M - maximal indices

```

# Answer
> 5 votes
# International Phonetic Esoteric Language, 12 bytes (WIP language) (OLD)

```
6ɪθɪt6ɪθɪtʈo

```

Outputs `1` for true and `0` for false.

No TIO interpreter yet, but is runnable by cloning the repository above, and calling `python main.py "code here"`.

The TL;DR of the language is that it's a stack-based language where every instruction is a character from the International Phonetic Alphabet.

Takes in arguments as 4 inputs from STDIN, in the order `g1, b1, g2, b2`. Might be golfed down to less than 12 bytes once loops are fully implemented.

```
6ɪθɪt6ɪθɪtʈo
6            ; Push 6
 ɪ           ; Take number input, push
  θ          ; Pop 2, multiply, push
   ɪ         ; Take number input, push
    t        ; Pop 2, add, push
     6       ; Push 6
      ɪ      ; Take number input, push
       θ     ; Pop 2, multiply, push
        ɪ    ; Take number input, push
         t   ; Pop 2, add, push
          ʈ  ; Pop 2, if a > b push 1, otherwise 0
           o ; Pop, print

```

# Answer
> 5 votes
# CP-1610 assembly (Intellivision), 9 DECLEs1 ≈ 12 bytes

A routine taking input in **R0** (\\$g\_1\\$), **R1** (\\$b\_1\\$), **R2** (\\$g\_2\\$) and **R3** (\\$b\_2\\$) and setting the sign flag if the 2nd team wins, or clearing it otherwise.

```
**275**   PSHR  R5        ; push return address
**110**   SUBR  R2,   R0  ; R0 -= R2
**082**   MOVR  R0,   R2  ; R2 = R0
**04C**   SLL   R0,   2   ; R0 <<= 2
**0D0**   ADDR  R2,   R0  ; R0 += R2
**0D0**   ADDR  R2,   R0  ; R0 += R2
**0C8**   ADDR  R1,   R0  ; R0 += R1
**118**   SUBR  R3,   R0  ; R0 -= R3
**2B7**   PULR  R7        ; return
```

The CP-1610 has no multiplication instruction and may only shift by 1 or 2 positions at a time, so we compute the following expression instead:

```
((R0 - R2) << 2) + (R0 - R2) + (R0 - R2) + R1 - R3

```

### Full test code

```
          ROMW    10              ; use 10-bit ROM width
          ORG     $4800           ; map this program at $4800

          ;; ------------------------------------------------------------- ;;
          ;;  test code                                                    ;;
          ;; ------------------------------------------------------------- ;;
main      PROC
          SDBD                    ; set up an interrupt service routine
          MVII    #isr,     R0    ; to do some minimal STIC initialization
          MVO     R0,       $100
          SWAP    R0
          MVO     R0,       $101

          EIS                     ; enable interrupts

          SDBD                    ; R4 = pointer to test cases
          MVII    #@@data,  R4
          MVII    #$200,    R5    ; R5 = backtab pointer

@@loop    PSHR    R5              ; save R5 on the stack
          MVI@    R4,       R0    ; load the next test case
          MVI@    R4,       R1    ; into R0 .. R3
          MVI@    R4,       R2
          MVI@    R4,       R3
          CALL    score           ; invoke our routine
          BMI     @@true

          MVII    #$80,     R0    ; set output to '0'
          B       @@output

@@true    MVII    #$88,     R0    ; set output to '1'

@@output  PULR    R5              ; restore R5
          MVO@    R0,       R5    ; draw the output

          SDBD                    ; was it the last test case?
          CMPI    #@@end,   R4
          BLT     @@loop          ; if not, jump to @@loop

          DECR    R7              ; loop forever

@@data    DECLE   1, 0, 0, 1      ; test cases
          DECLE   2, 0, 0, 11
          DECLE   10, 8, 11, 1
          DECLE   0, 0, 1, 0
          DECLE   100, 100, 117, 0
          DECLE   7, 7, 5, 12
          DECLE   2, 0, 0, 13
@@end     ENDP

          ;; ------------------------------------------------------------- ;;
          ;;  ISR                                                          ;;
          ;; ------------------------------------------------------------- ;;
isr       PROC
          MVO     R0,       $0020 ; enable display

          CLRR    R0
          MVO     R0,       $0030 ; no horizontal delay
          MVO     R0,       $0031 ; no vertical delay
          MVO     R0,       $0032 ; no border extension
          MVII    #$D,      R0
          MVO     R0,       $0028 ; light-blue background
          MVO     R0,       $002C ; light-blue border

          JR      R5              ; return from ISR
          ENDP

          ;; ------------------------------------------------------------- ;;
          ;;  routine                                                      ;;
          ;; ------------------------------------------------------------- ;;
score     PROC
          PSHR    R5              ; push the return address

          SUBR    R2,       R0    ; R0 -= R2
          MOVR    R0,       R2    ; R2 = R0
          SLL     R0,       2     ; R0 <<= 2
          ADDR    R2,       R0    ; R0 += R2
          ADDR    R2,       R0    ; R0 += R2
          ADDR    R1,       R0    ; R0 += R1
          SUBR    R3,       R0    ; R0 -= R3

          PULR    R7              ; return
          ENDP

```

### Output

*screenshot from jzIntv*

---

*1. A CP-1610 opcode is encoded with a 10-bit value, known as a 'DECLE'. This routine is 9 DECLEs long.*

# Answer
> 4 votes
# Python 3, 26 bytes

```
lambda g,b,G,B:6*g+b>6*G+B

```

Try it online!

Not incredibly interesting answer.

# Answer
> 4 votes
# Cascade, 16 bytes

```
#6&
>
 |/
 +
* &

```

Try it online!

Reuses the same `6*a+b` logic for both teams then prints whether the first scores higher than the other

# Answer
> 4 votes
# C# (Visual C# Interactive Compiler), 22 bytes

```
(a,b,c,d)=>a*6+b>c*6+d

```

Try it online!

# Answer
> 3 votes
# Clean, 34 bytes

```
import StdEnv
$a b c d=a*6+b>c*6+d

```

Try it online!

Defines `$ :: Int Int Int Int -> Bool` with arguments taken like `$ g1 b1 g2 b2`

# Answer
> 3 votes
# Perl 6, 13 bytes

```
*×6+*>*×6+*

```

Try it online!

Takes input as 4 integers, and basically just does as the question asks

# Answer
> 3 votes
# , 12 bytes

```
>&(1#.6 1*])

```

Try it online!

# Answer
> 3 votes
# Scratch 3.0 ~~17~~ 16 blocks, ~~160~~ 143 bytes

*Score comes from proposed scoring method here*

*1 block/17 bytes saved thanks to @A* (or Uzer\_A on scratch)\_

Try it on Scratch

*As Scratchblocks*:

```
when gf clicked
repeat(2
ask[]and wait
set[m v]to((answer)*(6)
ask[]and wait
change[m v]by(answer
add(m)to[x v
end
say<(item(1) of [x v]) > (m)

```

## Answer History

Pretty much a port of my Keg answer.

Try it on Scratch

Input is in the form of `g1, b1, g2, b2`

*In Scratchblocks syntax*

```
when gf clicked
repeat(0
set[m v]to(0
ask[]and wait
change[m v]by((answer)*(6)
ask[]and wait
change[m v]by(answer
add(m)to[x v
end
say<(item(1) of [x v]) > (m)

```

Now I know what you're saying... *why golf in scratch?!?* Well, it's fun. That's why. Also, Scratch is unique in that it isn't very often featured here on CGCC.

# Answer
> 3 votes
# 33, 22 bytes

```
6OxcOasz6OxcOaclmzh1co

```

Try it online!

Takes the input as 4 delimited integers, and returns 0 for the first team winning, 1 for the second.

## Explanation:

```
6Oxc                   | Multiplies the first number by 6
    Oa                 | Adds the second number
        6Oxc           | Multiplies the third number by 6
            Oa         | Adds the fourth number
      sz      clmz     | Subtract this from the first team's score
                  h1co | Print 0 if the first team's score is greater, 1 otherwise

```

-4 bytes if nondistinct results are allowed:

```
6OxcOasz6OxcOaclmo

```

Will output the score difference; positive results mean the first team win, negative means the second team win.

# Answer
> 3 votes
# Scala, 11 bytes

```
_*6+_>_*6+_

```

Try it online!

Takes 4 Integers in the order of `g1 b1 g2 b2`.

# Answer
> 3 votes
# brainfuck, ~~45~~ ~~38~~ ~~36~~ ~~32~~ ~~29~~ 28 bytes

```
,[>,[<++++++>-],]-[[-<]>>]>.

```

Try it online!

Thanks to @Jo King for -8 bytes

Input is b1, g1, b2, g2 (goals and behinds are exchanged) Prints þ, if team 1 won. Prints null, if team 2 won.

code:

```
[tape: p1, p2, print marker]

[Get input and calculate scores]
,               input behinds of team 1
[               while input
  >,                go to next cell and input goals of team
  [<++++++>-]       add it 6 times to behinds
,]              repeat this with the second pair of values

[Determine, which one is better]
-               set print marker
[               while score of both teams is greater than zero
  [-<]              decrement and go to previous cell (team 1 or empty cell/in the first run, it will decrement the print marker a second time)
  >>                return to team 2 (or two cells to the right of the first team that became 0)
]
>               go one cell right. If team 1 won, we are at the print marker now
                If team 2 won, we are one cell right of the print marker
.           Print that

```

# Answer
> 2 votes
# Keg, 10 bytes (SBCS)

```
(2|¿¿6*+)>

```

Try it online!

As an Australian, I approve of this question.

Input taken as:

```
b1
g1
b2
g2

```

And 0 means team 2 and 1 means team 1

## Explained

```
(2| #twice
¿¿  #get input in the form of bn, gn where n is the team number
*6+ #multiply the goals by 6 and add the values
)>  #compare the two values to determine the winner

```

# Answer
> 2 votes
# C (gcc), ~~39~~ ~~35~~ ~~31~~ 26 bytes

```
e(a,b,c,d){a=(a-c)*6>d-b;}

```

0 is false

1 is true

Input to function is (g1, b1, g2, b2)

Thanks to Doorknob for -5 bytes

Try it online!

# Answer
> 2 votes
# Zsh, 19 bytes

try it online!!

```
((6*$1+$2>6*$3+$4))

```

Input order is `g1 b1 g2 b2`. Exit codes `0==true` and `1==false`

# Answer
> 2 votes
# 05AB1E, ~~6~~ 5 bytes

```
6δβZk

```

Input as a nested list `[[g1,b1],[g2,b2]]`. Output `0` if team 1 wins and `1` if team 2 wins.

-1 byte thanks to *@Grimy* for reminding me about `δ`.

Try it online or verify all test cases.

**Explanation:**

Apparently arbitrary base conversion on nested lists doesn't work without an explicit ~~map~~ outer product.

```
 δβ    # Apply arbitrary base-conversion double-vectorized,
6      # using the (implicit) input-list of lists and 6 as base
       # (i.e. [a,b] becomes 6a+b (or to be more precise: 6¹a + 6⁰b))
   Z   # Get the maximum of this mapped list (without popping the list itself)
    k  # And get the 0-based index of this maximum in the mapped list
       # (after which the top of the stack is output implicitly as result)

```

# Answer
> 2 votes
# Brain-Flak, 62 bytes

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

```

Outputs `1` if the first team lost, and `0` if they won (or tied).

Try it online!

```
# Input: G B g b

   (                                 <(())>)                   # Push 1 under...
    ({})({}){}){}{}                                            #   6G + B
                   [                ]                          #   Minus
                    (({})({}){}){}{}                           #   6g + b
                                             <>                # Switch stacks
([(                                         (  )])             # Push 0 under -(6G+B-6g+b)
                                                   ({}())<>    # Add 1 and switch stacks...
                                                  {        }   #   until one stack reaches 0
                                                            {} # Pop, leaving either 1 or 0

```

# Answer
> 2 votes
# PowerShell, 35 bytes

```
param($g,$b,$h,$c)$g*6+$b-gt$h*6+$c

```

Try it online!

# Answer
> 2 votes
# Poetic, 751 bytes

```
the game:a game o soccer
for a moment of my fun,i kicked my leg
o,i hurt a player
o.m.gee,o no
suddenly i then apologized a little
o.m.gee,o no
but really,i loved a good soccer battle
a game i am doing,i love it
there is a game,a twenty-to-one unwinnable match(as we called it,i mean)a match we won
a wonder of an event i saw
i played,i go in again
i am happy in a match-up of teams,i am pumped
then o,a coach i saw played soccer
i know i do admire a game o soccer
o,a match was not a bummer,and also i am making in an extra score
i think i saw a split net,a hole i ripped out a net
i am ready to win a match
o,my people and i love a sport,a bit o soccer
i am going in a game,i score,i win
o really,i am doing a game o soccer
play ball
i am gonna wi-n

```

Try it online!

Boy, this was a tough one to write.

Input is in the following format:

```
g1
b1
g2
b2

```

This gives the error code of "Mismatched IF/EIF" if the first team wins, and "Unexpected EOF" if the second team wins. (Incidentally, a tie is treated as the second team winning).

# Answer
> 1 votes
# Retina 0.8.2, 34 bytes

```
\d+
$*
(1*),
$1$1$1$1$1$1
(1*);\1$

```

Try it online! Link includes test cases. Outputs `1` if the second team doesn't win and `0` if it does. Explanation:

```
\d+
$*

```

Convert the input to unary.

```
(1*),
$1$1$1$1$1$1

```

In each pair, multiply the first number by six and add the second.

```
(1*);\1$

```

Check whether the second number is greater than the first. Alternatively, you could use `^(1*);\1` which would output `0` if the first team wins and `1` if it doesn't.

# Answer
> 1 votes
# ABC-assembler, ~~111~~ 74 bytes

```
.o 0 4 iiii
f
	subI
	pushI 6
	mulI
	addI
	subI
	pushI 0
	ltI
.d 0 1 b
	rtn

```

Try it online!

It doesn't use anything above the most basic stack operations:

```
subI    | B = [g1-g2,b1,b2]
pushI 6 | B = [6,g1-g2,b1,b2]
mulI    | B = [6*g1-6*g2,b1,b2]
addI    | B = [6*g1+b1-6*g2,b2]
subI    | B = [6*g1+b1-6*g2-b2]
pushI 0 | B = [0,6*g1+b1-6*g2-b2]
ltI     | B = [0<6*g1+b1-6*g2-b2]

```

# Answer
> 1 votes
# PHP (7.4), 32 bytes

```
fn($g,$b,$G,$B)=>$g+$b/6>$G+$B/6

```

Try it online!

# Answer
> 1 votes
# Perl 5, 18 bytes

```
say<>*6+<>><>*6+<>

```

Try it online!

Input is line separated:

```
g1
b1
g2
b2

```

# Answer
> 1 votes
# Wolfram Language (Mathematica), 13 bytes

```
6#+#2>6#3+#4&

```

Try it online!

straightforward and boring

# Answer
> 1 votes
# Whitespace, 115 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _STDIN_as_integer][T    T   T   _Retrieve_integer][S S S T  T   S N
_Push_6][T  S S N
_Multiply][S N
S _Duplicate][S N
S _Duplicate][T N
T   T   _STDIN_as_integer][T    T   T   _Retrieve_integer][T    S S S _Add][S N
S _Duplicate][S N
S _Duplicate][T N
T   T   _STDIN_as_integer][T    T   T   _Retrieve_input][S S S T    T   S N
_Push_6][T  S S N
_Multiply][S N
S _Duplicate][S N
S _Duplicate][T N
T   T   _STDIN_as_integer][T    T   T   _Retrieve_input][T  S S S _Add][T   S S T   _Subtract][N
T   T   N
_If_negative_jump_to_Label_NEGATIVE][S S S N
_Push_0][T  N
S T _Print_as_integer][N
N
N
_Exit_Program][N
S S N
_Label_NEGATIVE][S S S T    N
_Push_1][T  N
S T _Print_as_integer]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Prints `0` if team 1 wins and `1` (could also be `-1` for the same byte-count) if team 2 wins.

Try it online (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Integer g1 = STDIN as integer
Integer t1 = g1*6
Integer b1 = STDIN as integer
t1 = t1 + b1
Integer g2 = STDIN as integer
Integer t2 = g2*6
Integer b2 = STDIN as integer
t2 = t2 + b2
If(t1 - t2 < 0):
  Goto NEGATIVE
Print 0
Exit program

Label NEGATIVE:
  Print 1
  (implicitly exit with an error)

```

One minor note: since the inputs are guaranteed to be \\$\geq0\\$, I'm using that to my advantage to re-use the inputs as heap-addresses for the subsequent inputs. With challenges which can have negative inputs I'd have to re-push `0` as heap-address, since heap-addresses cannot be negative.

# Answer
> 1 votes
# Japt, 6 bytes

Input as a 2D-array. Outputs `1` for team 1, `0` for a draw or `-1` for team 2.

```
mì6 rg

```

Try it

```
mì6 rg     :Implicit input of array
m          :Map
 ì6        :  Convert from base-6 digit array
    r      :Reduce by
     g     :  Sign of difference

```

# Answer
> 1 votes
# Ruby, 21 bytes

```
->a,b,x,y{b-y>6*x-=a}

```

Try it online!

Worked around the boring solution, saved a byte and called it a day.

# Answer
> 1 votes
# SimpleTemplate, 84 bytes

Just the simple "multiply by 6, sum and compare" aproach, except the math support is extremelly lacking.

```
{@set*A argv.0,6}{@incbyargv.1 A}{@set*B argv.2,6}{@incbyargv.3 B}0{@ifB is lowerA}1

```

Outputs `0` for false and `01` for true.

---

Ungolfed:

```
{@// multiply the first argument by 6}
{@set* teamA argv.0, 6}

{@// add the 2nd argument to the previous result}
{@inc by argv.1 teamA}

{@// same as before, for argument 3 and 4}
{@set* teamB argv.2, 6}
{@inc by argv.3 teamB}

{@echo 0}
{@// alternative: teamA is greater than teamB}
{@if teamB is lower than teamA}
    {@echo 1}
{@/}

```

Everything should be clear with the comments (`{@// ... }`) added.

# Answer
> 1 votes
# Go, 44 bytes

```
func f(a,b,x,y int)bool{return a*6+b>=x*6+y}

```

Try it online!

# Answer
> 1 votes
## MathGolf, ~~7~~ 6 bytes

I am quite impressed that MathGolf has *8* block-starting builtins!

```
2É6*+>

```

TIO

## Explanation

```
2      Constant 2
 É     Start code block of length 3
  6*   Take one input * 6 (with implicit input)
    +  Take another input and add them
     > Take Greater than of the two constants in the stack
There is an implicit output.

```

# Answer
> 1 votes
# Whitespace, 101 bytes

```
(Lots of whitespace)
```

Try it online!

readable version:

```
lstl        call readint
sssttsl     push 6
tssl        mult
lstl        call readint
tsss        add
lstl        call readint
sssttsl     push 6
tssl        mult
lstl        call readint
tsss        add
tsst        sub
sssl        push 0
slt         swap
lttsl       jn otherteam
ssstl       push 1
lsssl       otherteam:
tlst        printi
lll         end

lssl        readint:
sssl        push 0
sls         dup
tltt        readi
ttt         retrieve
ltl         ret

```

# Answer
> 1 votes
# , 28 bytes

```
function(a,b,c,d)a*6+b>c*6+d

```

Try it online!

# Answer
> 1 votes
# Pyth, 12 bytes

```
qhQeo+*6hNeN

```

Try it online!

Pretty simple but Im happy with it. Takes `(g1,b1),(g2,b2)`, returns `True` or `False`

## How it works

```
qhQeo+*6hNeN
qhQ          - The first input is equal to..
   eo        - The last input of a sorted list (implicitly the input)
     +*6hNeN - With the key 6 * first (hN) + last (eN)

```

# Answer
> 1 votes
# GolfScript, 11 bytes

Puts the code block into a function.

```
{6*+@@6*+>}

```

Try it online!

---
Tags: code-golf, decision-problem, integer, game
---