title: Based Palindromes

text:
# Question
Title: Based Palindromes
A palindromic number, as a refresher, is any number which reads the same forward as backwards. However, what about palindromes in other bases?

## Input

Any integer `b` where `b > 1`.

## Output

All integer base 10 numbers from 0 to 1000 inclusive that are palindromes in base b. The output can either be a list of integers, or integers separated by a delimiter such as a comma or a newline.

## Test cases

`Input->Output`

`10->{0,1,2,3,4,5,6,7,8,9,11,22,33,44,55,66,77,88,99,101,111,121,131,141,151,161,171,181,191,202,212,222,232,242,252,262,272,282,292,303,313,323,333,343,353,363,373,383,393,404,414,424,434,444,454,464,474,484,494,505,515,525,535,545,555,565,575,585,595,606,616,626,636,646,656,666,676,686,696,707,717,727,737,747,757,767,777,787,797,808,818,828,838,848,858,868,878,888,898,909,919,929,939,949,959,969,979,989,999}`

`2->{0,1,3,5,7,9,15,17,21,27,31,33,45,51,63,65,73,85,93,99,107,119,127,129,153,165,189,195,219,231,255,257,273,297,313,325,341,365,381,387,403,427,443,455,471,495,511,513,561,585,633,645,693,717,765,771,819,843,891,903,951,975}`

`9->{0,1,2,3,4,5,6,7,8,10,20,30,40,50,60,70,80,82,91,100,109,118,127,136,145,154,164,173,182,191,200,209,218,227,236,246,255,264,273,282,291,300,309,318,328,337,346,355,364,373,382,391,400,410,419,428,437,446,455,464,473,482,492,501,510,519,528,537,546,555,564,574,583,592,601,610,619,628,637,646,656,665,674,683,692,701,710,719,728,730,820,910,1000}`

# Answer
> 12 votes
# Python 3, 78 bytes

Outputs the numbers in decreasing order `1000 -> 0`, and short-circuits with a `ZeroDivisionError`

```
def f(b,n=1000):
 r=0;m=n
 while m:r=r*b+m%b;m//=b
 n==r==print(n);f(b,n-n//n)

```

Try it online!

The `f(b,n-n//n) -> f(b,n-1)` recurses until `0`, and errors because dividing by zero is undefined.

### Python 3, 76 bytes

We can shorten the answer by 2 bytes if a floating-point output is allowed.

```
def f(b,n=1e3):
 r=0;m=n
 while m:r=r*b+m%b;m//=b
 n==r==print(n);f(b,n-n/n)

```

Try it online!

# Answer
> 10 votes
# 05AB1E, 7 bytes

```
₄ÝʒIвÂQ

```

Try it online!

## Explained

```
₄Ý	"Push the range [0, 1000]"\
  ʒ	"and keep the items where:"\
   Iв	"After being converted to base (input)"\
     ÂQ	"have its reverse equal to itself"\

```

# Answer
> 10 votes
# C (gcc) forwards, ~~118~~ ~~117~~ 115 bytes

```
b[11],*p,*x,i,m;f(n){for(i=-1;i++<1e3;){for(p=x=b,m=i;m;*p++=m%n,m/=n);while(p>x)m|=*--p-*x++;m||printf("%d,",i);}}

```

Try it online!

# C (gcc), backwards, ~~115~~ 113 bytes

```
b[11],*p,*x,i,m;f(n){for(i=1001;i--;){for(p=x=b,m=i;m;*p++=m%n,m/=n);while(p>x)m|=*--p-*x++;m||printf("%d,",i);}}

```

Try it online!

## Explanation

C signature:

```
// Technically implicit int with a void return
void f(int base);

```

Loops through all numbers from 0 to 1000, converts them to base `base` by hand, then checks if it is a palindrome.

The backwards version does the same thing, but backwards.

Prints matching numbers, comma separated, to stdout.

Ungolfed version

```
#include <stdio.h>
// A buffer to hold our converted integer.
// It is large enough for 1000 in binary.
int buffer[11];
// Start and end pointers for buffer
int *start, *end;
// Loop counter
int i;
// Temporary
int tmp;

void f(int base)
{
    // Loop for 0 to 1000
#ifdef BACKWARDS
    // Loop backwards
    for (i = 1001; i-- != 0;) {
#else
    // Loop forwards
    // for (i = 0; i <= 1000; i++)
    for (i = -1; i++ < 1e3; ) {
#endif
        // Convert to base in buffer, tracking the length in end.
        for(start = end = buffer, tmp = i; tmp != 0;) {
            *end++ = tmp % base;
            tmp /= base;
        }

        // Check if it is a palindrome.
        // Loop while our starting pointer is less than our ending pointer.
        // tmp will zero at the start thanks to the loop condition.
        while (end > start)
            // Assembly style comparison using subtraction.
            // If *end == *start, tmp will still be zero.
            // If not, it will be permanently set to non-zero with a binary or.
            tmp |= *--end - *start++;
        // If tmp is still zero (meaning it is a palindrome), print.
        tmp || printf("%d,", i);
    }
}

```

Thanks to Arnauld for the -1 bytes!

Thanks to Toby Speight for the -2 bytes!

# Answer
> 6 votes
# Jelly, 7 bytes

```
ȷŻbŒḂ¥Ƈ

```

Try it online!

## How it works

```
ȷŻbŒḂ¥Ƈ - Main link. Takes a base b on the left
ȷ       - 1000
 Ż      - [0, 1, 2, ..., 1000]
     ¥  - Group the previous 2 links into a dyad f(k, b):
  b     -   Convert k to base b
   ŒḂ   -   Is this a palindrome?
      Ƈ - Filter [0, 1, 2, ..., 1000], keeping those k that are true under f(k, b)

```

# Answer
> 6 votes
# Wolfram Language (Mathematica), 44 bytes

```
Pick[r=0~Range~1000,r-r~IntegerReverse~#,0]&

```

Try it online!

-13 bytes from @att

# Answer
> 6 votes
# Scala, ~~62~~ 87 bytes

* Fixed after Siu Ching Pong -Asuka Kenji- pointed out `BigInt`'s `toString` only works for bases up to 36.
* Saved 1 byte thanks to @cubic lettuce.

```
b=>0 to 1000 filter{x=>val y=Seq.unfold(x){q=>Option.when(q>0)(q%b,q/b)};y==y.reverse}

```

Try it online!

This is pretty straightforward. It makes a range from 0 to 1000, then filters by checking if they equal their reverse in base `b`. To convert to base `b` (as a string), `BigInt`'s `toString` method ~~is~~was used, but now `Seq.unfold` is used to create a `Seq` of digits.

# Answer
> 6 votes
# JavaScript (ES6),  ~~87~~  86 bytes

Returns a comma-separated string.

```
n=>(g=k=>--k&&g(k)+((h=k=>a=k?[k%n,...h(k/n|0)]:[])(k)+''==a.reverse()?[,k]:''))(1001)

```

Try it online!

### How?

```
n => (                        // n = input base
  g = k =>                    // g is a recursive function taking a counter k
    --k &&                    //   decrement k; abort if it's equal to 0
    g(k) + (                  //   otherwise do a recursive call and append the ...
      ( h = k =>              //   ... result of the recursive function h
        a = k ?               //     which builds an array a[]
          [ k % n,            //     consisting of each digit of k in base n,
            ...h(k / n | 0) ] //     dividing k by n and taking the integer part
        :                     //     for the next iteration until k = 0
          []                  //
      )(k) + ''               //   invoke h with k and coerce the result to a string
      == a.reverse() ?        //   if this is palindromic:
        [, k]                 //     append a comma followed by k to the output
      :                       //   else:
        ''                    //     just append an empty string
    )                         //
)(1001)                       // initial call to g with k = 1001

```

# Answer
> 6 votes
# Japt, 11 bytes

```
A³ô fÈìU êê

```

Try it

# Answer
> 6 votes
# Husk, ~~12~~ 11 bytes

*Edit: -1 byte thanks to LegionMammal978*

```
foS=↔B⁰ŀdḋ9

```

Try it online!

The actual 'based palindrome' code is 7 bytes (`foS=↔B⁰`), but specifying 0...1000 costs ~~5~~ 4 (thanks to LegionMammal978) more bytes.
We could save a byte if it's Ok to output a few more based palindromes with values up to decimal 1024 (`foS=↔B⁰ŀ□32`).

```
f               # output the truthy values of
       ŀdḋ9     # series from zero up to one less than 1001
                # (decimal interpretation of binary digits of '9')
 o              # based on combination of 2 functions:
  S=↔           # 1. is it equal to reverse of itself?
     B⁰         # 2. digits in base given by argument

```

# Answer
> 5 votes
# Charcoal, 14 bytes

```
ＮθＩΦ⊕φ⁼↨ιθ⮌↨ιθ

```

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

```
Ｎθ              Input the base `b`
     φ          Predefined variable 1000
    ⊕           Incremented
   Φ            Filter on implicit range
        ι       Current value
       ↨ θ      Converted to base `b`
      ⁼         Equals
            ι   Current value
           ↨ θ  Converted to base `b`
          ⮌     Reversed
  Ｉ             Cast to string
                Implicitly print

```

# Answer
> 5 votes
# APL (Dyalog Extended), ~~17~~ 15 bytes

Thanks to Razetime for -2 bytes!
A bug fixed thanks to Siu Ching Pong!

Requires index origin `0`.

```
⍸⎕(⊤≡∘⌽⊤)¨⍳1001

```

Try it online!

```
                 ⍝ tradfn taking the base as input
          ⍳1001  ⍝ the indices up to 1000
 ⍵(     )¨       ⍝ apply a function to each index as a right argument and the input base as a left argument:
      ⌽⊤         ⍝  the reverse of the index converted to the input base
    ≡            ⍝  does it match
   ⊤             ⍝  the index converted to the input base
⍸                ⍝ all truthy indices

```

# Answer
> 5 votes
# C - 76 bytes

```
i=1001,a,z;f(b){for(;i--;i-z||printf("%d ",i))for(a=i,z=0;a;a/=b)z=z*b+a%b;}

```

# Explanation

Sufficiently different from my earlier answer to warrant posting separately. This time, we completely reverse the number, then compare to the original. So we don't need to eliminate trailing zeros, or special-case `0`.

```
void fun(int b)
{
    for (int i = 1001; i--;) {
        int z = 0;
        for (int a = i; a != 0; a /= b) {
            z = z*b + a%b;
        }
        if (i==z) {
            printf("%d ",i);
        }
    }
}

```

This method works reliably for `i` up to `INT_MAX/b` and `b` up to `INT_MAX`, or the appropriate equivalents if we change the integer type used. For unsigned types (or with `gcc -fwrapv`), it should work for the full range of `i`.

# Answer
> 5 votes
# Haskell, 63 bytes

```
f b|let 0%m=m;n%m=div n b%(m*b+mod n b)=[n|n<-[0..1000],n==n%0]

```

Try it online!

Based on a nice idea from dingledooper's Python answer: to check that `n` is a base-`b` palindrome, don't generate the list of base-`b` digits, but reverse `n` as a base-`b` number by running a base-conversion reading digits from the end, and check that the result still equals `n`.

The code `|let 0%m=m;n%m=div n b%(m*b+mod n b)` recursively defines an infix function `%` that reverses base `n` (given `0` as an initial second argument). Defining it inside of a `let` guard lets us access the argument `b` to the main function, whereas a standalone function would need to keep passing it with each recursive call.

# Answer
> 4 votes
# Python 3.8 (pre-release), ~~92~~ 85 bytes

```
lambda b:[i for i in range(1001)if(f:=lambda n:n*[0]and[n%b]+f(n//b))(i)==f(i)[::-1]]

```

Try it online!

Thanks to dingledooper for saving 7 bytes!

# Answer
> 4 votes
# , 27 bytes

```
((-:|.)@(#.inv)"0#])i.@1001

```

## how

* `(...) i.@1001` \- The whole thing is a J hook, meaning that the argument will be the left arg to everything in the parens, and the right arg will be the integers from 0 to 1000: `i.@1001`
* `...#]` The phrase inside the parens uses copy `#` to filter the right arg `]` by the boolean mask resulting from the phrase on the left of `#`:
* `(-:|.)@(#.inv)"0` \- The rank 0 `"0` ensures the phrase applies to each individual number of the right arg. The phrase itself first converts each of those numbers to a list of digits in the base given by the left arg `(#.inv)`, and then checks if that list equals its reverse `(-:|.)@`. The entire phrase will thus return 1 when this is true and 0 otherwise, and this boolean mask will filter the right arg as desired.

Try it online!

# Answer
> 4 votes
# C, 100 bytes

```
i=1001,a,z;f(b){for(;--i;)for(a=i,z=0;i%b*a;a/=b)if(a==z||a==(z=z*b+a%b))printf("%d ",i);puts("0");}

```

Try it online

## Ungolfed code

```
void fun(int b)
{
    for (int i = 1001; --i;) {
        if (i%b) {              /* no leading/trailing zeros */
            for (int a = i, z = 0; a != 0; a /= b) {
                if (a==z) {
                    printf("%d ",i);
                }
                z = z*b + a%b;
                if (a==z) {
                    printf("%d ",i);
                }
            }
        }
    }
    puts("0");
}

```

## Explanation

This outputs the numbers highest first, since no particular order was specified. For each candidate number, we reduce it (as `a`) by successively dividing by the base, using the remainder to build up the reverse number (in `z`). If `a` becomes equal to `z`, then we have a palindrome. Ordinarily, we'd stop there (`a >= z` in the loop condition), but for golfing, we continue all the way to `a==0`.

We need to test the equality both before and after transferring the remainder to `z`, to accept both odd and even length palindromes.

Finally, we print `0`, which is always a palindrome, and is easier to special-case than include in the loop.

The method works for integers up to `INT_MAX` if we ungolf the condition `i%b*a` back to `i%b&&a`, and would also work for other integer types.

# Answer
> 4 votes
# K (ngn/k), 18 bytes

```
{&{x~|x}'x\'!1001}

```

Try it online!

* `x\'!1001` convert each of 0..1000 to base-x representation
* `{x~|x}'` check if each representation is a palindrome
* `&` get indices of trues

# Answer
> 4 votes
# Haskell, 67 bytes

```
b&n=take n$mod n b:b&div n b
f b=[n|n<-[0..1000],reverse(b&n)==b&n]

```

`f` is the function of interest. Try it online!

Perhaps the only clever bit here is the use of `take n` to make a base case for the digit-expansion function. When `n=0`, `take n` ignores its argument and so the recursion stops via laziness; when `n>0`, there certainly won't be more than `n` digits so it's safe to keep only the first `n`. The following definition is equivalent (and equally long):

```
b&0=[]
b&n=mod n b:b&div n b

```

...but the `take n` version is more fun because it's more confusing. ^\_^

# Answer
> 3 votes
# Ruby 2.7, 74 bytes

```
->b{(0..1e3).select{(a=(g=->k,r=[]{k>0?g[k/b,r<<k%b]:r})[_1])==a.reverse}}

```

Try it online!

TIO uses an older version of Ruby, whereas in Ruby 2.7, we've numbered parameters, which saves two bytes.

---

# Ruby, 48 bytes

```
->b{(0..1e3).select{|k|(k=k.to_s b)==k.reverse}}

```

Try it online!

Doesn't works for bases over 64, due to the limitation in `.to_s` method.

# Answer
> 3 votes
# , ~~82~~ 81 bytes

(or 79 bytes using the rather-complicated delimiter of "`\n[1]` ")

*Edit: -1 byte thanks to caird coinheringaahing*

```
function(b)for(i in 0:1e3)if(!i||all((a=i%/%b^(0:log(i,b))%%b)==rev(a)))cat(i,'')

```

Try it online!

Manually calculates digits in new base representation, and checks whether they are the same as themselves reversed.

```
function(b)
 for(i in 0:1000)               # loop i through zero to 1000
  if(!i                         # if i is zero (always a palindrome),
   ||                           # or
   all(                         # if all the digits of
    (a=i%/%b^(0:log(i,b))%%b)   # a = the representation of i in base b
    ==rev(a))                   # are the same as themselves reversed
  )cat(i,'')                    # output this i

```

# Answer
> 3 votes
# JavaScript (V8), ~~77~~ 89 bytes

Fixed for bases greater than 36.

```
b=>{for(i=-1;i<1e3;){j=[],k=++i;while(k|=0)j.push(k%b),k/=b;''+j==j.reverse()&&print(i)}}

```

Try it online!

# Answer
> 3 votes
# PowerShell, 102 100 98 95 87 75 bytes

-14 bytes thanks to mazzy!

```
param($u)0..1e3|?{for($b=@();$_=($_-($b+=$_%$u)[-1])/$u){}"$b"-eq$b[11..0]}

```

Try it online!

# Answer
> 2 votes
# Vyxal `M`, 7 bytes

```
k1'⁰τḂ⁼

```

Try it Online!

# Answer
> 1 votes
# jq, 66 bytes

```
. as$a|range(1001)|select([while(.>0;./$a|floor)|.%$a]|reverse==.)

```

Try it online!

## Explanation

<pre><code>. as $a |                # Assign the input to $a.
range(1001) |            # For every item in [0..1000]:
select (                 # Filter out all items where:
  [ while(. > 0;         #     The list of quotients from repeatedly
     . / $a | floor)     #     short-dividing by $a

      |. % $a]           #     And then modulo-ing by $a
  | reverse == .)        # is equal to its reverse
```
</code></pre>

# Answer
> 1 votes
# Pyth, 11 bytes

```
f_IjTQUh^T3

```

Try it online!

---

```
f_IjTQUh^T3 | Explanation
------------+---------------------------------------
f           | filter
      Uh^T3 | the range [0, 1001)
   jTQ      | on whether each number in base <input>
 _I         | equals itself reversed

```

# Answer
> 1 votes
# Java 10, 118 bytes

```
b->{for(int i=-1;i++<1e3;){var s=b.toString(i,b);if(s.contains(new StringBuffer(s).reverse()))System.out.println(i);}}

```

Try it online.

**Explanation:**

```
b->{                           // Method with Integer parameter and no return-type
  for(int i=-1;i++<1e3;){      //  Loop `i` in the range [0,1000]:
    var s=b.toString(i,b);     //   Convert `i` to base-`b` as String
    if(s.contains(new StringBuffer(s).reverse()))
                               //   If this String is a palindrome:
      System.out.println(i);}} //    Print `i` with trailing newline

```

# Answer
> 0 votes
# Factor, ~~53~~ 52 bytes

```
[ 1e3 [0,b] swap '[ _ >base dup reverse = ] filter ]

```

Try it online!

---
Tags: code-golf, base-conversion, palindrome
---


# Question
Title: Write a (simplified) BitCycle interpreter
Implement a function or program that can run simplified BitCycle code. The functions you must implement are:

`<^>v`: Change the direction of a bit to the direction this is pointing.

`+`: Turn all 0s left and all 1s right.

`\` and `/`: Reflect one bit 90 degrees, then become inactive. In regular BitCycle, this is displayed as `-` or `|`, but that isn't required here. There are no collectors in this implementation, so these will never reset.

`?`: Take one bit at a time from input and send it east until all input is gone. You only need to worry about one input here. Bits only input from `?`.

`!`: Output and delete the bit present here. Only one output is required.

`~`: Send the inputted bit right and a negated version of it left.

`@`: When a bit hits this device, terminate the program.

The `=`, `0`, and `1` operations, multiple inputs/outputs, and collectors are not included in this specification. Other than that, everything should behave the same as in regular BitCycle.

## Basic BitCycle Rules

The program itself forms a rectangular grid. A list of bits, either 0 or 1, will be taken as input, and a potentially-empty list of bits will be given as output. Bits travel rightwards at a rate of 1 character per cycle (which is the term I will try to use for each "tick" of the program) until they hit some sort of operation character. In those cases, they will behave as specified by the operator. Code will stop running upon hitting a `@` character, or, depending on your output specification, also after some amount of time.

Left-right turns (from `+`) are relative to the direction of input. For example, if the character entered from the right, 0s will head downwards and 1s upward.

In standard BitCycle, values output as soon as they reach a `!` character. However you may instead save all the bits and output them at the end, as long as your interpreter will stop evaluation after some amount of time. Any bit which leaves the grid is destroyed.

For the purpose of this challenge, if it doesn't otherwise interfere with your code (ignoring integer overflow of their position), you may choose to not destroy the bits and just have them continue moving in the direction they were.

All undefined characters are no-ops.

## Example Programs (mostly taken from the BitCycle github)

```
?!

```

Cat program

```
v ~
!+~
?^<

```

Truth Machine

```
?  v
 ~ /
>! <

```

Negate the first bit, output the rest

```
?~
@+!

```

Output all 0s before the first 1

## Rules

This is , so lowest byte count wins.

Standard I/O rules apply for both the bits and the program.

You may choose whether to output as bits, a signed integer, or an unsigned integer, however, you must always be able to handle a case with only 1 or 0 bits as output AND if you don't output as bits, your program must meet the output-at-end rules. This is because any integer-output version wouldn't output anything on an infinite loop unless there was some form of max round number.

If you are outputting all bits at the end, your code must stop after some number of rounds. You may handle this in any "reasonable" way, as long as most simple programs will fully evaluate before your code automatically halts them.

A few examples of a valid method for halting the code:

* A button that shows the round number, and when pressed, outputs all bits and halts the program.
* A program which halts in n cycles, where n based on the number of flags it is given (as long as the max size of n isn't unreasonably small)
* A third input which specifies the number of cycles it should do.
* A program that always halts after 1000 cycles.
* A function which halts after going 100 cycles with no new I/O.

# Answer
> 6 votes
# Python 3, 442 bytes

```
def f(s,I):
 if[0]>I:return[]
 N='\n';l=s.split(N);W=max(map(len,l))+1;s=[*N.join(i.ljust(W-1)for i in l)+N*W];Q=s.index('?');B=[(Q,I.pop(0),1)];O=[];R=999;L=[-1,-W,1,W]
 while B*R:
  C=[];R-=1
  for p,v,d in B:p+=d;c=s[p];z=L[L.index(d)-3];d=dict(zip('<^>v+~\/',L+[z*2*v-z,z,W//d,-W//d])).get(c,d);O+=[v]*(c=='!');R*=c!='@';s[p]=[c,' '][c in'\/'];C+=[(p,1-v,-d)]*(c=='~')+[(p,v,d)]*(c not in'!?\n')
  if I:C+=[(Q,I.pop(0),1)]
  B=C
 return O

```

Try it online!

Test cases adapted from those in @Ajax1234's answer

Ungolfed:

```
def f(s, I):
    if I == []: return []
    l = s.split('\n')
    width = max(map(len, l))+1 # including newline
    s = list('\n'.join(i.ljust(width-1) for i in l) + '\n'*width)
    Q = s.index('?') # location input bits start at
    # directions are 1, -1, width, -width corresponding to right, left, down, up
    bits = [(Q, I.pop(0), 1)]
    O = [] # output
    R = 999 # rounds remaining
    directions = [-1, -width, 1, width]
    while bits and R:
        C = []
        R -= 1
        for pos, val, dir in bits:
            pos += dir
            char = s[pos]
            z = directions[directions.index(dir) - 3] # dir turned right
            dir = {'<':-1, '^':-width, '>':1, 'v':width, '+':z*(2*val - 1), '~':z, '\\':width//dir, '/':-width//dir}.get(char, dir)
            if char == '!':
                O.append(val)
            if char == '@':
                R = 0
            if char in '\/':
                s[pos] = ' '
            if char == '~':
                C.append((pos, 1-val, -dir))
            if char not in '!?\n':
                C.append((pos, val, dir))
        if I:
            C.append((Q, I.pop(0), 1))
        bits = C
    return O

```

# Answer
> 5 votes
# Python3, 789 bytes:

```
E=enumerate
def f(p,s):
 b=[*map(list,p.split('\n'))]
 x,y=[(x,y)for x,a in E(b)for y,c in E(a)if'?'==c][0]
 q,C,s,D=[(x,y,0,1,a,[(x,y)],i)for i,a in E(s)],[],[],{(0,1):[(-1,0),(1,0)],(0,-1):[(1,0),(-1,0)],(-1,0):[(0,-1),(0,1)],(1,0):[(0,1),(0,-1)]}
 while q:
  x,y,X,Y,B,p,I=q.pop(0)
  if(p,I)not in s and 0<=(x:=x+X)<len(b)and 0<=(y:=y+Y)<len(b[0]):
   s+=[(p,I)]
   if(O:=b[x][y])in(L:={'>':(0,1),'<':(0,-1),'v':(1,0),'^':(-1,0)}):q+=[(x,y,*L[O],B,p+[(x,y)],I)]
   if'+'==O:q+=[(x,y,*D[(X,Y)][B],B,p+[(x,y)],I)]
   if O in['\\','/']:q+=[(x,y,*((Y,X)if X==0 else(0,[1,-1][X==1])),B,p+[(x,y)],I)];b[x][y]=' '
   if'~'==O:q+=[(x,y,*D[(X,Y)][0],not B,[(x,y)],I)];q+=[(x,y,*D[(X,Y)][1],B,[(x,y)],I)]
   if'!'==O:C+=[int(B)]
   if'@'==O:q=[]
   if' '==O:q+=[(x,y,X,Y,B,p+[(x,y)],I)]
 return C

```

Try it online!

---
Tags: code-golf, array, interpreter
---


title: Period of the decimal representation

text:
# Question
Title: Period of the decimal representation
Write a function which takes a single positive integer *n* and returns the period of the decimal representation of 1/*n*.

Test cases:

```
1 -> 1               # 1/1 = 1.0000...... = 1._0
2 -> 1               # 1/2 = 0.5000...... = 0.5_0
3 -> 1               # 1/3 = 0.3333...... = 0._3
7 -> 6               # 1/7 = 0.14285714.. = 0._142857
13 -> 6
14 -> 6
123 -> 5
345 -> 22
654 -> 108
12345 -> 822
67890 -> 120

```

This is . Built-ins or libraries which return the period directly are not permitted. Numbers up to at least 100000 should work within reasonable time (at most several minutes).

# Answer
# APL, 19 chars/bytes\*

```
{(↑⍳⍨1∘↓)⌽⍵|10x*⍳⍵}

```

Nars2000. The previous version was wrong on some numbers, this should be right. I manually checked it on all numbers up to 50.

Again, credit goes to Ben Reich for the idea of looking at the period of `10^i (mod x)`

**Exploded view**

```
{                     ⍳⍵}   generate all naturals up to the argument ⍵
                 10x*       raise 10 to each of them, with unlimited precision
              ⍵|            compute the respective remainders mod ⍵
            ⌽               reverse the list
 (  ⍳⍨    )                 (fork) find the position of the first occurrence
  ↑                         of the fist element of the list
       1∘↓                  in the remainder of the list

```

**Examples**

```
      {(↑⍳⍨1∘↓)⌽⍵|10x*⍳⍵}¨1 2 3 7 13 14 123 345 654 12345 67890
1 1 1 6 6 6 5 22 108 822 120

```

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
<sup>\*: APL can be written in its own (legacy) single-byte charset that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of scoring, a program of N chars *that only uses ASCII characters and APL symbols* can be considered to be N bytes long.</sup>
> 12 votes

# Answer
## GolfScript (42 27)

```
{:x)1\[{.10*x%}*]-1%(?)}:P;

```

Benchmark time: 5 secs. Benchmarking code:

```
'"The time is #{Time.now#1
}"'~ puts
[1 2 3 7 13 14 123 345 654 12345 67890 99991]{[P]p}%
'"The time is #{Time.now#2
}"'~ puts

```

Credit to Ben Reich for the core idea of looking at the period of `10^i (mod x)`.

### Explanation

The period `p` is defined as the smallest positive integer such that for all sufficiently large `i` we have `frac(10^i * 1/x) = frac(10^(i+p) * 1/x)`. We can simplify that slightly to `frac(10^i / x) = frac(10^(i+p) / x)`. Now, `frac(a / x) = frac(b / x)` iff `a == b (mod x)`, so we're looking for the smallest positive integer such that for all sufficiently large `i`: `10^i == 10^(i+p) (mod x)`.

Suppose `10^i == 10^(i+p) (mod x)`. Then `10^(i+1) == 10 * 10^i == 10 * 10^(i+p) == 10^(i+p+1) (mod x)`; so once we get a repetition, we're in an unbreakable cycle.

There are only `x` distinct values `(mod x)`, so by the pigeonhole principle we must get a repetition in the first `x + 1` values of `10^i (mod x)`.

So what the code above does is to compute `x + 2` values of `10^i (mod x)`\*. Then the last one is guaranteed to be a repetition, and by reversing the list and searching for it I can find the most recent occurrence. Moreover, because I'm only doing the one search this is pseudolinear time.

* The extra one is to handle the special case `x = 1`, because I don't reduce `10^0 (mod x)` and so I'd be looking for a `0` in `[1]`.
> 8 votes

# Answer
## Golfscript - 26 bytes

```
{:i.)+.,{;10*i%.}%i>|,}:f;

```

*Edit: updated to output `1` if the decimal terminates, rather than the length of the decimal representation.*

A fairly efficient version. The value *67890* runs in approximately 10 seconds, and *99991* around 20 seconds. It's a bit slower than it was before (roughly half as fast), because the range that is iterated has been doubled, the first half of which is ignored.

**Alternative, also 26 bytes**

```
{:i.)+.n*{*i%.}%i>)^^,}:f;

```

This one works by iterating over the string `"\n"*(2*i+1)`, where `i` is the value passed to the function. The value passed to the block each time is the ordinal value of `"\n"`, which is *10*.

The `)^^` is a bit of a work-around. When you uncons a character from a string, the result is the ordinal value of the character removed, as mentioned above. However, appending that value back on will append the *string representation* of that number, rather than the character - fairly nonsymmetric behavior, and in my opinion a design flaw. If you actually wanted to do that, stringifying first would only cost one byte.

An extra copy of the final value is already on the stack, so I remove the final value again `)`, xor it with the string, and then xor it again, so that any characters which were added or removed by the first xor are restored. If `int op string` were treated as a character, rather than its string representation, `)^^` could be replaced by `|`.

Note that while strings (which in Golfscript are stored as an array of ints) will display the value of each character mod *256*, the values of each character may themselves be outside this range. When testing for uniqueness (via set operations) or containedness (via `?`), it is the actual value that is compared, rather than the display value.

A patch file for the current Golfscript interpreter:

```
61c61
<       to_gs
---
>       Gstring.new([self])

```

The above will only affect the behavior of `string op int` (and vice versa), where `op` is one of
`+-|&^`. Everything else remains unaffected, including the behavior of `Gint``.

The following **24 byte** solution would then become valid:

```
{:i.)+.n*{*i%.}%i>|,}:f;

```

And this also fixes a lot of other really ugly work-arounds.

---

## Python - 48 bytes

```
f=lambda n:len(set(10**-~i%n for i in range(n)))

```

Not the most efficient solution, but reasonable for values less than *100000*.

FWIW, the core element is identical to my solution for Generate cyclic numbers in decimal.

A more efficient version of the same code (**70 bytes**):

```
 def f(n):
  a=[];i=10%n
  while i not in a:a+=i,;i=i*10%n
  return len(a)

```

The value *99991* takes less than a second.
> 8 votes

# Answer
## GolfScript, ~~48~~ ~~47~~ 46

Thanks to @PeterTaylor for chopping two chars off.

```
{2{1$1$%!{.@\/\d}*}:d~;5d;9{2$%}{10*9+}/+,}:f;

```

I tried using J, but it kept giving me all sorts of strange results.

Test online

This basically divides 2 and 5 out of the number (2 and 5 are the prime factors of 10, and their reciprocals terminate, and stuff up the algorithm), then the lowest integer n such that the resulting number divides 10^n - 1 is the period.
> 3 votes

# Answer
## Perl, 52 characters

```
sub f{($p,%r)=1;1until$r{$p=$p*10%$_[0]}++;~~keys%r}

```

This is an uncomplicated implementation of the direct approach. (Fortunately the direct approach is also pretty efficient: thanks to modulo arithmetic, the math never has to deal with a number more than 10 times the input value.)

Since the challenge specified a function, I felt compelled to (re-)initialize my variables, something I wouldn't bother doing for a complete program. Likewise, the `~~` in the final statement is unnecessary if the function can be certain it will be invoked in a scalar context.
> 2 votes

# Answer
# Clojure, ~~102, 117, 115~~, 106

unformated:

```
(defn r([n](r{}(iterate #(mod(* % 10)n)10)0))([a[f & s]i](if(a f)(- i(a f))(recur(assoc a f i)s(inc i)))))

```

formatted:

```
(defn r
  ([n] (r {} (iterate #(mod (* % 10) n) 10) 0))
  ([a [f & s] i]
    (if (a f)
      (- i (a f))
      (recur
        (assoc a f i)
        s
        (inc i)))))

```

Running time scales with the period. Almost instantaneous on my computer for the sample values.

Basically, this calculates the result of the subtraction after each step in long division. A cycle is detected if at any point that number is the same as one that has been calculated before it.
> 2 votes

# Answer
# Pyth, 13 bytes

```
fq.^;yTQ.^;TQ

```

Uses turtle-and-hare algorithm (more information).

Watch it pass every test.
> 2 votes

# Answer
# 05AB1E, 9 bytes

```
ÌLR°I%ćk>

```

Port of *@PeterTaylor* GolfScript answer, so make sure to upvote him as well!

Try it online or verify almost all test cases. The last test case is omitted, which takes little over a minute.

If we want to output all test cases in less than a second, a port of *@primo*'s Python answer could be used, which comes in at **14 bytes** with a minor alternative of the same approach using a cumulative right-reduce:

```
>LTªÅ«T*I%}ćk>

```

Try it online or verify all test cases.

**Explanation:**

Based on the input \\$n\\$, I first generate a list within the range \\$\[n+1,1\]\\$. And then find the first 1-based index of a value \\$x\\$ which is truthy for \\$10^x\pmod n=10^{n+2}\pmod n\\$.

```
Ì          # Increase the (implicit) input-integer by 2
 L         # Pop and push a list in the range [1,input+2]
  R        # Reverse it to the range [input+2,1]
   °       # Map each value to 10 to the power that value
    I%     # Modulo the input
      ć    # Extract head; pop and push remainder-list and first item separately
       k   # Get the 0-based index of this 10**(input+2) in the list of
           # [10**(input+1),10**input,...,100,10]
        >  # Increase this by 1 to make it a 1-based index
           # (which is output implicitly as result)

```

```
>L         # Push a list in the range [1,input+1]
  Tª       # Append a trailing 10
    Å«     # Cumulative right-reduce, keeping all intermediate results:
      T*   #  Multiply the current integer by 10
        I% #  Modulo the input
     }     # After the right-reduce:
      ćk>  # Get the 1-based index of the extracted head, similar as above
           # (which is output implicitly as result)

```
> 2 votes

# Answer
# Vyxal `r`, 8 bytes

```
⇧ɾṘ↵%ḣḟ›

```

Try it Online!

Port of 05AB1E.

## How?

```
⇧ɾṘ↵%ḣḟ›
⇧ɾ        # Push range [1, (implicit) input + 2]
  Ṙ       # Reverse to make it range [input + 2, 1]
   ↵      # Map each value to 10 to the power of it
    %     # Modulo by the (implicit) input
     ḣ    # Head extract, push a[0] and a[1:]
      ḟ   # Get the index of this a[0] in this a[1:]
       ›  # Increment to make this a one-based index

```
> 1 votes

# Answer
# PARI/GP, 33 bytes

```
n->znorder(Mod(10,n/gcd(n,10^n)))
```

Attempt This Online!
> 0 votes

# Answer
# Stax, 7 bytes

```
üpßN▲╞§

```

Run and debug it

**Approach:**

1. Multiply by 10
2. Keep only fractional part
3. Repeat until a loop of values is found
4. Keep only the loop
5. Get the length
> 0 votes

---
Tags: code-golf, number-theory
---


title: King of the Cards

text:
# Question
Title: King of the Cards
# King of the Cards

*Code available here!*

In this King of the Hill challenge, you must write a bot that can play Crazy Eights. This is a card game often played by children, in which the objective is to empty your hand.

## How to Play

The game of Crazy Eights is deceptively simple. At the beginning of the game, each player gets dealt a hand of cards (in this case eight), with the remaining cards placed in the middle of the table as the draw pile. The top card is then placed face up and serves as the beginning of the discard pile. Then, each player can discard one card per turn if that card has a matching suit or rank with the top card on the discard pile. They may also play an 8, which allows them to change the effective suit of the 8 and therefore the suit the next player must follow. The played card then becomes the top card. If the player does not have any matching cards, they must draw from the draw pile until they get a matching card and play that. If they exhaust the draw pile, play passes to the next player. Players may draw at any time, even if they have playable cards (which does not count as a turn).

For example, if 6♣ is played, the next player:

* Can play a 6 of any suit
* Can play any club
* Can play an 8 (and then must declare a suit)
* Can draw and continue their turn.

If the draw pile runs out, then the discard pile (except for the top card) is shuffled and becomes the new draw pile.

The game ends once a player runs out of cards, in which case they are declared the winner. (This differs from normal Crazy Eights, and is included to make this game a bit simpler.)

# Bots

Bots must be written in Python. Bots will have access to the `kotc` module, which supplies these classes:

* `KOTCBot`, which bots must extend
* `Card`, which represents a card
* `Suit` and `Rank`, enums representing the suit and value of a card

Bots must implement a `play` method, which takes as input a `Card` representing the top card on the discard pile. This method must return a `Card` within that bot's `hand`. If the returned `Card` is not in the bot's `hand` that bot is disqualified. (I will leave a comment on it with information about the state of the game when it happened.) However, if the `Card` is an `Eight` then only the `rank` will be checked against the bot's `hand`. If the bot has no playable cards in its hand, the `play` method will ***NOT*** be called and the controller will automatically draw cards on behalf of the bot and add them to its `hand`. **The bot should NEVER modify its `hand`!** This will be done by the controller. The `play` method may also return `None` or `False`, which will cause its turn to be skipped.

Bots will compete against each other in matches of two, in an elimination-style tournament bracket. The winner will advance onwards, and the loser will be ~~executed~~ eliminated.

# API

## `KOTCBot`

This class is the actual bot.

Methods and properties: (Do NOT override any of these in your bot)

* `draw`: When called, this function draws a card from the pile and adds it to the bot's hand. It also returns the card drawn.
* `hand`: This property is a list of `Card`s representing the bot's hand.
* `arena`: This property is the `KOTCArena` instance the bot is playing in.

## `KOTCArena`

This class is accessible through the `arena` property of the `Bot`. It has three functions available to the bots:

* `handSizes`: Returns a list of the lengths of the hands of the other bots
* `discardSize`: Returns the size of the discard pile
* `drawSize`: Returns the size of the draw pile

## `Card`

The `Card` class represents a card, and takes a `Suit` and `Rank` when constructed. This class must be returned by the bot's `play` method. Its suit and rank can be accessed through their respective properties.

* `all`: This classmethod takes no parameters and returns a 52-item list of all possible card combinations.

*Note: All enumeration members are UPPERCASE.*

## `Suit`

Members of this enum:

* `CLUBS`
* `DIAMONDS`
* `SPADES`
* `HEARTS`

## `Rank`

Members of this enum:

* `ACE`
* `KING`
* `QUEEN`
* `JACK`
* `TWO` through `TEN`

# Example Bot

This bot just plays any available card, without using eights.

```
import kotc

class ExampleBot(kotc.KOTCBot):
  def play(self, discard):
    for card in self.hand:
      if card.suit == discard.suit or card.rank == discard.rank:
        return card

```

# Answer
> 3 votes
# BasicBot

```
import kotc
from random import shuffle
class BasicBot(kotc.KOTCBot):
  shuffle(self.hand)
  def play(self, discard):
    for card in self.hand:
      if (card.rank == kotc.Rank.EIGHT):
        playables = 0
        for card2 in self.hand:
          if card.suit == discard.suit or card.rank == discard.rank:
            playables+=1
        if playables<2:
          return card2

      if card.suit == discard.suit or card.rank == discard.rank:
        return card
    for card in self.hand:
        if card.suit == discard.suit or card.rank == discard.rank:
            return card

```

I think this will work. Pretty much ExampleBot, except it will play an eight if it has less than two other cards it can play. Currently doesn't prioritize playing a specific suit (that's next on my list of goals) but it still should be better than BasicBot.

---
Tags: king-of-the-hill, card-games
---


title: Unshuffle my poker chips

text:
# Question
Title: Unshuffle my poker chips
This part is somewhat detached from the actual array manipulation side of the challenge, scroll down for an explanation that is much more array-based

You've been learning how to shuffle poker chips recently, but, as you're still learning, you don't always get the perfect alternating shuffle that you're aiming for. Instead, they often get grouped into pairs or triples of chips between each shuffle. Now, to make things easier, you've been practicing with 2 colors of chips, black and white, so you can see the outcome of the shuffle.

One of your recent shuffles has produced this stack of 10 chips (where the left most element of the array is the top chip):

```
W B W W B B B W B W

```

Now, you want to unshuffle these chips and get them back to being two "blocks" of colors, either of these two:

```
W W W W W B B B B B
B B B B B W W W W W

```

Unfortunately for you, the only way you like to unshuffle chips is by taking a number of chips off the top, flipping that "substack" of chips over, then adding back to the top:

```
 W B W W B B B W B W
[W B W W]B B B W B W
 W W B W B B B W B W

```

Here, we flipped the top 4 chips over (reversed the prefix of length 4). Indeed, it is possible to unshuffle this stack in 5 flips:

```
 W B W W B B B W B W
[W B]W W B B B W B W
[B W W W]B B B W B W
[W W W B B B B]W B W
[B B B B W W W W]B W
[W W W W B B B B B]W
 B B B B B W W W W W

```

In fact, a greedy approach should, in this case, always generate the fewest number of flips when only using two colors of chips.

However, what if we instead use three colors? In this case, a strictly greedy approach (i.e. the lengths of the prefixes are always increasing) doesn't work. Consider, with green chips added in,

```
 G W G W W B B G G W B B

```

This can be solved in 5 flips as well:

```
 G W G W W B B G G W B B
[G W G W W B B]G G W B B
[B B W W G W G G G W]B B
[W G G G W G]W W B B B B
[G W]G G G W W W B B B B
[W G G G G]W W W B B B B
 G G G G W W W W B B B B

```

Once we start adding in even more colors, it gets even more complicated. For example, with 5 different colors (`W`, `B`, `R`, `G`, `Y`), we might have, say:

```
 R G B B G W B G R W W Y Y R Y

```

which can be done in 8 flips, in at least 2 ways, shown below:

```
 R G B B G W B G R W W Y Y R Y     R G B B G W B G R W W Y Y R Y
[R G B B G W B G R W W Y Y]R Y    [R G B B G W B G R W W Y Y]R Y
[Y Y W W R G B W G B B G R R]Y    [Y Y W W R G B W G B B G R R]Y
[R R G B B G W B G]R W W Y Y Y    [R R G B B G W B G]R W W Y Y Y
[G B W G B B]G R R R W W Y Y Y    [G B W]G B B G R R R W W Y Y Y
[B B G W]B G G R R R W W Y Y Y    [W B G G B B G R R R]W W Y Y Y
[W G B B B G G R R R]W W Y Y Y    [R R R G B B G G B]W W W Y Y Y
[R R R G G]B B B G W W W Y Y Y    [B G G]B B G R R R W W W Y Y Y
[G G R R R B B B]G W W W Y Y Y    [G G B B B]G R R R W W W Y Y Y
 B B B R R R G G G W W W Y Y Y     B B B G G G R R R W W W Y Y Y

```

---

Alternatively, in more array manipulation based terms: given a list of integers, we can rearrange it by repeatedly reversing prefixes of given lengths ("flips"). For example,

```
[3, 2, 3, 1, 1, 2] -> [2, 3, 3, 1, 1, 2] -> [1, 1, 3, 3, 2, 2] -> [3, 3, 1, 1, 2, 2] -> [2, 2, 1, 1, 3, 3] -> [1, 1, 2, 2, 3, 3]

```

Here, we sorted the list by reversing the prefixes of lengths \\$2\\$, \\$5\\$, \\$4\\$, \\$6\\$ and then \\$4\\$. In this case, 5 flips is the minimum number possible to sort this list in ascending order.

In this challenge, we don't require the final list to be sorted into ascending order. Instead, we simply want the list to be sorted so that equal elements are all adjacent to one another, in any order. For example, the previous example can be shortened to 2 flips:

```
[3, 2, 3, 1, 1, 2] -> [2, 3, 3, 1, 1, 2] -> [1, 1, 3, 3, 2, 2]

```

---

Your task is to, given a list of digits representing a chip stack, output the minimum number of flips required to arrange the list into a series of blocks of identical digits.

For example, we could represent our 5 color example above as

```
[1,2,3,3,2,4,3,2,1,4,4,5,5,1,5]

```

or even as the integer `123324321445515`. You may assume that the input does not contain more than 9 distinct digits (so all will be from `123456789`), and that the numbers of each digit are equal. You may take input in any reasonable manner or format.

This is a so the shortest code in bytes wins!

## Test cases

```
array -> output
[1,2] -> 0
[1,2,1,2] -> 2
[2,1,1,2] -> 1
[3,1,2,1,2,3] -> 3
[3,2,3,1,1,2] -> 2
[3,3,1,1,2,2,4,4] -> 0
[1,2,1,1,2,2,2,1,2,1] -> 5
[2,3,2,3,3,1,1,2,2,3,1,1] -> 5
[3,1,3,1,1,2,2,3,3,1,2,2] -> 5
[1,2,3,3,2,4,3,2,1,4,4,5,5,1,5] -> 8*
[2,5,1,1,5,3,1,5,2,3,3,4,4,2,4] -> 8*
[5,5,1,3,4,1,3,4,5,5,3,3,2,3,4,2,2,1,5,1,2,4,4,1,2] -> 15*

```

`*`: These are currently only an upper bound, and aren't proven to be the minimal number (just suspected). If you can get a lower value, please provide the list of flips to verify that value

# Answer
## Python3, 186 bytes:

```
import itertools as I
def f(a):
 q=[(a,0)]
 while q:
  j,c=q.pop(0)
  if len(set(t:=[u for u,_ in I.groupby(j)]))==len(t):return c
  for i in range(2,len(j)):q+=[(j[:i][::-1]+j[i:],c+1)]

```

Try it online!

The code above is a basic brute-force approach. However, the solution below, while longer, uses dynamic programming to produce results for all the test cases in about six seconds:

## Python3, 542 bytes

```
import itertools as I
E=enumerate
P=lambda a:[(j,[*k])for j,k in I.groupby(a)]
L=lambda a:[u for u,_ in P(a)]
V=lambda r:len(set(t:=L(r)))==len(t)
def f(a):
 q,s,R,H=[(a,0)],[a],[],[len(L(a))]
 while q:
  j,c=q.pop(0)
  if V(j):R+=[c];continue
  for x,(_,A)in E(r:=P(j)):
   for y,(_,B)in E(r):
    if x<y and A[-1]==B[0]:
     J=j[:(i:=sum(len(k[1])for k in r[:x])+len(A))][::-1]+j[i:]
     if(O:=J[:(Y:=i+sum(len(k[1])for k in r[x+1:y]))][::-1]+J[Y:])not in s:
      if(M:=len(L(O)))<=min(H):q+=[(O,c+1+(J!=j))];s+=[O];H+=[M]
 return min(R)

```

Try it online!
> 4 votes

# Answer
# Charcoal, 50 bytes

```
⊞υ⟦⁰Ｓ⟧Ｆυ¿¬ⅉ«≔⊟ιθ¿⊙θ⁻✂θ⌕θκλ¹κＦＬθ⊞υ⟦⊕Σι⁺⮌…θ⊕κ✂θ⊕κ⟧Ｉι

```

Try it online! Link is to verbose version of code. Takes input as a string of characters. Explanation: Uses brute force, in particular it always tries flipping one character, which is pointless.

```
⊞υ⟦⁰Ｓ⟧Ｆυ

```

Start a breadth-first search with `0` flips and the initial input.

```
¿¬ⅉ«

```

Stop when a solution has been found.

```
≔⊟ιθ

```

Remove the current string from the search term, leaving the flip count.

```
¿⊙θ⁻✂θ⌕θκλ¹κ

```

If there is a character that exists in a disjoint range, then...

```
ＦＬθ⊞υ⟦⊕Σι⁺⮌…θ⊕κ✂θ⊕κ⟧

```

... reverse each nontrival prefix of the string and push the result to the search list with an incremented flip count, otherwise...

```
Ｉι

```

... output the flip count as a string.

99-byte faster version based on @Ajax1234's second version, assuming it's correct (it only flips nontrivial proper prefixes), can easily deal with the second longest test case on TIO:

```
≔Ｌθη⊞υ⟦⁰θ⟧Ｆυ¿¬ⅉ«≔⊟ιθ≔ΦＬθ∧κ⁻§θκ§θ⊖κζ¿¬›Ｌζη«≔Ｌζη≔Φζ∨⁼§θκ§θ⁰‹κ⌈⌕Ａθ§θ⊖κζ¿ζＦ⁻Ｅζ⁺⮌…θκ✂θκＬθ¹Ｅυ§κ¹⊞υ⊞Ｏ⊕ικＩι

```

Try it online! Link is to verbose version of code. Works with both strings and lists. Explanation:

```
≔Ｌθη

```

Keep track of the minimum number of runs found so far.

```
⊞υ⟦⁰θ⟧Ｆυ

```

Start a breadth-first search with `0` flips and the initial input.

```
¿¬ⅉ«

```

Stop when a solution has been found.

```
≔⊟ιθ

```

Remove the current string from the search term, leaving the flip count.

```
≔ΦＬθ∧κ⁻§θκ§θ⊖κζ

```

Get the list of indices of starts of new runs (excluding the first run).

```
¿¬›Ｌζη«

```

If this does not exceed the minimum number of runs found so far:

```
≔Ｌζη

```

Update the minimum number of runs in case this entry has fewer.

```
≔Φζ∨⁼§θκ§θ⁰‹κ⌈⌕Ａθ§θ⊖κζ

```

Keep only those runs which are potentially worth reversing, of which there are two sorts: either the first element is the same as that of the run, or the previous run is not the last run of its element.

```
¿ζ

```

If there are any such runs, then:

```
Ｆ⁻Ｅζ⁺⮌…θκ✂θκＬθ¹Ｅυ§κ¹

```

For each run, compute the result of flipping up to that run, but then delete any results seen previously.

```
⊞υ⊞Ｏ⊕ικ

```

Push the new run with the incremented flip count to the search list.

```
Ｉι

```

If there were no such runs, this can only happen when there are no disjoint runs of an element, which means that we've found a solution, so output its flip count.
> 3 votes

# Answer
# JavaScript (ES6),  ~~124~~  109 bytes

Expects a string. Performs a breadth-first search.

```
f=(s,n=N=0,r)=>!/(.)(?!\1).+\1/.test(s)|[...s].some((c,i)=>n&&f((r=c+[r])+s.slice(i+1),n-1))?N:n==N&&f(s,++N)

```

Try it online!

### Commented

```
f = (                   // f is a recursive function taking:
  s,                    //   s = input string
  n =                   //   n = remaining number of iterations
  N = 0,                //   N = total number of iterations
  r                     //   r = reversed prefix, initially undefined
) =>                    //
  !/(.)(?!\1).+\1/      // success if there isn't any character appearing
  .test(s) |            // twice with some other characters in between
  [...s].some((c, i) => // for each character c at position i in s:
    n && f(             //   unless n = 0, do a recursive call:
      (r = c + [r]) +   //     update the reversed prefix
      s.slice(i + 1),   //     append the non-reversed suffix
      n - 1             //     decrement n
    )                   //   end of recursive call
  ) ?                   // end of some(); if truthy:
    N                   //   we've found a solution: return N
  :                     // else:
    n == N              //   if it was the root call of the attempt with
    &&                  //   N iterations:
      f(s, ++N)         //     increment N and try again

```
> 2 votes

# Answer
# C(GCC) ~~218~~ ~~210~~ 203 bytes?

*-8 bytes thanks to @ceilingcat*, *-7 bytes thanks to myself*

```
f(int*x){int*c,*y=x,o=0,h,i,p=0;while(*y){for(c=y;*y==*++c;);while(*y-*++c&&*c);if(*c){if(y-x)for(c=y,p++;*y==*++c;);for(i=0;i+x<c;x[i++]=*--c,*c=h)h=i[y=x];o++;}else for(c=y;*c==*++y;);}return o-p+p%2;}

```

Try it online

This code is based on idea of creating a machine, that always does the right shuffle, or at least after finishing can decide, how it is improvable. For some strange reason, it works. The most effective way to unshuffle the poker chips would be to link two pieces (at one place) of the same value every round, without breaking any. However, this is not always possible (the 10th and 11th test case). When the machine runs into a such situation, where nothing can be linked, it will do a sneaky shuffle that brings a linkable block of numbers on the top. The fact that this machine runs only on one path means it can choose the wrong one, and do more (still less than types of numbers) sneaky shuffles, but the right amount of normal shuffles. My theory is, that every deck can be unshuffled with at most one sneaky shuffle, because every two of these are basically a shift, that can be created by rearranging the previous shuffles. That is, why the output is `o-p+p%1`, where o is the total amount of shuffles and p the amount of sneaky shuffles. But, sadly, I don't have the mathematical tools needed to prove this last theory, so I would be really grateful, if someone could find a counterexample, or correct my naive maths.
> 2 votes

# Answer
# Python, 157 bytes

```
def f(x):
    X=[x,0];n=len(x);m=n//max(x);r=range(1,n)
    while X:
        x,c,*X=X
        if all(x[j]==x[j//m*m]for j in r):return c
        for i in r:X+=[x[i::-1]+x[i+1:],c+1]
```

Attempt This Online!

Note: it is extremely inefficient, but it eventually terminates correctly.
> 1 votes

---
Tags: code-golf, array
---


title: Plot a centered circle

text:
# Question
Title: Plot a centered circle
# Intro

Given radius \\$r\\$, draw a circle in the center of the screen.

Sandbox.

# The Challenge

Here is a simple challenge.

Plot a circle using the formula \\$x^2+y^2=r^2\\$, or any other formula that will plot a circle according to the given parameters.

You may use any units that your language provides, so long as they are well defined and give consistent output.

The circle must have it's center at the center of the canvas, and must have a padding of 5 units or more on all sides.

The circle can have any fill that does not match the outline.

You may have axes in the background of your plot.

The outline of the circle must be solid (no gaps), and it must be visible. Here is an example:

Input can be taken in any acceptable form. (function params, variables, stdin...)

Output can be in the form of a separate window, or an image format.

Standard loopholes and rules apply.

# Example Code (`Java + Processing`)

```
// Modified from the C language example from
// https:// en.wikipedia.org/wiki/Midpoint_circle_algorithm
int r = 70; //radius
void settings() {
  size(2*r+10, 2*r+10);
}

void draw() {
  background(255);
  drawCircle(width/2, height/2, r, 60);
  save("Circle.png");
}

void drawCircle(int x0, int y0, int radius, int angle) {
  int circCol = color(0, 0, 0);
  float limit = radians(angle);
  int x = radius;
  int y = 0;
  int err = 0;

  while (x >= y && atan2(y, x) < limit) {
    set(x0 + x, y0 + y, circCol);
    set(x0 + y, y0 + x, circCol);
    set(x0 - y, y0 + x, circCol);
    set(x0 - x, y0 + y, circCol);
    set(x0 - x, y0 - y, circCol);
    set(x0 - y, y0 - x, circCol);
    set(x0 + y, y0 - x, circCol);
    set(x0 + x, y0 - y, circCol);

    y += 1;
    if (err <= 0) {
      err += 2*y + 1;
    }
    if (err > 0) {
      x -= 1;
      err -= 2*x + 1;
    }
  }
}

```

# Scoring

This is a question. No ascii art.

This is . shortest answer in each language wins.

# Answer
> 11 votes
# Desmos, 1 byte

`r`

Try it on Desmos

Uses the same input method as the other Desmos answer. An unused variable named `r` defaults to drawing a circle with radius r.

# Answer
> 10 votes
# , ~~74~~ ~~70~~ ~~68~~ ~~65~~ 54 bytes

*Edit: -11 bytes thanks to Giuseppe*

```
function(r)plot(r*1i^(1:1e3/99),,"l",l<-c(-r-5,r+5),l)

```

Try it at rdrr.io

I propose 3 possible answers to this challenge in , of decreasing length but with increasing caveats.

My favourite answer (above, using `plot`) is the ~~middle~~ shortest one of the 3. It plots a circle by calculating the complex coordinates of powers of `i`, using 396 points (with a bit of wrap-around). Here's an image of the output from `plot_circle(5)`:

---

For a 'true' circle (rather than an almost-circle with tiny straight-lines connecting the data points), we can use the `curve` function with a formula, but unfortunately we need to draw the positive & negative halves separately, so it ends up longer:

# , ~~86~~ 84 bytes

```
function(r){curve((r^2-x^2)^.5,xli=l<-c(-r-5,r+5),yli=l)
curve(-(r^2-x^2)^.5,add=T)}

```

Try it at rdrr.io

---

~~The shortest (that I can think of)~~ Previously the shortest, but - thanks to Giuseppe now no longer so - is to use the `circles` option of the `symbols` function, for only 56 bytes. However, this has the caveat that the circle symbols are always circular even if the plot is re-sized, and so may no-longer line-up with the y-axis.

# , ~~62~~ ~~58~~ 56 bytes

```
function(r)symbols(x=1,c=r,i=F,xli=l<-c(-r-4,r+6),yli=l)

```

Try it at rdrr.io

# Answer
> 8 votes
# Python 2 & 3, 55 bytes

*-17 bytes thanks to @DigitalTrauma*
*-1 byte thanks to @Sisyphus*
*-2 bytes thanks to @ovs*

```
from turtle import*
def f(r):sety(-r);clear();circle(r)

```

Try it online!

turtle is standard library included in Python 2 & 3. I came up with `turtle` idea as a almost first result in Googling "graphics python".

# Answer
> 7 votes
# LaTeX, 66 bytes

```
\input tikz\def\f#1{~\vfill\centering\tikz\draw circle(#1);\vfill}

```

I consider the "canvas" required by this challenge to be the default text area of a latex page. The code defines a macro `\f` that takes the radius in cm as an argument.

## Example Code

```
\documentclass{article}

\input tikz\def\f#1{~\vfill\centering\tikz\draw circle(#1);\vfill}

\begin{document}
\f{3}
\enddocument

```

Outputs a PDF:

# Answer
> 6 votes
# SageMath, 24 bytes

```
lambda r:circle((0,0),r)

```

Try it online!

### Example

# Answer
> 6 votes
# C (gcc), ~~169~~ ~~166~~ ~~161~~ 160 bytes

Thanks to ceilingcat (x3) for the suggestions! I also changed the newlines in the header to spaces as they seem to work fine as separators (at least in Irfanview) and fixed a bug that got revealed when the array was put on the stack.

Generates an image in PBM format, as it's probably the simplest way to make a bitmap! For some reason, all the online PBM viewers that I tried don't seem to like the output file, but Irfanview and GIMP are fine with it.

```
z;f(r,w){char s[(w=r*2+11)*w+1];float x=s[w*w]=!memset(s,48,w*w);for(;x<7;)s[z=round(sin(x+=1e-5)*r+r+5)+round(cos(x)*r+r+5)*w]=49;printf("P1 %d %d %s",w,w,s);}

```

Try it online!

# Answer
> 5 votes
# T-SQL, 47 bytes

```
SELECT geometry::Point(0,0,0).STBuffer(r)FROM t

```

Input is taken via a pre-existing table *t* with float field *r*, per our IO rules.

Uses SQL geo-spatial functions, displayed in the SQL Management Studio results pane:

# Answer
> 4 votes
# Desmos, ~~12~~ 10 bytes

```
xx+yy=rr
r

```

Desmos it

# Answer
> 4 votes
# Wolfram Language (Mathematica), 16 bytes

```
Graphics@*Circle

```

See Wolfram documentation on Circle

for example here is a circle with center (0,0) and radius r=42

-6 bytes from @LegionMammal978

# Answer
> 4 votes
## JavaScript (ES6), 96 bytes

```
f=
v=>`<svg width=${s=v*2+12} height=${s}><circle r=${v} cx=${v+=6} cy=${v} stroke=#000 fill=none>`
```

```
<input type=number min=1 oninput=o.innerHTML=f(+this.value)><div id=o>
```

Outputs an SVG(HTML5) image, which the snippet displays for you. If HTML5 is acceptable, then for 95 bytes:

```
f=
v=>`<div style="width:${v*=2}px;height:${v}px;margin:6px;border:1px solid;border-radius:100%">`
```

```
<input type=number min=1 oninput=o.innerHTML=f(+this.value)><div id=o>
```

# Answer
> 4 votes
# MATLAB, ~~38~~ 37 bytes

*-1 byte thanks to Tom Carpenter*

```
ezpolar(@(x)r);axis((r+5)*cospi(1:4))

```

Input as variable `r` in workspace.
Output:

# Answer
> 4 votes
# TI-Basic, ~~11~~ ~~8~~ 7 bytes

```
Polar
Input r₁
ZSquare

```

Input is a string, and is stored as a function. This function is shown in polar coordinates, so it shows as a circle.

Output for `"4`:

# Answer
> 4 votes
## \<\>^v, 56 bytes

```
ƒ∆57±∑361i∆90v
v 0Ii(I<   ª <
]      ^
>¶°    ^
>1 æ∑  ^

```

#### Explanation

`ƒ` : toggle turtle visibility
: raise pen
`57`: push 57
`±` : negate
: turtle forward by top of stack
`361`: push 361 (360 + 1)
`i` : pop stack & store in variable `i`
: lower pen
`90`: push 90
`v` : send instruction pointer down
`<` : send instruction pointer left
`ª` : turtle rotate right by top of stack (90)
**start of loop**
`<` : send instruction pointer left
`I` : push value of variable `i`
`(` : decrement top of stack
`i` : pop & store in variable `i`
`I` : push value of variable `i`
`0` : push 0
`v` : send instruction pointer down
`]` : if top of stack is greater than or equal to second element of stack\

* `>` : send instruction pointer right
* : update display
* continue to **continue here**\

Else
`>` : send instruction pointer right
`1`: push 1
`æ` : turn left (top of stack) degrees
: go forward by top of stack
`^` : send instruction pointer up
**continue here**
`^` : send instruction pointer up
`^` : Idem, there to ensure trailing whitespace is not removed
go to **start of loop**

After drawing the circle, the program never halts to prevent the window from closing.

Screenshot below (Python Turtle Graphics is because the program does not set a title to the window and the interpreter is written in Python and uses Turtle for graphics) :

# Answer
> 3 votes
# Red, 74 bytes

-16 bytes thanbks to Aaron Miller!

```
func[r][d: r + 5 view compose/deep[base(2x2 * d)draw[circle(1x1 * d)(r)]]]

```

# Red, 90 bytes

```
func[r][d: r + 5 view compose/deep[base(as-pair d * 2 d * 2)draw[circle(as-pair d d)(r)]]]

```

`f 200`

# Answer
> 3 votes
# Java 8, ~~141~~ 123 bytes

```
import java.awt.*;r->new Frame(){{setSize(2*r+26,2*r+56);show();}public void paint(Graphics g){g.drawOval(13,43,2*r,2*r);}}

```

Output for \\$n=100\\$ (the second picture with added light grey background color is to verify the top padding):

**Explanation:**

```
import java.awt.*;     // Required import for Frame and Graphics
r->                    // Method with integer parameter and Frame return-type
 new Frame(){          //  Create the Frame
   {                   //   In an inner code-block:
     setSize(2*r       //    Set the width to 2 times the radius-input
             +26       //     + 2 times 8 pixels for the frame borders
                       //     + 2 times 5 pixels for the required padding
             2*r       //    Set the height to 2 times the radius-input
             +56);     //     + 2 times 8 pixels for the frame borders
                       //     + 30 pixels for the frame title-bar
                       //     + 2 times 5 pixels for the required padding
     show();}          //    And show the Frame at the end
   public void paint(Graphics g){
                       //   Overwrite its paint method to draw on
     g.drawOval(13,43, //    With 5,5 for the required padding as top-left
                       //    x,y-coordinate of the surrounding rectangle + the same 8+30
                       //    pixels adjustment for the frame and frame title-bar,
         2*r,2*r);}}   //    draw the circle with a size of 2 times the radius-input

```

Note: I cannot use `(r*=2),r,r,r` instead of `2*r,2*r,2*r,2*r` to save (3) bytes, because `r` has to be effectively final inside the inner Frame-class.

# Answer
> 2 votes
# JavaScript (V8), 158 bytes

```
r=>document.write(`<p style="border-radius:50%;border:solid;position:fixed;width:${r*2}px;height:${r*2}px;top:50%;left:50%;transform:translate(-50%,-50%);">`)

```

Try it online!

jsfiddle thanks to @Razetime

* Saved 1 thanks to @Razetime
* Saved 2 using template literals

Writes directly to the HTML a `p` element fixed positioned, centered with border radius 50%

# Answer
> 2 votes
## Shadertoy (GLSL), 142 bytes

```
void mainImage(out vec4 f,in vec2 v){vec2 S=iResolution.xy;vec2 u=v/S-vec2(0.5);u.y/=S.x/S.y;vec4 c;if(abs(length(u)-0.2)<8e-4)c=vec4(1);f=c;}

```

Shadertoy link

Output:

# Answer
> 2 votes
# Red, ~~96~~ ~~92~~ 87 bytes

*Forgot to remove some extra whitespace for -4 bytes.*

*-5 bytes by using shorter type conversions and initializing and using `x` at the same time.*

```
draw to-pair x: r * 9 to-block append"circle "append mold to-pair x / 2 append" "mold r

```

No TIO link because `draw` doesn't seem to be implemented on TIO. However, you can copy this into the Red offline interpreter to output an image.

The first line is for defining a variable to be used for the canvas size. Multiplying by 9 might be a bit overkill, but it ensures enough padding around the circle. I couldn't figure out how to use variables in the block, so the second line builds the draw command bit by bit, essentially building the command `draw {x}x{x} [circle {x / 2}x{x / 2} {r}]`.

Example output for \\$r = 10\\$:

# Answer
> 2 votes
# Red, 59 57 55 51 byte

```
func[r][?(draw 2 * c: 5x5 + r reduce['circle c r])]

```

Try it locally.

-2 bytes thanks to Aaron Miller spotting superfluous `as-pair`.

---

Output for \\$r=50\\$:

# Answer
> 2 votes
# 80186 DOS machine code, ~~76~~ ~~74~~ ~~72~~ 71 bytes

```
00000000: b8 13 00 cd 10 1e 68 00 a0 1f f7 df 8d 6d 02 01  ......h......m..
00000010: fd 31 c0 f7 df e8 20 00 f7 df 97 e8 1a 00 89 eb  .1.... .........
00000020: 39 df e8 0a 00 97 39 fb e8 04 00 75 e6 1f 7c 06  9.....9....u..|.
00000030: 01 fd 8d 6b 03 47 c3 e8 00 00 69 d8 40 01 fe 81  ...k.G....i.@...
00000040: a0 7d f7 df f7 d8 c3                             .}.....

```

A function which expects the radius in `di`. Forces DOS to graphics mode and doesn't bother to clean up.

I am mostly just excited about getting it working, I will hopefully find some ways to optimize.

Translation of the Go version of the Midpoint circle algorithm from Rosetta Code.

* 2 bytes: branch once in `correct` instead of branching twice in the main function
* 2 bytes: reuse flags from `inc` for loop trigger.
* 1 byte: Fall through to `correct` when returning.

#### Commented assembly

```
        ; nasm file.asm -f obj -o file.obj
        [cpu 186]
        global draw_circle
        ; args: di: radius
draw_circle:
        ; switch DOS to graphics mode
        mov     ax, 0x0013
        int     0x10
        ; set ds to point to the screen buffer
        push    ds
        push    0xA000
        pop     ds

        ;  http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm#Go
        ; di => x1
        neg     di
        ; bp => err
        lea     bp, [2 + di]
        add     bp, di
        ; ax => y1
        xor     ax, ax
.loop:
        neg     di
        ; x - x1, y + y1
        ; x + x1, y - y1
        call    set_pixel
        neg     di
        ; swap
        xchg    ax, di
        ; x + y1, y + x1
        ; x - y1, y - x1
        call    set_pixel
        ; ax: x1, di: y1

        ; save err to bx
        mov     bx, bp
        ; check y1
        ; we branch in correct
        cmp     di, bx
        call    correct
        ; swap back
        xchg    ax, di
        ; check x1, using the opposite order
        cmp     bx, di
        call    correct
        ; loop while x1 is negative
        ; the flags will be set from correct
        jnz     .loop
        ; restore ds segment
        pop     ds
        ; uncomment to wait for enter then switch to
        ; standard mode
        ; mov     ah, 0x08
        ; int     0x21
        ; mov     ax, 0x0003
        ; int     0x10
        ; Fallthrough to exit

        ; some helper functions to cut down the copy-paste
correct:
        ; The flags will be set to the comparison before
        ; calling
        jl      .skip
        ; err += 2 * ++di + 1
        add     bp, di
        lea     bp, [bp + di + 3]
        ; ++di
        inc     di
.skip:
        ret

        ; ax: y, di: x
set_pixel:
        ; run twice by semi-recursion
        call    .semirecurse
.semirecurse:
        ; ++byte[x + 160 + (320 * (y + 100))]
        imul    bx, ax, 320
        inc     byte[di + bx + 0x7DA0]
        ; negate both here
        neg     di
        neg     ax
        ret

```

with radius = 50, showing the disgusting exit:

# Answer
> 2 votes
# Python + pygame, 110 bytes

```
r=int(input())
d=display
s=5+r
draw.circle(d.set_mode([s+s]*2),[99]*3,[s]*2,r,1)
d.update()

```

We only use `set_mode` once, so we can pass it as an argument to `draw.circle`.

It's almost impossible to golf in Pygame so this is probably the shortest it can get, although I could change `99` to 9.

Example for 250:

# Answer
> 2 votes
# Desmos, ~~10~~ 12 bytes

```
xx+yy=rr
r=1

```

Desmos it

# Answer
> 1 votes
# Perl 5, 92 bytes

```
$r=$_;
$w=$r*2+11;
$_="P1 $w $w @{[map{($_%$w-$r-5)**2+($_/$w-$r-5)**2<$r**2?1:0}0..$w**2-1]}"

```

Try it online!

Circle with black filling. Put the 92 bytes above into program.pl and run like this:

```
echo 50 | perl -p program.pl > circle.pbm  # radius 50
feh circle.pbm                             # view with feh or other image viewer

```

# Answer
> 1 votes
# PHP, 131 bytes

```
($f=imagecolorallocate)($i=imagecreate($d=10+$argn*2,$d),0,0,0);imageellipse($i,$d/2,$d/2,$d-10,$d-10,$f($i,9,9,9));imagepng($i,a);

```

Try it online!

Actually you cannot run it in online PHP testers because they disable the image functions. Saves the image in a file named "a". One byte could be saved using `imagegd` but I didn't know the "gd" format and couldn't open it to check if it works.

The circle is in very dark grey, but I consider it visible. If you don't, leave a comment and I'll edit, with one byte more `$f($i,99,0,0)` it's much clearer.

with `$f($i,9,9,9)`:

with `$f($i,99,0,0)`:

# Answer
> 1 votes
# HTML + Javascript, 98

## JavaScript: 85, HTML: 13

```
F=r=>{C.width=C.height=r*2+16;c=C.getContext`2d`;c.arc(r+8,r+8,r,0,6.283);c.stroke()}

F(100)
```

```
<canvas id=C>
```

To change r, change `r=100` to `r=/*place your value here*/`.

# Answer
> 1 votes
# Swift, entire iOS app, 152 bytes

`project.pbxproj` not included.

```
import SwiftUI
@main struct A:App{@State var s="1"
var body:some Scene{WindowGroup{VStack{TextField("",text:$s)
Circle().frame(width:.init(Int(s)!))}}}}

```

The unit for the radius is 0.5pt, which is either 1px or 1.5px depending on the device. The app crashes if you type something that isn't an integer.

Preview, with a radius of 50pt:

### Ungolfed

```
import SwiftUI

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

struct ContentView: View {
    @State private var text = "1"

    var body: some View {
        VStack {
            TextField("", text: $text)

            Circle()
                .frame(width: CGFloat(Int(text)!))
        }
    }
}

```

# Answer
> 1 votes
## ZX Spectrum BASIC, 1, 3 or 6 bytes

Nothing beats BASIC computers with bitmap graphics that consider a case of honour to implement the built in CIRCLE command...

`CIRCLE x,y,r`

The command takes just one byte (though it is printed as the whole word), depending on what and how do you count the size, it can be 1 byte (the command itself), 3 bytes (the command and obligatory commas separating the articles; note that the space is only visual), 6 bytes (the command, commas and three already defined variables (or `PI`)).

# Answer
> 1 votes
## PostScript, 69 bytes

```
currentpagedevice/PageSize get{2 div}forall
3 2 roll
0 360 arc stroke

```

Pass the radius on the command line:

```
gs -c 150 -- circle.ps

```

Displays output in a window, which then immediately closes! Add `showpage` for a persistent window. Centering the output took more bytes than I had hoped...

# Answer
> 1 votes
# C (gcc), ~~132~~ 128 bytes

*-4 bytes thanks to @ceilingcat*

```
main(r,w,i,j){scanf("%d",&r);i=w=r+9;for(printf("P5\n%d%1$d\n1\n",2*w);i--+w;)for(j=w;j--+w;)putchar(abs((i*i+j*j)*2-r*r)<2*r);}

```

Try it online!

Outputs a PGM image. A unit corresponds to `sqrt(2)` pixels.

# Answer
> 1 votes
## Applesoft BASIC, 106 bytes

```
0INPUTR
1HGR
2HCOLOR=3
3D=0
4HPLOTR*COS(D)+140,R*SIN(D)+96TOR*COS(D+.1)+140,R*SIN(D+.1)+96
5D=D+0.1
6GOTO4

```

# Answer
> 0 votes
# Desmos, 3 bytes

```
r=1

```

Simply entering `r`, in my concern, doesn't work, but entering `r=0` automatically makes it a slider.

r=0 doesn't create a circle. Sorry about that.

# Answer
> 0 votes
# Robocompass, 16 bytes

```
arc(0,0,a,0,360)

```

Where you have to define a before that as input.

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


title: Longest pristine(ish) codepoint run

text:
# Question
Title: Longest pristine(ish) codepoint run
Your challenge is to create the longest run of characters with incrementing Unicode codepoints in a pristine program as you can. To keep things simple, I'll abridge the definition for this challenge to be "any program which produces no errors but will error if any one character is removed".

Let's define a codepoint run as any contiguous substring of N characters, where `1 <= N <= program length`, where the Unicode/UTF-8 codepoints increment by 1 for each character.

For example: `abc`, `<=>`, `{|`, and `ƐƑƒƓƔ` are all codepoint runs.

Your program (must be a standalone program) doesn't have to be purely a codepoint run. Instead, **its score will be the length in *characters* of the longest codepoint run in its source code**. A program `dabc`'s score would be 3.

**Note that your program does not need to actually output anything, as long as it does not error.**

* Compiler warnings do not count as errors
* Your program does not need to (but still can) error if more than 1 contiguous character is removed
* Your program may take input only if the contents of the input do not affect whether or not the program errors
* Any code which is not part of the longest codepoint run is ignored in the scoring
* Highest score, as in code golf, is per-language

# Answer
> 6 votes
# Python 3, run of 1,114,111

```
#coding:utf
assert len(open(__file__).read(1061))==1061
"""

 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂăĄąĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıĲĳĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňŉŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃǄǅǆǇǈǉǊǋǌǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰǱǲǳǴǵǶǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑȒȓȔȕȖȗȘșȚțȜȝȞȟȠȡȢȣȤȥȦȧȨȩȪȫȬȭȮȯȰȱȲȳȴȵȶȷȸȹȺȻȼȽȾȿɀɁɂɃɄɅɆɇɈɉɊɋɌɍɎɏɐɑɒɓɔɕɖɗɘəɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼʽʾʿˀˁ˂˃˄˅ˆˇˈˉˊˋˌˍˎˏːˑ˒˓˔˕˖˗˘˙˚˛˜˝˞˟ˠˡˢˣˤ˥˦˧˨˩˪˫ˬ˭ˮ˯˰˱˲˳˴˵˶˷˸˹˺˻˼˽˾˿̴̵̶̷̸̡̢̧̨̛̖̗̘̙̜̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̱̲̳̹̺̻̼͇͈͉͍͎͓͔͕͖͙͚̀́̂̃̄̅̆̇̈̉̊̋̌̍̎̏̐̑̒̓̔̽̾̿̀́͂̓̈́͆͊͋͌͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮͯ̕̚͘͜͟͢͝͞͠͡ͅͰͱͲͳʹ͵Ͷͷ͸͹ͺͻͼͽ;Ϳ΀΁΂΃΄΅Ά·ΈΉΊ΋Ό΍ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ΢ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώϏϐϑϒϓϔϕϖϗϘϙϚϛϜϝϞϟϠϡϢϣϤϥϦϧ"""

```

Try it online!

The triple-quoted contains the entire Unicode range except for the null byte `\0` which terminates a program. (Thanks to Chas Brown for suggesting triple-quoting, which allowed 13 more characters.) The TIO link uses a shortened version; assume that the number 1061 is replaced with the code length.

The program opens itself and checks that it has the appropriate length, which guards against any deletion. No one-character deletion can disable this logic in the code. Lowering either the number of characters read or the number checked for equality will make the assertion fail.

I'm not totally sure if all Unicode characters except '\0' are valid in Python code, and I haven't been able to test it. Maybe this is system dependent. Please let me know if this fails at some point.

We can also do this without reading the file:

```
s="""

 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂăĄąĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıĲĳĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňŉŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃǄǅǆǇǈǉǊǋǌǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰǱǲǳǴǵǶǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑȒȓȔȕȖȗȘșȚțȜȝȞȟȠȡȢȣȤȥȦȧȨȩȪȫȬȭȮȯȰȱȲȳȴȵȶȷȸȹȺȻȼȽȾȿɀɁɂɃɄɅɆɇɈɉɊɋɌɍɎɏɐɑɒɓɔɕɖɗɘəɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰʱʲʳʴʵʶʷʸʹʺʻʼʽʾʿˀˁ˂˃˄˅ˆˇˈˉˊˋˌˍˎˏːˑ˒˓˔˕˖˗˘˙˚˛˜˝˞˟ˠˡˢˣˤ˥˦˧˨˩˪˫ˬ˭ˮ˯˰˱˲˳˴˵˶˷˸˹˺˻˼˽˾˿̴̵̶̷̸̡̢̧̨̛̖̗̘̙̜̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̱̲̳̹̺̻̼͇͈͉͍͎͓͔͕͖͙͚̀́̂̃̄̅̆̇̈̉̊̋̌̍̎̏̐̑̒̓̔̽̾̿̀́͂̓̈́͆͊͋͌͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮͯ̕̚͘͜͟͢͝͞͠͡ͅͰͱͲͳʹ͵Ͷͷ͸͹ͺͻͼͽ;Ϳ΀΁΂΃΄΅Ά·ΈΉΊ΋Ό΍ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ΢ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώϏϐϑϒϓϔϕϖϗϘϙϚϛϜϝϞϟϠϡϢϣϤϥϦϧ"""
assert len(s)==999

```

Try it online!

There isn't a way to delete a character from the assertion line while keeping it syntactically valid and preserving the length number.

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), Score: 1114076

```
var s=@"Insert all characters from character 36 then on";if(s.Length!=1114076)throw new Exception();

```

Try it online!

# Answer
> 1 votes
# x86 machine code, score: 1,114,112

```
E9 81 F7 42 00 00 01 02 ... F4 8E BF BF C3

```

In assembly:

```
main:
    jmp $+4388742 # i.e. to the end
    .byte 0,1,...,0xF4,0x8F,0xBF,0xBF
end:
    ret

```

The code that is executed is just a relative jump followed by a return. All the unicode codepoints are in between.

If the jump itself or any of the first three bytes of its offset are deleted, then the unicode codepoints are executed as code until it crashes. If any byte after that is removed, then it jumps past the end of the program and eventually crashes.

---
Tags: code-bowling, pristine-programming
---