# Question
Title: Fastest way to perform the equivalent of an if-statement in x86 assembly
The task is simple: Create an if-statement from scratch in x86 assembly that runs in as few clock-cycles as possible.

* Must be x86 assembly.
* Can't use any of the *conditional* jump/branch instructions (e.g. `je`, `jne`, `jz`, `jg`, `jge`, `jl`, `jle`).
* **Can** use `jmp` to jump to existing blocks of code.
* **Can** use `cmp` if necessary.
* Can't call any external libraries or functions.
* Can't use `call`.
* Free to use any of the other available instructions in the Intel docs.
* No C.
* Any of the ~7 Intel Core architectures are acceptable (listed on page 10). Ideally Nehalem (Intel Core i7).
* The `if` statement needs to check arbitrary conditions. Basically replicating the functionality of any one of the `je`, `jge`, etc. *conditional* jumps.

The winning answer is one that uses the fewest clock cycles possible. That is, it can have the most operations per second. Approximate clock cycle summaries are here: http://www.agner.org/optimize/instruction\_tables.pdf. Calculating clock cycles can happen after the answer is posted.

# Answer
And then I realised that we can be faster, and use no additional registers:

```
cmp eax, ebx
mov eax, offset false_case
mov ebx, offset true_case
cmove eax, ebx ;or cmovb, etc.
jmp eax
```
> 4 votes

# Answer
```
xor ecx, ecx
mov edx, 1
cmp eax, ebx
cmove ecx, edx ;or cmovb, etc.
jmp [false + ecx*4]

false dd offset false_case
true  dd offset true_case
```

Accepts eax and ebx for the comparison.
Replace the cmov with the corresponding check to perform.
> 2 votes

---
Tags: fastest-algorithm, function, assembly
---


# Question
Title: Addition-Subtraction of Numbers Within String
Take a string as an input, and perform addition/subtraction of all the digits in the string and output the sum of those operations as the result.

## Rules

* The digits in the string are read from left to right
* If a digit (n) is odd, perform addition with the next digit (n + n1)
* If a digit (n) is even, perform subtraction with the next digit (n - n1)
* If you've reached the last digit in the string, perform the operation with the first digit in the string
* Output will be the sum of all the resulting values
* If there is only one digit in the string, perform the operation with itself (n+n or n-n)
* If there are no digits in the string, output is 0

## Example

```
Input: r5e6o9mm!/3708dvc
Process: (5+6) + (6-9) + (9+3) + (3+7) + (7+0) + (0-8) + (8-5)
Output: 32

```

## Notes

* Either function or full program is accepted
* Maximum input length would depend on your language's limit for a string input
* No restrictions on character input, but only half-width digits count towards the output
* Fewest bytes wins

# Answer
> 6 votes
# Jelly, ~~17 15~~ 12 bytes

```
fØDV€ḂT‘ịƲSḤ

```

Try it online!

Try test cases.

The program keeps only the digits that follow an odd digit then computes twice the sum.

```
fØDV€ḂT‘ịƲSḤ
f                   Remove anything that isn't...
 ØD                 a digit.
   V€               Cast each digit to an integer
         Ʋ          Monad:
     Ḃ              Parity of each digit.
      T             Indices of truthy elements (odd digits).
       ‘            Increment.
        ị           Index into list of digits.
                    Wraps to beginning and if there are no digits this returns 0.
          S         Sum.
           Ḥ        Double.

```

# Answer
> 3 votes
# K (oK), ~~47~~ ~~43~~ ~~40~~ 31 bytes

**Solution:**

```
{+/(1_x,*x)*2*2!x^:(x-:48)^!10}

```

Try it online!

**Explanation:**

Remove everything from string that isn't a number (whilst also converting), modulo 2, multiply by 2, multiply with x rotated by 1, and sum up.

```
{+/(1_x,*x)*2*2!x^:(x-:48)^!10} / solution
{                             } / lambda taking implicit x
                           !10  / range 0..10
                          ^     / except
                   (     )      / do this together
                    x-:48       / subtract 48 from x (type fudging char ascii value -> ints), save back into x
                x^:             / x except right, and save back to x
              2!                / modulo 2
            2*                  / multiply by 2
           *                    / multiply by
   (      )                     / do this together
        *x                      / first element of x
       ,                        / append to
      x                         / x
    1_                          / drop first (ie rotate everything by 1)
 +/                             / sum, add (+) over (/)

```

**Naive solution:**

Remove everything from string that isn't a number (whilst also converting), take 2-item sliding window, figure out whether they are odd or even, apply add/subtract as appropriate, then sum up.

```
{+/((-;+)2!x).'2':(1+#x)#x^:(x-:48)^!10}

```

Try it online!

**Notes:**

* **-4 bytes** thanks to @ngn due to a smarter way of filtering the input
* **-3 bytes** by using sliding window rather than reshape
* **-9 bytes** porting ngn's solution (non-naive approach)

# Answer
> 3 votes
# Python 2, 86 bytes

```
k=[int(a)for a in input()if'/'<a<':']
print sum(a-(-1)**a*b for a,b in zip(k,k[1:]+k))

```

Try it online!

# Answer
> 2 votes
# 05AB1E, ~~12~~ 9 bytes

Saves 1 byte over the naive method by utilizing dylnan's parity trick
Saved 3 bytes thanks to *Mr. Xcoder*

```
þDÁ€ÉÏSO·

```

Try it online!

**Explanation**

```
þ              # push only digits of input
 D             # duplicate
  Á            # rotate right
   €É          # get the parity of each
     Ï         # keep only true items
      SO       # calculate digit-sum
        ·      # double

```

# Answer
> 2 votes
# Perl 6, 41 bytes

```
{2*sum rotate($!=.comb(/\d/))Z*(@$! X%2)}

```

Try it online!

Uses the same logic as dylnan's Jelly answer. This sums only digits that follow an odd number and then multiplies by 2.

# Answer
> 2 votes
# MATL, ~~18~~ 17 bytes

```
t4Y2m)!Ut1YSof)sE

```

Try it online!

*(-1 byte thanks to Luis Mendo/Giuseppe/both!)*

Explanation:

```
     % Implicit input
 t   % duplicate input
     % stack: ['r5e6o9mm!/3708dvc' 'r5e6o9mm!/3708dvc']
 4Y2 % push inbuilt literal, characters '0':'9'
     % stack: ['r5e6o9mm!/3708dvc' 'r5e6o9mm!/3708dvc' '0123456789']
 m)  % extract only characters from input that belong to '0':'9'
     % stack: ['5693708']
 !U  % transpose and convert each value from string to number
     % stack: [5 6 9 3 7 0 8]
 t   % duplicate that
 1YS % circular shift by 1
     % stack: [[5 6 9 3 7 0 8] [8 5 6 9 3 7 0]]
 o   % parity check - 1 for odd, 0 for even
     % stack: [[5 6 9 3 7 0 8] [0 1 0 1 1 1 0]]
 f   % find non-zero value indices in last array
     % stack: [[5 6 9 3 7 0 8] [2 4 5 6]]
 )   % index at those places in the first array
 s   % sum
 E   % multiply by 2
     % (implicit) convert to string and display

```

The basic idea is that numbers that follow even numbers can be ignored, while those that follow odd numbers are doubled - and the final result is the sum of those doubled values.

I didn't think `f` after the parity check `o` would be necessary, but for some reason MATL doesn't see the array of 0's and 1's that result from the `o` as a logical array, instead takes them as numerical indices and indexes into positions `1` and `end`.

# Answer
> 2 votes
# Powershell, ~~80~~ ~~78~~ 76 bytes

```
($d="$args"-split'\D*'-ne'')+$d[0]|?{$p-match'[13579]';$p=$_}|%{$s+=2*$_};$s

```

-2 bytes thanks Neil with Retina solution

-2 bytes thanks AdmBorkBork

Test script:

```
$f = {
($d="$args"-split'\D*'-ne'')+$d[0]|?{$p-match'[13579]';$p=$_}|%{$s+=2*$_};$s
}

&$f 'r5e6o9mm!/3708dvc'

```

## Explanation

First of all: it sould add 2\*n if previous digit is odd, and 0 if a previous digit is even.

```
($d="$args"-split'\D*'-ne'')+ # let $d is array contains digits only, each element is a digit
$d[0]|                        # apend first digit to the end of the array
?{                            # where for each digit
    $p-match'[13579]'         # predicate is 'previous digit is odd' (it is false on the first iteration because $p is null)
    $p=$_                     # let previous digit is current
}|
%{                            # for each digit matched to the predicate
    $s+=2*$_                  # add current digit multiply 2 to $s.
}
$s                            # return sum

```

---

## Extra, 99 bytes

Inspired by @Neil. Regex match digits with 'previous digit is odd' only. `Matches` is an automatic variable.

```
param($d)$d+($d-match'\d')+$Matches[0]|sls '(?<=[13579]\D*)\d'-a|%{$_.Matches.Value|%{$s+=2*$_}};$s

```

# Answer
> 2 votes
# K (ngn/k), 33 bytes

```
{+/(1_x,*x)*2*2!x:-48+x^x^,/$!10}

```

Try it online!

`{` `}` is a function with argument `x`

`!10` is the list `0 1 ... 9`

`$` convert to strings

`,/` concatenate

`x^` means `x` without what's on the right

`x^x^` means `x` intersected with what's on the right, i.e. keep only the digits from `x`

`-48+` subtract `48`, which is the ASCII code of `"0"`

`x:` assign to `x`

`2!` mod 2

`2*` multiplied by 2

`1_x,*x` is one drop of: `x` followed by the first of `x`; i.e. `x` rotated to the left by one step

`+/` sum

# Answer
> 2 votes
# Japt (v2.0a0), ~~25~~ 19 bytes

<sup>*-6 bytes thanks to Shaggy.*</sup>

```
kè\D
íÈ°*2*Y°u}Ué)x

```

Try it here.

It works with no digits this time! Input is a list of characters.

# Answer
> 1 votes
# Retina, 37 bytes

```
(\d).*
$&$1
L$`(?<=[13579]\D*).
2**
_

```

Try it online! Explanation:

```
(\d).*
$&$1

```

Append a duplicate of the first digit.

```
L$`(?<=[13579]\D*).

```

Match anything whose first previous digit is odd.

```
2**

```

Convert all the matches to unary and double them. (Non-digits are treated as zero.)

```
_

```

Take the sum. If there were no matches, then this produces zero as required.

The best I could do in Retina 0.8.2 was 44 bytes:

```
[^\d]

(.).*
$&$1
(?<![13579]).

.
$*
.
..
.

```

Try it online! Explanation:

```
[^\d]

```

Delete non-digits.

```
(.).*
$&$1

```

Append a copy of the first digit.

```
(?<![13579]).

```

Delete digits that do not follow an odd digit.

```
.
$*

```

Convert to unary.

```
.
..

```

Double them.

```
.

```

Take the sum.

# Answer
> 1 votes
# JavaScript (ES6), 56 bytes

Takes input as an array of characters.

```
s=>s.map(c=>1/c?r+=p*(p=c*2&2,n=n||c,c):0,n=p=r=0)|r+p*n

```

Try it online!

### Commented

```
s =>                     // given the input array s[]
  s.map(c =>             // for each character c in s[]:
    1 / c ?              //   if c is a digit:
      r +=               //     update r:
        p * (            //       p = either 0 or 2 (always 0 on the 1st iteration)
          p = c * 2 & 2, //       p = 0 if c is even, 2 if c is odd
          n = n || c,    //       if n is still equal to 0 (as an integer), set it to c
          c              //       compute p * c
        )                //     add the result to r
    :                    //   else:
      0,                 //     do nothing
    n = p = r = 0        //   n = first digit, p = previous digit, r = result
  )                      // end of map()
  | r + p * n            // compute the last operation with the 1st digit and add it to r

```

# Answer
> 1 votes
# , 58 bytes

```
function(x,y=strtoi(x[x%in%0:9]))sum(c(y[-1],y[1])*y%%2*2)

```

Try it online!

* using dylnan's parity trick
* -8 bytes accepting vector of characters instead of strings
* -3 byte thanks to @Giuseppe

# Answer
> 1 votes
# Jelly, 15 bytes

```
fØDV€1ịṭƊ+_Ḃ?ƝS

```

Try it online!

# Answer
> 1 votes
# JavaScript (Node.js), 85 84 83 82 bytes

-1 bytes thanks to ovs

```
s=>(s.match(/\d/g)||[]).reduce((r,n,i,a)=>r+(+n)+a[a[++i]!=null?i:0]*-(1-n%2*2),0)

```

Try it online!

Takes the string input, finds the digits as an array of characters or returns empty array if none found, and then uses type coercion to ensure the values are added/subtracted correctly. The forward lookup preincrements the index and uses a null check for brevity, and then the final part checks whether number is odd or even to then force addition or subtraction ( + and - is -, etc)

# Answer
> 0 votes
# Julia 0.6, ~~77~~ 69 bytes

```
s->(s=s.-'0';s=s[0.<=s.<=9];endof(s)>0?sum(2(s%2).*[s[2:end];s[]]):0)

```

Try it online!

# Answer
> 0 votes
## Perl 5, 48 bytes

```
$;=$;[++$-%@;],$\+=$_%2?$_+$;:$_-$;for@;=/\d/g}{

```

Try it online!

I quite like how cryptic this looks, but it's a pretty straightforward loop around all the numbers in the string.

# Answer
> 0 votes
### C Sharp 180 bytes

This isn't very good golfing, lol.

```
s=>{var q=new Queue<int>(s.Where(Char.IsNumber).Select(n=>n-48));q.Enqueue(q.First());int t,o=0;o=q.Dequeue();try{while(true){t+=o+(o%2==0?-1:1)*(o=q.Dequeue());}}catch{return t;}}

```

Ungolfed :

```
var q = new Queue<int>(s.Where(Char.IsNumber).Select(n=>n-48));
int t,o=0;

q.Enqueue(q.First());
o=q.Dequeue();

try{
    while(true){
        t += o + (o%2==0?-1:1) * (o=q.Dequeue());
    }
}
catch {
    return t;
}

```

# Answer
> 0 votes
# Stax, 14 bytes

```
ÿ←«4é■≥B▬ê→█T♥

```

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

```
Vd|&    filter out non-digits
c|(\    zip into pairs after rotating right
F       for each digit pair
  B2%s  first-of-pair % 2, then swap top two stack elements
  eH*   eval digit as integer, double, then multiply
  +     add to running total

```

Run this one

# Answer
> 0 votes
# JavaScript (ES6), 52 bytes

```
s=>s.filter(t=>1/t&&~(a+=u*t,u=t%2),a=u=0)[0]*u+a<<1

```

Expects input as an array of characters. Caveat: Due to use of bit-shifting, the output has an upper bound of `2^31-1`

Try it online!

# Explanation

Essentially doubles the sum of the digits following odd values.

```
s => s.filter(             // filter to preserve the first digit
    t =>
        1/t &&             // short-circuits if NaN
        ~(                 // coerce to truthy value
            a += u * t,    // adds value only if previous digit is odd
            u = t%2        // store parity of current digit
        ),
    a = u = 0
)[0]                       // first digit
* u + a
<< 1                       // bit-shift to multiply by 2 (also coerces a NaN resulting from a string devoid of digits to 0)

```

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


title: Spoonerise words... in Finnish

text:
# Question
Title: Spoonerise words... in Finnish
*This challenge is based on, and contains test cases from, a programming course I took at Aalto University. The material is used with permission.*

Two and a half years ago there was a challenge about spoonerisms in English. However, in Finnish spoonerisms are much more complicated.

## Spoonerisms in Finnish

In Finnish, the vowels are `aeiouyäö` and the consonants are `bcdfghjklmnpqrstvwxz`. (`å` is technically part of Finnish, but is not considered here.)

The most basic spoonerisms only take the first vowel of each word, and any consonants preceding them, and exchange the parts:

```
**he**nri **ko**ntinen -> **ko**nri **he**ntinen
**ta**rja **ha**lonen -> **ha**rja **ta**lonen
**fra**kki **ko**ntti -> **ko**kki **fra**ntti
**o**vi **ke**llo -> **ke**vi **o**llo
```

### Long vowels

Some words contain two of the same consecutive vowel. In those cases, the vowel pair must be swapped with the other word's first vowel, shortening or lengthening vowels to keep the length same.

```
**haa**mu **ko**ntti -> **koo**mu **ha**ntti
**ki**sko **kaa**ppi -> **ka**sko **kii**ppi
```

In the case of two *different* consecutive vowels this does not apply:

```
**ha**uva **ko**ntti -> **ko**uva **ha**ntti
**pu**oskari **ko**ntti -> **ko**oskari **pu**ntti
```

Three or more of the same consecutive letter will **not** appear in the input.

### Vowel harmony

Finnish has this lovely thing called vowel harmony. Basically, it means that the *back vowels* `aou` and *front vowels* `äöy` should not appear in the same word.

When swapping front or back vowels into a word, all vowels of the other kind in the rest of the word should be changed to match the new beginning of the word (`a <-> ä`, `o <-> ö`, `u <-> y`):

```
*y*h*ä* **ko**ntti -> **ko***u*h*a* ntti
**ha***u*v*a* **lää**h*ä*tt*ää* -> *y*v*ä* **haa**h*a*tt*aa*
```

`e` and `i` are neutral and may appear with all other letters; swapping them into a word *must not* cause changes to the rest of the word.

### Special cases

Vowel harmony does not apply to some words, including many loan words and compound words. These cases are not required to be handled "correctly".

## Challenge

Given two words, output the words spoonerised.

The input words will only contain the characters `a-z` and `äö`. You may choose to use uppercase or lowercase, but your choice must be consistent between both words and input/output.

I/O may be done in any convenient format. (Words should be considered strings or arrays of characters.)

This is , so the shortest solution in bytes wins.

## Test cases

```
henri kontinen -> konri hentinen
tarja halonen -> harja talonen
frakki kontti -> kokki frantti
ovi kello -> kevi ollo
haamu kontti -> koomu hantti
hauva kontti -> kouva hantti
puoskari kontti -> kooskari puntti
köyhä kontti -> kouha köntti
hauva läähättää -> läyvä haahattaa
frakki stressi -> strekki frassi
äyskäri kontti -> kouskari äntti
hattu sfääri -> sfätty haari
ovi silmä -> sivi olma
haamu prätkä -> präämy hatka
puoskari sfääri -> sfäöskäri puuri
puoskari äyskäri -> äöskäri puuskari
uimapuku hajoa -> haimapuku ujoa
ihme baletti -> bahme iletti
uhka lima -> lihka uma
osuma makkara -> masuma okkara
makkara fakta -> fakkara makta
lapsi laiva -> lapsi laiva
firma hajoa -> harma fijoa
dimensio bitti -> bimensio ditti
flamingo joustava -> jomingo flaustava
globaali latomo -> labaali glotomo
trilogia fakta -> falogia trikta
printti maksa -> mantti priksa
riisi bitti -> biisi ritti
sini riisi -> rini siisi
aarre nyrkki -> nyyrre arkki
laavu laki -> laavu laki
kliininen parveke -> paaninen klirveke
priimus kahvi -> kaamus prihvi
spriinen lasta -> laanen sprista
kliimaksi mammona -> maamaksi klimmona
hylky hupsu -> hulku hypsy
kehys fiksu -> fihys keksu
levy huhu -> huvu lehu
tiheys guru -> guheus tiru
nyrkki heiluri -> herkki nyilyri
latomo hajoa -> hatomo lajoa
prisma lehti -> lesma prihti
viina baletti -> baana viletti
```

# Answer
# JavaScript (ES6), ~~196~~ 175 bytes

Takes the words as two strings in currying syntax `(a)(b)`. Returns an array of two arrays of characters.

```
a=>b=>[(e=/(.*?)([eiäaöoyu])(\2?)(.*)/,g=(a,[,c,v])=>[...c+v+(a[3]&&v)+a[4]].map(c=>(j=e.search(v),i=e.search(c))>9&j>9?e[i&~1|j&1]:c))(a=e.exec(a),b=e.exec(b),e+=e),g(b,a)]

```

Try it online!

### How?

Each input word is passed through the regular expression **e**, which has 4 capturing groups:

```
e = /(.*?)([eiäaöoyu])(\2?)(.*)/    1: leading consonants (or empty)
     [ 1 ][     2    ][ 3 ][ 4]     2: first vowel
                                    3: doubled first vowel (or empty)
                                    4: all remaining characters

```

The helper function **g()** takes all capturing groups of the word to be updated as **a\[ \]** and the first and second capturing groups of the other word as **c** and **v**.

We apply basic spoonerism and take care of long vowels with:

```
c + v + (a[3] && v) + a[4]

```

To apply vowel harmony, we first coerce the regular expression **e** to a string by adding it to itself, which gives:

```
e = "/(.*?)([eiäaöoyu])(\2?)(.*)//(.*?)([eiäaöoyu])(\2?)(.*)/"
     ^^^^^^^^^^^^^^^^
     0123456789ABCDEF (position as hexa)

```

Vowels that need to be harmonized have a position greater than 9 in the resulting string. Furthermore, the expression was arranged in such a way that front vowels ***äöy*** are located at even positions, while back vowels ***aou*** are located at odd positions, next to their counterparts.

Hence the following translation formula which is applied to each character **c** of the output word:

```
(j = e.search(v), i = e.search(c)) > 9 & j > 9 ? e[i & ~1 | j & 1] : c

```
> 9 votes

# Answer
# Python 3, ~~235~~ ~~231~~ ~~225~~ ~~221~~ ~~217~~ 215 bytes

```
import re
S=F,B='äöy','aou'
def f(a,b,C=1):
 e,r,Q,W=re.findall(fr' ?(.*?([ei{B+F}]))(\2)?(\w*)'*2,a+' '+b)[0][2:6]
 for c in zip(*S*(W in B)+(B,F)*(W in F)):r=r.replace(*c)
 return[Q+W*len(e)+r]+(C and f(b,a,[]))

```

Try it online!

---

Saved

* -2 bytes, thanks to Lynn
* -4 bytes, thanks to Zacharý
> 4 votes

# Answer
# Pyth, 84 bytes

```
.b++hY*W@N2JhtY2XW}JeA@DJc2"aouäöy"eNGH_Bmth:d:"^([^A*)([A)(\\2)*(.+)"\A"aeiouyäö]"4

```

Try it online. Test suite.

Proving that it's not *that* hard in golf languages. A stack-based language might do even better.

Pyth uses ISO-8859-1 by default, so `äö` are one byte each.

### Explanation

* `Q`, containing the input pair of words, is appended implicitly.
* `m`: map each word `d` in the input to:
    + `:"^([^A*)([A)(\\2)*(.+)"\A"aeiouyäö]"`: replace `A` with `aeiouyäö]` in the string to get the regex `^([^aeiouyäö]*)([aeiouyäö])(\2)*(.+)`.
    + `:d`: find all matches and return their capturing groups.
    + `h`: take the first (and only) match.
    + `t`: drop the first group containing the entire match.
* `_B`: pair with reverse to get `[[first, second], [second, first]]`.
* `.b`: map each pair of words `N, Y` in that to:
    + `hY`: take the beginning consonants of the second word.
    + `@N2`: take the long first vowel of the first word, or `None`.
    + `htY`: take the first vowel of the second word.
    + `J`: save that in `J`.
    + `*W``2`: if there was a long vowel, duplicate the second word's vowel.
    + `+`: append that to the consonants.
    + `c2"aouäöy"`: split `aouäöy` in two to get `["aou", "äöy"]`.
    + `@DJ`: sort the pair by intersection with the first vowel of the second word. This gets the half with the second word's first vowel in the end of the pair.
    + `A`: save the pair to `G, H`.
    + `e`: take the second half.
    + `}J`: see if the first vowel of the second word is in the second half.
    + `XW``eNGH`: if it was, map `G` to `H` in the suffix of the first word, otherwise keep the suffix as-is.
    + `+`: append the suffix.
> 0 votes

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


# Question
Title: Calculate the sum of all odd digits of pi in range
# Introduction

In the not so distant future with the AI revolution, we will need a way to solve their captchas to prove we're not humans.

This challenge was inspired by CommitStrip.

# Challenge

One such captcha is the challenge of calculating the sum of all odd digits of Pi from digit 1 to digit n, including the first digit, being 3.

### Output

* The **calculated sum** of all odd digits in the range 1 to n.

# Rules

* All the digits of pi must be calculated by your program at runtime, how you implement that is up to you.
* Hard-coded constants of pi are not allowed.
* This is , so shortest bytes win.

# Example

If n = 6, we must find the sum of the odd digits in `[3, 1, 4, 1, 5, 9]` meaning an output of `19`

# Other

Since this questions keeps getting marked as a duplicate of this, allow me to explain how this is different.

This question asks for the sum of a range of numbers, not finding the nth decimal.

# Answer
# Husk, 7 bytes

As you can see here1 the following program, does indeed compute all the digits itself:

```
Σf%2↑İπ

```

Try it online!

### Explanation

```
Σf%2↑İπ  -- implicit input N, eg: 8
     İπ  -- compute all digits of pi: [3,1,4,1,5,9,2,6,5,3,...
    ↑    -- take N: [3,1,4,1,5,9,2,6]
 f%2     -- filter out even ones: [3,1,1,5,9]
Σ        -- sum: 19

```

1: This is a link to the Haskell code which is generated by Husk, in case you're lost (it's quite long) just search for `func_intseq 'π'`..
> 0 votes

# Answer
# Python3, 346 bytes

Based on a recursive implementation of the Chudnovsky algorithm, one of the fastest algorithms to estimate pi. For each iteration, roughly 14 digits are estimated (take a look here for further details).

```
def f(n):import decimal as d;d.getcontext().prec=n+10;q=lambda n,k=6,m=1,l=13591409,x=1,i=1:(d.Decimal(((k**3-16*k)*m//i**3)*(l+545140134))/(x*-262537412640768000)+q(n,k+12,(k**3-16*k)*m//i**3,l+545140134,x*-262537412640768000,i+1)if i<n else 13591409);return sum([ord(i)%2 and int(i)for i in str(426880*d.Decimal(10005).sqrt()/q(n//14+1))[:n+1]])

```

Ungolfed version

```
def f(n):
    import decimal as d
    d.getcontext().prec = n + 10
    q=lambda n, k=6, m=1, l=13591409, x=1, i=1:\
        (d.Decimal(((k ** 3 - 16 * k) * m // i**3) * (l + 545140134)) / (x * -262537412640768000) +
         q(n, k+12, (k ** 3 - 16 * k) * m // i**3, l + 545140134, x * -262537412640768000, i+1)if i < n else 13591409)
    return sum([ord(i) % 2 and int(i)for i in
                str(426880 * d.Decimal(10005).sqrt() / q(n // 14+1))[:n + 1]])

```

Function `q` computes the value of `S`(see the reference), than it is used to divide the term `426880 * d.Decimal(10005).sqrt()` and get the value of the approximation of pi. The precision is controlled by setting the value of `d.getcontext().prec`.

A a little bit longer (372 bytes), more golfed but all-in-one version:

```
f=lambda n,k=6,m=1,l=13591409,x=1,i=0:not i and(exec('global d;import decimal as d;d.getcontext().prec=%d+10'%n)or sum([ord(i)%2 and int(i)for i in str(426880*d.Decimal(10005).sqrt()/f(n//14+1,k,m,l,x,1))[:n+1]]))or i<n and d.Decimal(((k**3-16*k)*m//i**3)*(l+545140134))/(x*-262537412640768000)+f(n,k+12,(k**3-16*k)*m//i**3,l+545140134,x*-262537412640768000,i+1)or 13591409

```

Thanks to O.O.Balance to push me to go deeper into this challenge: it was very fun and interesting.

## Old answer, based on `math.pi` (74 bytes)

```
import math;f=lambda n:sum([ord(i)%2and int(i)for i in"%.*G"%(n,math.pi)])

```

Try it online!

N.B.: `math.pi` is "The mathematical constant π = 3.141592…, to available precision.", but the digits for the challenge are computed on the fly through the rounding and truncating operations. So, technically this is not a violation of the rules: *"all the digits of pi must be calculated by your program at runtime."*
> 3 votes

# Answer
## Mathematica, 53 bytes

```
Total@DeleteCases[(RealDigits@N[Pi,#])[[1]],_?EvenQ]&

```

Mathematica noob, please excuse me.
> 1 votes

# Answer
# Ruby, 78 bytes

```
f=->n{"#{eval'x=2*10**n+p*x/=2+p+p-=1;'*x=p=4*n}"[0,n].bytes.sum{|c|c%2*c%16}}

```

Computes only to necessary precision.

Try it online!
> 1 votes

# Answer
# Java 10, 275 bytes

```
import java.math.*;
n->{int j,t,i=0,s=3;for(;i<n-1;++i){var a=BigInteger.TEN.pow(10010).multiply(new BigInteger("2"));var p=a;for(j=1;a.signum()>0;p=p.add(a))a=a.multiply(new BigInteger(j+"")).divide(new BigInteger((2*j+++1)+""));s+=((t=(p+"").charAt(i+1)-48)%2)*t;}return s;}

```

Uses the approach from this answer by Kevin Cruijssen to calculate the digits. Try it online here.
> 0 votes

# Answer
# SmallTalk – 299 bytes

Relies on the identity `tan⁻¹(x) = x − x³/3 + x⁵/5 − x⁷/7 ...`, and that `π = 16⋅tan⁻¹(1/5) − 4⋅tan⁻¹(1/239)`, so no “cheats”.

```
|l a b c d e f g h p t s|l:=stdin nextLine asInteger. a:=1/5. b:=1/239. c:=a. d:=b. e:=a. f:=b. g:=3. h:=-1. s:=0. l timesRepeat:[c:=c*a*a. d:=d*b*b. e:=h*c/g+e. f:=h*d/g+f. g:=g+2. h:=0-h]. p:=4*e-f*4. l timesRepeat:[t:=p floor. p:=(p-t)*10. t odd ifTrue:[s:=s+t]]. Transcript show:s printString;cr

```

Save as `pi.st`. You provide the number of digits from the console when you run it, or through the `<<<` operator.

```
$ gst -q pi.st <<< 6
19

```
> 0 votes

# Answer
# Python 3, 119 bytes

```
y=sum([int(i)for i in str(sum([4/j if j%4%3 else-4/j for j in range(10**8)if j%2]))[0:n+1].replace('.','')if int(i)%2])

```

My first code-golf submit, so please be gentle .\_.

This computes pi on the fly using the Gregory-Leibniz series. X may prove insufficient for big n, but be aware of the RAMifications of choosing a large x.

## Explanation:

### Computation of Pi:

i.e. `sum( [4/i if i%4==1 else -4/i for i in range(x) if i%2==1] )` with x as large as sensible, also `i%4==1` is one byte larger than `i%4%3`, so that's nice...

### Casting **a lot** and eventual sum:

I'm sure there are better possibilities than all this, but I cast the float to string, take the first n\*1 chars (including the dec point), replace the point, then cast each char in my string to int for the modulo check at the very end of the code, and take the sum of all i that are odd to assign them to y.

### Room for improvement:

I'm sure there's lots, but I am the least happy with the series to compute pi, and also with the multiple int() casts ad the need to replace the dec point... *HELP*
> 0 votes

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


title: First Last Last First

text:
# Question
Title: First Last Last First
# Challenge

The task is simple. Given an array and a first and last value: Return the first of the last after the first, and the last of the first before the last.

---

Or simply: Given an array, var1, var2.

Example Array:

\[ var2, , var1, , var2, , var2, var1, var2, \]

Return:

* The index of the first var2 on the right side of the first var1 that appears in the array.

\[ var2, , *first var1*, , **first var2**, , second var2, var1, third var2, \]

* The index of the first var1 on the left side of the last var2 that appears in the array.

\[ var2, , second var1, , var2, , var2, **first var1**,*last var2*, \]

# Input

Two distinct positive integers

Array of positive integers

# Output

Index of answers, in order

# Rules

The array will contain at least one of each variable (minimum size of 2)

Assume inputs work

> Example: `0, 1 [1, 0]` or similar would fail

IO is flexible

# Examples

```
Input
First = 2; Last = 4; [0, 2, 4, 2, 3, 1, 4, 0, 1, 2, 4, 9]

Output
2, 9

```

---

```
Input
First = 4; Last = 2; [0, 2, 4, 2, 3, 1, 4, 0, 1, 2, 4, 9]

Output
3, 6

```

---

```
Input
First = 0; Last = 1; [0, 1]

Output
1, 0

```

# Answer
# Jelly, 17 bytes

```
ẹⱮṚ>Ƈ<Ƈƭ"1,0ị"$⁺Ʋ

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES6), 63 bytes

```
(x,y,a)=>a.map(P=(v,i)=>v-y?v-x?0:a=i:1/(p=a)?P=+P||i:0)&&[P,p]

```

Try it online!

### Commented

```
(x, y, a) =>          // given the two integers x, y and the array a[]
  a.map(P =           // initialize P to a non-numeric value
            (v, i) => // for each value v at position i in a[]:
    v - y ?           //   if v is not equal to y:
      v - x ?         //     if v is not equal to x:
        0             //       do nothing
      :               //     else (v = x):
        a = i         //       save the current position in a
    :                 //   else (v = y):
      1 / (p = a) ?   //     update p to a (last position of x); if p is numeric (>= 0):
        P = +P || i   //       unless P is also already numeric, update it to i
                      //       (if P is numeric, it's necessarily greater than 0 because
                      //       we've also seen x before; that's why +P works)
      :               //     else:
        0             //       do nothing
  )                   // end of map()
  && [P, p]           // return [P, p]

```

### Alternate versions

Using JS built-ins, a more straightforward answer is 79 bytes:

```
(x,y,a)=>[a.indexOf(y,a.indexOf(x)),a.slice(0,a.lastIndexOf(y)).lastIndexOf(x)]

```

which can be slightly compressed to 75 bytes:

```
(x,y,a)=>[a.indexOf(y,a.indexOf(x)),a.slice(0,a[L='lastIndexOf'](y))[L](x)]

```

Try it online!

**Edit**: @Neil managed to reduce it to a very nice **67-byte**:

```
(x,y,a,f=s=>a[z=y,y=x,x=z,s+=`ndexOf`](x,a[s](y)))=>[f`i`,f`lastI`]

```

Try it online!
> 4 votes

# Answer
# APL (Dyalog Classic), ~~29~~ 27 bytes

```
⊃{(⊃⍵~⍳⊃⍺),⊃⌽⍺∩⍳⊃⌽⍵}/⍸¨⎕=⊂⎕

```

Try it online!

prompts for the array and then for var1,var2
> 4 votes

# Answer
# Python 2, 72 bytes

```
def f(x,y,a):i=a.index;j=a[::-1].index;print i(y,i(x)),len(a)+~j(x,j(y))

```

Try it online!
> 4 votes

# Answer
# Python 3, ~~97~~ 93 bytes

-4 bytes thanks to ovs

```
def h(f,l,a,I=list.index):j=I(a,f);i=len(a)+~I(a[::-1],l);print(I(a[j:],l)+j,i-I(a[i::-1],f))

```

Try it online!
> 3 votes

# Answer
# Japt, ~~27~~ ~~25~~ 24 bytes

*Inspired in @Arnauld answer*

*Thanks @Shaggy -2 bytes and @ETHproductions -1 byte*

I just started with japt so it must be a better way.\

```
[WsX=WbU)bV +XWsTWaV)aU]

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog Unicode), 42 bytesSBCS

Anonymous tacit infix function. Takes var1,var2 as left argument and the array as right argument.

```
{⍸<\(⍵=⊃⌽⍺)∧∨\⍵=⊃⍺},{⍸⌽<\(⍵=⊃⍺)∧∨\⍵=⊃⌽⍺}∘⌽

```

Try it online!
> 1 votes

# Answer
# , 81 bytes

```
function(a,b,v,x=which(v==b),y=which(v==a))c(x[x>y[1]][1],tail(y[y<tail(x,1)],1))

```

Try it online!

(1-indexed)
> 1 votes

# Answer
# MATL, 27 bytes

```
y=Y>/ti=PY>P/t3G=f1)w2G=f0)

```

Try it online!

Alternately for the same bytecount:

### 27 bytes

```
y=Y>yi=*f1)y3G=PY>Pb2G=*f0)

```

Try it online!

The second one is easier to explain:

```
y   % implicitly get the first two inputs (the array and var1),
    %  and duplicate the first input
    %  stack: [[0 2 4 2 3 1 4 0 1 2 4 9] 2 [0 2 4 2 3 1 4 0 1 2 4 9]]
=   % compare and return logical (boolean) array
    %  stack: [[0 2 4 2 3 1 4 0 1 2 4 9] [0 1 0 1 0 0 0 0 0 1 0 0]]
Y>  % cumulative maximum - make all values after the first 1 also 1s
    %  stack: [[0 2 4 2 3 1 4 0 1 2 4 9] [0 1 1 1 1 1 1 1 1 1 1 1]]
    %  now we have 1s in positions at and after the first time var1 appears
y   % duplicate 2nd element in stack
    %  stack: [[0 2 4 2 3 1 4 0 1 2 4 9] [0 1 1 1 1 1 1 1 1 1 1 1] [0 2 4 2 3 1 4 0 1 2 4 9]]
i=  % compare with the next input (var2), returning a boolean array
    % stack: [[0 2 4 2 3 1 4 0 1 2 4 9] [0 1 1 1 1 1 1 1 1 1 1 1] [0 0 1 0 0 0 1 0 0 0 1 0]]
*   % multiply the two boolean arrays - so we'll have 1s only where var2 was present after the first occurrence of var1
    % stack: [[0 2 4 2 3 1 4 0 1 2 4 9] [0 0 1 0 0 0 1 0 0 0 1 0]]
f1) % find the index of the first 1 in that (this is our first result value)

```

The second part of the code does the same thing, except for these changes:

* use `2G` for second input (var1) and `3G` first 3rd input (var2) instead of implicit input or `i`, since those have been consumed
* use `PY>P` (flip array left-to-right, get cumulative maximum, flip back) instead of `Y>`, to get 1s *before the last occurrence* instead of after the first occurrence
* use `f0)` to get *last* place where both conditions are true, instead of first place (works because MATL uses modular indexing, so 0 is taken to refer to the last index of the array)
> 1 votes

# Answer
## MATLAB (80 bytes)

Input is `x`, `y`, and `a`. Since MATLAB is 1-indexed, you should add 1 to test cases.

```
xi=find(a==x);
yi=find(a==y);
yi(find(yi>xi(1),1))
xi(find(xi<yi(end),1,'last'))

```

Test case:

```
x=4
y=2
a =  [0, 2, 4, 2, 3, 1, 4, 0, 1, 2, 4, 9]

%
xi=find(a==x);
yi=find(a==y);
yi(find(yi>xi(1),1))
xi(find(xi<yi(end),1,'last'))

ans =

     4

ans =

     7

```
> 1 votes

# Answer
# Julia, ~~71~~ 64 bytes

thanks to sundar and his `find(A.==x)[]` instead of `findfirst(A,x))`.

.

```
(A,x,y)->findnext(A,y,find(A.==x)[]),findprev(A,x,findlast(A,y))

```
> 0 votes

# Answer
# Java 8, 114 bytes

A lambda taking a `java.util.List<Integer>` and two `int`s (var1, var2) and returning a comma-separated pair.

```
(a,f,l)->a.indexOf(f)+a.subList(a.indexOf(f),a.size()).indexOf(l)+","+a.subList(0,a.lastIndexOf(l)).lastIndexOf(f)

```

Try It Online
> 0 votes

# Answer
# Kotlin, 132 bytes

```
{f:Int,l:Int,a:Array<Int>->{var p=a.indexOfFirst{it==f}
while(a[p]!=l)p++
var i=a.indexOfLast{it==l}
while(a[i]!=f)i--
Pair(p,i)}()}

```

Try it online!
> 0 votes

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


title: Two lasers between two mirrors

text:
# Question
Title: Two lasers between two mirrors
What if we have a corridor comprised of two parallel mirrors?

```
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |
|          |

```

Now, we shine a laser down it...

```
|  \       |
|   \      |
|    \     |
|     \    |
|      \   |
|       \  |
|        \ |
|         \|
|         /|
|        / |

```

Oh, look. It bounced, towards the end, there.

What if we draw two lasers BUT going in the opposite direction?

```
|  \    /  |
|   \  /   |
|    \/    |
|    /\    |
|   /  \   |
|  /    \  |
| /      \ |
|/        \|
|\        /|
| \      / |

```

Hmm, they didn't seem to meet, there. That's convenient. What happens if both lasers take up the same space?

```
|  \     / |
|   \   /  |
|    \ /   |
|     X    |
|    / \   |
|   /   \  |
|  /     \ |
| /       \|
|/        /|
|\       / |

```

I guess that was pretty obvious, huh?

---

Drawing these diagrams by hand is pretty laborious (trust me on this). Perhaps some code could do it for us?

* Write some code to output two parallel mirrors, with two bouncing, intersecting lasers.
* Input (all integers):
    + The width of the corridor
    + The length of the corridor
    + Starting position of the right-going laser (zero-indexed, must be less than width)
    + Starting position of the left-going laser (zero-indexed, must be less than width)
* Process
    + If a laser is right going, it will be drawn one space to the right on the following line.
    + If a laser is left going, it will be drawn one space to the left on the following line.
    + If a laser can not take it's sideways step, it will change it's direction, but not it's position.
    + If both laser are at the same index, print an upper-case X at that index.
* Output
    + A string with multiple lines
    + Each line starts and ends with a pipe character (|)
    + Right-going laser are denoted by a back slash (\\)
    + Left-going laser are denoted by a forward slash (/)
    + The intersection of two lasers is denoted by an upper-case X.
* Any language
* I'd like to see TIO links
* Attempt to fix it in the smallest number of bytes

---

# Test cases

width: 6 length: 10 right-going: 1 left-going: 4

```
| \  / |
|  \/  |
|  /\  |
| /  \ |
|/    \|
|\    /|
| \  / |
|  \/  |
|  /\  |
| /  \ |

```

width: 6 length: 10 right-going: 0 left-going: 1

```
|\/    |
|/\    |
|\ \   |
| \ \  |
|  \ \ |
|   \ \|
|    \/|
|    /\|
|   / /|
|  / / |

```

width: 4 length: 10 right-going: 2 left-going: 0

```
|/ \ |
|\  \|
| \ /|
|  X |
| / \|
|/  /|
|\ / |
| X  |
|/ \ |
|\  \|

```

width: 20 length: 5 right-going: 5 left-going: 15

```
|     \         /    |
|      \       /     |
|       \     /      |
|        \   /       |
|         \ /        |

```

width: 5 length: 6 right-going: 2 left-going: 2

```
|  X  |
| / \ |
|/   \|
|\   /|
| \ / |
|  X  |

```

width: 1 length: 2 right-going: 0 left-going: 0

```
|X|
|X|

```

# Answer
> 12 votes
# Stax, 40 bytes

```
àù@○⌡┼PY¼îαφu^·A☺°É⌠■╟¡Åt^◘v(µ╩Ñ♣t{╓○xß╦

```

Run and debug it

Try it online!

Pretty sure this can be further golfed.

Input is given in the form of `width [right-going left-going] length`(per comment by @EngineerToast).

ASCII equivalent:

```
xHXdmzx);hi+x%Y92&;Hi-x%cy=41*47+&2ME:R\{|+m'||S

```

# Answer
> 18 votes
# JavaScript (ES6), 149 bytes

Takes input in currying syntax `(w)(h)([a,b])`.

```
w=>h=>g=(p,d=[1,-1],s=Array(w).fill` `)=>h--?`|${p=p.map((x,i)=>~(k=d[i],s[x]='/X\\'[x-p[i^1]?k+1:1],x+=k)&&x<w?x:x+(d[i]=-k)),s.join``}|
`+g(p,d):''

```

Try it online!

### Commented

```
w => h =>                  // w = width, h = height
  g = (                    // g = recursive function taking:
    p,                     //   p[] = array holding the point coordinates
    d = [1, -1],           //   d[] = directions
    s = Array(w).fill` `   //   s = array of w spaces (we can't use a string because it's
  ) =>                     //       immutable in JS)
    h-- ?                  // if we haven't reached the last row yet:
      `|${                 //   append the left pipe
      p = p.map((x, i) =>  //   for each x at position i in p[]:
        ~(k = d[i],        //     k = direction for this point
          s[x] = '/X\\'[   //     insert either '/', 'X' or '\' at position x in s
            x - p[i ^ 1] ? //     if p[0] != p[1]:
              k + 1        //       use the direction
            :              //     else:
              1            //       force 'X'
          ], x += k        //     add k to x
        ) &&               //     if the result is not equal to -1
        x < w ?            //     and is less than w:
          x                //       use the current value of x
        :                  //     else:
          x + (d[i] = -k)  //       change the direction and restore the initial value of x
      ),                   //   end of map()
      s.join``}|\n` +      //   join and append s; append the right bar and a linefeed
      g(p, d)              //   followed by the result of a recursive call
    :                      // else:
      ''                   //   stop recursion

```

# Answer
> 11 votes
# Python 2, 119 bytes

```
w,l,a,b=input()
exec"print'|%s|'%''.join(' \/X'[sum(i==k%(2*w)for k in[a,~b]+[~a,b]*2)]for i in range(w));a+=1;b-=1;"*l

```

Try it online!

# Answer
> 9 votes
# Python 2, ~~187~~ ~~181~~ ~~179~~ ~~177~~ ~~174~~ ~~172~~ 171 bytes

```
def f(w,l,a,b,A=1,B=-1):
 while l:l-=1;print'|%s|'%''.join(' \X/'[[0,A,B,2][(i==a)+2*(i==b)]]for i in range(w));a,A=[a,a+A,-A,A][-1<a+A<w::2];b,B=[b,b+B,-B,B][-1<b+B<w::2]

```

Try it online!

---

Recursive:

# Python 2, 172 bytes

```
def f(w,l,a,b,A=1,B=-1):
 if not-1<a<w:A=-A;a+=A
 if not-1<b<w:B=-B;b+=B
 if l:print'|%s|'%''.join(' \X/'[[0,A,B,2][(i==a)+2*(i==b)]]for i in range(w));f(w,l-1,a+A,b+B,A,B)

```

Try it online!

---

Recursive, alternative print:

# Python 2, 172 bytes

```
def f(w,l,a,b,A=1,B=-1):
 if not-1<a<w:A=-A;a+=A
 if not-1<b<w:B=-B;b+=B
 if l:L=[' ']*w;L[a]=' \/'[A];L[b]=[' \/'[B],'X'][a==b];print'|%s|'%''.join(L);f(w,l-1,a+A,b+B,A,B)

```

Try it online!

# Answer
> 9 votes
# Python 2, 168 bytes

```
w,n,r,l=input()
R=L=1
exec"""
d=[~r*R,-~l*L].count
print'|%s|'%''.join(' /\X'[2*d(~x)|d(x+1)]for x in range(w))
if-1<r+R<w:r+=R
else:R=-R
if-1<l-L<w:l-=L
else:L=-L"""*n

```

Try it online!

# Answer
> 8 votes
# C (clang), ~~240~~ ~~236~~ 208 bytes

```
#define g(a,b) b?a++,a==x&&(a=x-1,b=0):a--,a==-1&&(a=0,b=1)
i,m,n,o,p,t[]={47,92};f(x,y,r,l){for(m=1,n=0;y--;puts("|"),g(r,m),g(l,n))for(printf("|"),i=0;i<x;o=i==r,p=i++==l,putchar(o*p?88:o?t[m]:p?t[n]:32));}

```

Try it online!

f() takes parameters as follows:

`x` = width,
`y` = length,
`r` = Initially right-going line starting position
`l` = Initially left-going-line starting position

-4 Bytes. credits Kevin Cruijssen. Thanks

# Answer
> 7 votes
# Canvas, ~~66~~ 40 bytes

```
｛²Ｘø⁶╵［⁷／²２％［↔｝∔｝；ｘ╷？⁷∔⁷＋╷｝［ｊ｝｝ｎ⁶［|ＰＪｐ|ｐ

```

Try it here!

# Answer
> 5 votes
# Charcoal, ~~56~~ 50 bytes

```
↷ＰＩθＭ⊕η→ＩθＦ²«Ｊ⊕⎇ιεζ⁰ＦＩθ«✳§⟦↘↙⟧ι∨⁼ＫＫψX¿⁼ＫＫ|«¿ι→←≦¬ι

```

Try it online! Link is to verbose version of code. Edit: Saved 6 bytes by reducing reliance on pivoting. Explanation:

```
↷ＰＩθＭ⊕η→Ｉθ

```

Print the sides.

```
Ｆ²«

```

Loop over the two lasers.

```
Ｊ⊕⎇ιεζ⁰

```

Move to the start of the laser.

```
ＦＩθ«

```

Loop over the height.

```
✳§⟦↘↙⟧ι∨⁼ＫＫψX

```

Draw a `\` or `/` in the appropriate direction, unless the square is not empty, in which case draw an `X`.

```
¿⁼ＫＫ|«

```

Have we hit a side?

```
¿ι→←≦¬ι

```

If so then take one step sideways and invert the direction of travel.

# Answer
> 5 votes
# Java (JDK 10), 186 bytes

```
(w,h,r,l)->{var x="";for(int i=0,j,R=1,L=-1;i++<h;l+=L,l+=l<0|l>=w?L=-L:0,r+=R,r+=r<0|r>=w?R=-R:0,x+="|\n")for(j=0,x+="|";j<w;j++)x+="/X\\ ".charAt(j==r?j==l?1:R+1:j==l?L+1:3);return x;}

```

Try it online!

# Answer
> 3 votes
# PHP, ~~177 169~~ 166 bytes

```
[,$w,$h,$a,$b]=$argv;for($e=-$d=1;$h--;$s[$a+=$d]^L?:$a+=$d=-$d,$s[$b+=$e]^L?:$b+=$e=-$e){$s=str_pad("",$w)."|";$s[$b]="X\/"[$e];$s[$a]="X\/"[$a-$b?$d:0];echo"|$s
";}

```

requires **PHP 7.1** for negative string indexes, **PHP 5.5** or later for indexing string literals.
for **PHP \<7.1**, remove `^L`, replace `"X\/"` with `"/X\\"`, `:0` with `+1:1`, `[$e]` with `[$e+1]`, remove `."|"` and insert `|` before the newline. (+3 bytes)
for **PHP \< 5.5**, replace `"/X\\"` with `$p` and insert `$p="/X\\";` at the beginning. (+2 bytes)

takes input from command line arguments. Run with `-nr` or try them online.

# Answer
> 3 votes
# Python 3, 162 bytes

```
from numpy import*
def f(w,h,u,v):
 v=w+w-v-1;T=eye(w);M=vstack([T,2*T[::-1]]*2*h)
 for r in M[u:u+h,:]+M[v:v+h,:]:print('|%s|'%''.join(' \/X'[int(i)]for i in r))

```

Try it online!

# Answer
> 3 votes
# Ruby, 117 bytes

```
->w,h,a{a[1]-=w;(1..h).map{s=' '*w;a.map!{|x|d=x<0?-1:1;s[x]='X\\/'[s[x][/ /]?d:0];x+=d;x==w ?-1:x<-w ?0:x};?|+s+?|}}

```

Try it online!

Anonymous lambda taking input as width `w`, height `h` and an array of starting points `a`.

# Answer
> 2 votes
# PowerShell, ~~243~~ ~~233~~ ~~222~~ 205 bytes

```
param($w,$h,$a,$b)$l,$r,$s=1,-1,' \/'
1..$h|%{$p,$p[$b],$p[$a]=[char[]](' '*$w),$s[$r],($s[$l],"x")[!($a-$b)]
if($a+$l-in($z=0..($w-1))){$a+=$l}else{$l*=-1}if($b+$r-in$z){$b+=$r}else{$r*=-1}"|$(-join$p)|"}

```

Try it online!

Oooof. those logic blocks are big and dirty and mostly duplicated. The next step would be rewriting them so they don't need the else statement.

# Answer
> 1 votes
# Python 2, ~~165~~ 164 bytes

```
w,h,x,y=input()
a,b,s=1,-1,' \/'
exec"""l=[' ']*w
l[x],l[y]=s[a],s[b]if x-y else'X'
if-1<x+a<w:x+=a
else:a=-a
if-1<y+b<w:y+=b
else:b=-b
print'|%s|'%''.join(l)
"""*h

```

Saved a byte thanks to Jonathan Frech.
Try it online!

# Answer
> 1 votes
# K (ngn/k), 58 bytes

```
{" \\/X|"4,'(+/3!1 2*(x#'e+2*|e:=2*x)(2*x)!z+(!y;-!y)),'4}

```

Try it online!

anonymous function that accepts three arguments: `x` the width, `y` the length, `z` a pair of starting positions for the lasers

# Answer
> 1 votes
# C (gcc), 169 bytes

```
A,B,c;f(w,l,a,b){for(A=1,B=-1;l--;a+=A,a<0|a==w?A=-A,a+=A:0,b+=B,b<0|b==w?B=-B,b+=B:0,puts("|"))for(c=-1;c<w;c++)putchar(c<0?'|':a^c?b^c?32:B>0?92:47:b^c?A>0?92:47:88);}

```

Try it online!

# Answer
> 1 votes
# Kotlin, ~~322~~ ~~311~~ 302 bytes

Changed how I put laser direction in string for 11 bytes. Moved assignment out of when for 9 bytes.

```
{w:Int,h:Int,r:Int,l:Int->{var a=""
var f=r
var d=1>0
var s=l
var t=!d
for(o in 1..h){a+="|"
for(c in 0..w-1)a+=when{c==f&&c==s->"X"
c==f&&d||c==s&&t->"\\"
c==f||c==s->"/"
else->" "}
a+="|\n"
if(d){if(++f==w){--f
d=!d}}else if(--f<0){f=0
d=!d}
if(t){if(++s==w){--s
t=!t}}else if(--s<0){s=0
t=!t}}
a}()}

```

Try it online!

---
Tags: code-golf, ascii-art
---


title: Incrementing Gray Codes

text:
# Question
Title: Incrementing Gray Codes
# Introduction

A Gray Code is an alternative to binary representation in which a number is incremented by toggling only one bit, rather than a variable amount of bits. Here are some gray codes along with their decimal and binary equivalents:

```
 decimal | binary | gray
-------------------------
       0 |      0 |    0
-------------------------
       1 |      1 |    1
-------------------------
       2 |     10 |   11
-------------------------
       3 |     11 |   10
-------------------------
       4 |    100 |  110
-------------------------
       5 |    101 |  111
-------------------------
       6 |    110 |  101
-------------------------
       7 |    111 |  100
-------------------------
       8 |   1000 | 1100
-------------------------
       9 |   1001 | 1101
-------------------------
      10 |   1010 | 1111
-------------------------
      11 |   1011 | 1110
-------------------------
      12 |   1100 | 1010
-------------------------
      13 |   1101 | 1011
-------------------------
      14 |   1110 | 1001
-------------------------
      15 |   1111 | 1000

```

### Cyclic Bit Pattern of a Gray Code

Sometimes called "reflected binary", the property of changing only one bit at a time is easily achieved with cyclic bit patterns for each column starting from the least significant bit:

```
bit 0: 0110011001100110011001100110011001100110011001100110011001100110
bit 1: 0011110000111100001111000011110000111100001111000011110000111100
bit 2: 0000111111110000000011111111000000001111111100000000111111110000
bit 3: 0000000011111111111111110000000000000000111111111111111100000000
bit 4: 0000000000000000111111111111111111111111111111110000000000000000
bit 5: 0000000000000000000000000000000011111111111111111111111111111111

```

...and so on.

# Objective

Given a non-padded input string of a gray code, increment the gray code by alternating a single character in the sequence or prepending a `1` (when incrementing to the next power of 2), then output the result as a non-padded gray code.

### Caveats

* Do not worry about taking `0` or an empty string as input.
* The lowest input will be `1`, and there is no upper-bound to the string length other than memory limitations imposed by the environment.
* By non-padded string, I mean there will be no leading or trailing whitespace (other than an optional trailing newline), and no leading `0`s in the input or output.

### I/O formats

The following formats are accepted form for input and output, but strings are encouraged over other formats:

* most significant "bit" first
* non-padded character array or string of ASCII `'1'`s and `'0'`s
* non-padded integer array of `1`s and `0`s
* non-padded boolean array

**What's not allowed:**

* least significant "bit" first
* decimal, binary or unary integer
* fixed-length data-structure
* character array or string of non-printable ASCII indices `1` and `0`

### Tests

```
input -> output
1 -> 11
11 -> 10
111 -> 101
1011 -> 1001
1111 -> 1110
10111 -> 10110
101100 -> 100100
100000 -> 1100000

```

More tests can be added by request.

# Criteria

This is , so shortest program in bytes wins! All ties will be broken by favoring earlier submissions; standard loopholes apply. The best submitted answer will be accepted October 9th, 2016, and updated whenever better answers are given.

# Answer
> 14 votes
## Jelly, ~~10~~ 8 bytes

*Thanks to Dennis for saving 2 bytes.*

```
^\Ḅ‘^H$B

```

Input and output are lists of 0s and 1s.

Try it online!

### Explanation

The inverse of the Gray code is given by A006068. Using this we don't need to generate a large number of Gray codes to look up the input. One classification of this sequence given on OEIS is this:

```
a(n) = n XOR [n/2] XOR [n/4] XOR [n/8] ...

```

Where the `[]` are floor brackets. Consider the example of `44` whose binary representation is `101100`. Dividing by 2 and flooring is just a right-shift, chopping off the least-significant bit. So we're trying to XOR the following numbers

```
1 0 1 1 0 0
  1 0 1 1 0
    1 0 1 1
      1 0 1
        1 0
          1

```

Notice that the `n`th column contains the first `n` bits. Hence, this formula can be computed trivially on the binary input as the cumulative reduction of XOR over the list (which basically applies XOR to each prefix of the list and gives us a list of the results).

This gives us a simple way to invert the Gray code. Afterwards, we just increment the result and convert it back to the Gray code. For the latter step we use the following definition:

```
a(n) = n XOR floor(n/2)

```

Thankfully, Jelly seems to floor the inputs automatically when trying to XOR them. Anyway, here is the code:

```
^\          Cumulative reduce of XOR over the input.
  Ḅ         Convert binary list to integer.
   ‘        Increment.
    ^H$     XOR with half of itself.
       B    Convert integer to binary list.

```

# Answer
> 9 votes
# Perl, ~~27~~ 25 bytes

Includes +1 for `-p`

Give input string on STDIN, e.g.

```
gray.pl <<< 1010

```

`gray.pl`:

```
#!/usr/bin/perl -p
s%(10*\K1(\K0)*)*%1-$&%e

```

Perl has no cheap infinite-precision integers. So directly toggle the right bit which is the one just before where the last odd-numbered 1 would be.

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

```
s=>s.replace(s.split`1`.length%2?/.$/:/.?(?=10*$)/,c=>1-c)

```

Directly toggles the appropriate bit. Explanation: As shown in MartinEnder♦'s answer, each bit in a decoded Gray code is the cumulative XOR, or parity, of itself and the bits to its left. We then need to increment the number which causes a carry ripple that toggles all the rightmost 1 bits to 0 and then the next 0 bit to 1. Re-encoding results in a code with just that one 0 bit position toggled. If the parity of all the 1 bits is even, then the rightmost bit is 0 and we therefore just toggle the last bit. If the parity of all the 1 bits is odd, then the rightmost bits are 1, and we need to find the last 1 bit. This is now the last of the carried bits, so the bit we need to toggle is the next bit from the right.

# Answer
> 6 votes
# Haskell, ~~118 115~~ 108 bytes

```
g 0=[""]
g n|a<-g$n-1=map('0':)a++map('1':)(reverse a)
d=dropWhile
f s=d(=='0')$(d(/='0':s)$g$1+length s)!!1

```

Try it on Ideone.
Naive approach: `g` generates the set of all gray codes with length `n` (with 0-padding), `f` calls `g` with `length(input)+1`, removes all elements until `0<inputstring>` is found and returns the next element (truncating a possibly leading `0`).

# Answer
> 6 votes
## JavaScript (ES6), 53 bytes (non-competing)

A recursive function which builds all gray codes until the input is found, then stops at the next iteration.

The highest possible input depends on the browser recursion limit (about 13 bits in Firefox and 15 bits in Chrome).

```
f=(s,n=1)=>(b=(n^n/2).toString(2),s)?f(b!=s&&s,n+1):b

console.log(f("1"));      // -> 11
console.log(f("11"));     // -> 10
console.log(f("111"));    // -> 101
console.log(f("1011"));   // -> 1001
console.log(f("1111"));   // -> 1110
console.log(f("10111"));  // -> 10110
console.log(f("101100")); // -> 100100
console.log(f("100000")); // -> 1100000
```

# Answer
> 5 votes
# MATL, 18 bytes

```
ZBtE:t2/kZ~tb=fQ)B

```

Try it online! Or verify all test cases.

### Explanation

Let *a*(*n*) denote the sequence of integers corresponding to Gray codes (OEIS A003188). The program uses the characterization *a*(*n*) = *n* XOR floor(*n*/2), where XOR is bit-wise.

Essentially, the code converts the input to an integer *a*0, finds that integer in the sequence, and then selects the next term. This requires generating a sufficiently large number of terms of the sequence *a*(*n*). It turns out that 2·*a*0 is sufficiently large. This stems from the fact that the Gray code *a*(*n*) never has more binary digits than *n*.

Let's take input `'101'` as an example.

```
ZB      % Input string implicitly. Convert from binary string to integer
        %   STACK: 5
t       % Duplicate
        %   STACK: 5, 5
E       % Multiply by 2. This is the number of terms we'll generate from the sequence
        %   STACK: 5, 10
:       % Range
        %   STACK: 5, [1 2 3 4 5 6 7 8 9 10]
t       % Duplicate
        %   STACK: 5, [1 2 3 4 5 6 7 8 9 10], [1 2 3 4 5 6 7 8 9 10]
2/k     % Divide by 2 and round down, element-wise
        %   STACK: 5, [1 2 3 4 5 6 7 8 9 10], [0 1 1 2 2 3 3 4 4 5]
Z~      % Bit-wise XOR, element-wise
        %   STACK: 5, [1 3 2 6 7 5 4 12 13 15]
t       % Duplicate
        %   STACK: 5, [1 3 2 6 7 5 4 12 13 15], [1 3 2 6 7 5 4 12 13 15]
b       % Bubble up
        %   STACK: [1 3 2 6 7 5 4 12 13 15], [1 3 2 6 7 5 4 12 13 15], 5
=       % Equality test, element-wise
        %   STACK: [1 3 2 6 7 5 4 12 13 15], [0 0 0 0 0 1 0 0 0 0]
f       % Find: yield (1-based) index of nonzero values (here there's only one)
        %   STACK: [1 3 2 6 7 5 4 12 13 15], 6
Q       % Increase by 1
        %   STACK: [1 3 2 6 7 5 4 12 13 15], 7
)       % Apply as index
        %   STACK: 4
B       % Convert to binary array
        %   STACK: [1 0 0]
        % Implicitly display

```

# Answer
> 5 votes
## CJam (19 bytes)

```
{_2b__(^@1b1&*)^2b}

```

Online demo. This is an anonymous block (function) from bit array to bit array, which the demo executes in a loop.

It works on the simple principle that if the number of set bits is even we should toggle the least significant bit, and otherwise we should toggle the bit to the left of the least significant set bit. Actually identifying that bit turns out to be much easier using bit hacks on an integer than using the list of bits.

### Dissection

```
{         e# Declare a block:
  _2b     e#   Convert the bit array to a binary number
  __(^    e#   x ^ (x-1) gives 1s from the least significant set bit down
  @1b1&   e#   Get the parity of the number of set bits from the original array
  *       e#   Multiply: if we have an even number of set bits, we get 0;
          e#   otherwise we have 2**(lssb + 1) - 1
  )^      e#   Increment and xor by 1 or 2**(lssb + 1)
  2b      e#   Base convert back to a bit array
}

```

Working solely with the bit array, I think it's necessary to reverse it: working with the left-most `1` is much easier than the right-most. The best I've found so far is (24 bytes):

```
{W%_1b)1&1$+1#0a*1+.^W%}

```

---

### Alternative approach (19 bytes)

```
{[{1$^}*]2b)_2/^2b}

```

This converts from Gray code to index, increments, and converts back to Gray code.

# Answer
> 2 votes
## Retina, 25 bytes

```
^(10*10*)*
$1:
1:
0
.?:
1

```

I feel sure there should be a better way of doing this...

# Answer
> 2 votes
# 05AB1E, 12 bytes

Uses CP-1252 encoding.

```
CÐ<^¹SOÉ*>^b

```

Try it online!

**Explanation**

Example for input *1011*.

```
C              # convert to int (bigint if necessary)
               # STACK: 11
 Ð             # triplicate
               # STACK: 11, 11, 11
  <            # decrease by 1
               # STACK: 11, 11, 10
   ^           # XOR
               # STACK: 11, 1
    ¹          # push first input
               # STACK: 11, 1, 1011
     S         # split to list
               # STACK: 11, 1, [1,0,1,1]
      O        # sum
               # STACK: 11, 1, 3
       É       # mod 2
               # STACK: 11, 1, 1
        *      # multiply
               # STACK: 11, 1
         >     # increase by 1
               # STACK: 11, 2
          ^    # XOR
               # STACK: 9
           b   # convert to binary
               # STACK: 1001
               # implicitly print top of stack

```

# Answer
> 2 votes
## Batch, ~~199~~ 197 bytes

```
@echo off
set/ps=
set r=
set t=%s:0=%
if 1%t:11=%==1 goto g
:l
set b=%s:~-1%
set s=%s:~,-1%
set r=%b%%r%
if %b%==0 goto l
if 0%s%==0 set s=0
:g
set/ab=1-%s:~-1%
echo %s:~,-1%%b%%r%

```

Reads input from STDIN into variable `s`. Removes the 0s and does a parity check on the 1s and if there are an odd number it strips the rightmost 0s in a loop, stopping when it strips a 1. `s` therefore contains the even parity prefix and `r` the rest of the string. `s` is set to zero if it was blank so that its last digit can be toggled, and then everything is concatenated.

# Answer
> 2 votes
## C++, 205 bytes

```
#include <string>
std::string g(std::string s){int i,z;if(s=="1")return"11";for(i=z=0;i<s.length();i++)if(s[i]=='1')z++;i--;if(z%2){char c=s[i];s.erase(i);s=g(s);s+=c;}else{s[i]=s[i]==49?48:49;}return s;}

```

Description: Even numbers have even number of ones. Variable `z` counts ones; if `z` is even (`z mod 2 = z%2 = 0` \- else branch), alter the last bit; if `z` is odd, call this function again without the last character and calculate new value, then append the last character afterwards.

Click here to try it for the test cases.

# Answer
> 1 votes
## Python 2.7, 68 characters

```
def f(s):i=long(s,2);print bin(i^(1,(i&-i)<<1)[s.count('1')&1])[2:]

```

## Python 3, 68 characters

```
def f(s):i=int(s,2);print(bin(i^(1,(i&-i)<<1)[s.count('1')&1])[2:])

```

This function converts the given binary string to an integer then xor the last bit if the number of set bits in the original string is even, or its swaps the bit to the left of the rightmost set bit if the number of set bits in the original string is odd. Then it converts the result to a binary string and removes the `0b` boolean prefix.

# Answer
> 1 votes
# Actually, ~~20~~ ~~19~~ 13 bytes

Based on Martin Ender's Jelly answer with my own version of "cumulative reduce of XOR over the input". Golfing suggestions welcome. Try it online!

```
σ1♀&2@¿u;½≈^├

```

**Ungolfing**

```
      Implicit input a as a list, such as [1,0,1,1,0,0].
σ     Get the cumulative sums of a.
1♀&   Map x&1 (equivalent to x%2) over every member of the cumulative sum.
2@¿   Convert from binary to decimal.
u     Increment x.
;½≈   Duplicate and integer divide by 2.
^     XOR x and x//2.
├     Convert to binary to obtain our incremented Gray code.
      Implicit return as a string, such as "100100".

```

# Answer
> 1 votes
# J, 38 bytes

```
[:#:@(22 b.<.@-:)@>:@#.[:22 b./[:#:#.\

```

Try it online!

This is essentially Martin's algorithm in J.

Note that `22 b.` is XOR.

```
                                    [: #: #.\   Creates the prefixes of the input
                                                converts to a number, then converts
                                                back to binary.  Needed to get the
                                                padding on the left.

                          [: 22 b./             Reduce the rows of the resulting
                                                matrix with XOR, giving us the
                                                normal binary
                      @#.                       Convert to int and...
                   @>:                          Increment and...
      (22 b. <.@-:)                             XOR that with its own floored half
[: #:@                                          And turn the result back to binary

```

---
Tags: code-golf, sequence, number-theory, binary, coding-theory
---


title: Hardcoding the Cops and Robbers (Cops)

text:
# Question
Title: Hardcoding the Cops and Robbers (Cops)
**This is a challenge. The robbers' thread is here.**

An interesting question to think about is the following:

> If I have a sequence of numbers how many of them do I have to provide before it is clear what sequence I am talking about?

For example if I want to talk about the positive integers in order starting from \\$1\\$, I could say \\$1,2,3, \dots\\$, but is that really enough?

I have one way of answering this question, and being a code-golfer it involves code-golf. You have provided enough terms of a sequence if the shortest code that produces those terms produces all the terms of the sequence. If we think about this in terms of code-golf, this would mean you have provided enough test cases such that the shortest code that passes the test-cases does the desired task.

## Challenge

This challenge is a challenge. In which cops will be presenting test-cases and robbers will have to find a shorter way to spoof the test-cases other than the intended sequence. Cops will present the following things:

* A piece of code that takes a non-negative integer as input and produces an integer as output. This code will define your sequence. Your code does not need to support 0 as an input, opting to instead take 1 as the smallest input. It should be clear if this is the case in your answer.
* Any relevant platform or language requirements that might affect the output, for example the size of longint.
* A number \\$n\\$, along with the first \\$n\\$ terms of the sequence as calculated by the code. These will act as "test-cases".

You are encouraged to explain what your sequence does and link OEIS if it exists, however it is your code that defines the sequence not the description.

Robbers will be finding a program in the same language that is shorter than the one presented and passes all the test cases (produces the same output for the first \\$n\\$ inputs as the cop's code). The robber's code must also differ in output from the cop's program for some number larger than \\$n\\$.

Cops must be able to crack their own answers before submitting them.

After one week a cop *may* reveal their crack and mark their answer as Safe. Answers marked as such can no longer be cracked.

## Scoring

Cops answers will be scored by the number of bytes with fewer bytes being better. Cracked answers score an infinite score.

# Answer
# cQuents, 4 bytes (Cracked)

```
"::$

```

Try it online!

Here are eight (`n=8`) cases:

```
1 1
2 12
3 123
4 1234
5 12345
6 123456
7 1234567
8 12345678

```

Code explanation:

```
"      Stringify sequence (join on "", remove it and see what happens)
 ::    Given input n, output all items in the sequence up to and including n
   $   Each item in the sequence equals the index

```

So the sequence is `1,2,3,4,5 ...`, it is joined on `""` so it becomes `12345 ...`, and `::` means that it prints up to the input.
> 6 votes

# Answer
# Python 3, ~~66~~ 57 bytes (Cracked)

*cracked by xnor*
*also cracked by Cat Wizard before an edit*

```
def f(n):x=n/10-2;return int(x*60-x**3*10+x**5/2-x**7/84)

```

Try it online!

Hello! Here is a sequence to crack for \\$n=40\\$. It gives these first 40 elements with 0-indexing, it's not an OEIS sequence

```
[-54, -56, -58, -59, -59, -59, -59, -57, -55, -53, -50, -46, -43, -38, -33, -28, -23, -17, -11, -5, 0, 5, 11, 17, 23, 28, 33, 38, 43, 46, 50, 53, 55, 57, 59, 59, 59, 59, 58, 56]

```
> 5 votes

# Answer
# Python 2, 44 bytes (cracked)

```
f=lambda n,i=1,p=1:n and-~f(n-p%i,i+1,p*i*i)

```

Try it online!

The prime numbers. What sequence could be purer? Or more overdone? Your goal is to produce the first 50 primes for `n=1` to `n=50`.

The code is a Wilson's Theorem generator copied exactly from this tip.

The different values for the alternative sequence are not due to machine limitations like overflows and precision. No 3rd party libraries.

---

Cracked by Arnauld, @PoonLevi, and Mr. Xcoder.
> 5 votes

# Answer
# Wolfram Language (Mathematica), ~~39~~ 34 bytes (Safe)

```
Check[{1,9,7}[[#]],18+Boole[#>9]]&

```

Try it online!

Looks simple, solution should be hard.

1-indexed and \\$n = 99\\$. This sequence is not available on the OEIS.

```
{1, 9, 7, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19}

```

This above list is equal to:

```
Join[{1, 9, 7}, Table[18, 6], Table[19, 90]]

```

Here's a template for checking your solution: Try it online!

## Intended Crack

> The catch here is that the output increases by 1 when the number of digit increases by 1, with the exception for the first three terms; the intended solution has something to do with string conversion.
> Hence, reading the documentation on Converting between Expressions & String, one could find the function `SpokenString`.
> The solution is simply the length of the spoken-string version of the expression `x^n` for various inputs: `StringLength@SpokenString[x^#]&`
> 4 votes

# Answer
# Haskell, 29 bytes (Cracked: ,)

```
a n=n*ceiling(realToFrac n/2)

```

Try it online!

This is A093005: \\$ a(n)=n\lceil \frac{n}{2} \rceil\\$.

Test cases for \\$0 \leq n \leq 20 \\$, that is `map a [0..20]`:

```
[0,1,2,6,8,15,18,28,32,45,50,66,72,91,98,120,128,153,162,190,200]

```

## Intended solution (20 bytes)

```
b n=sum$n<$show(3^n)

```

Try it online! Differs at \\$ n=23 \\$, with \\$ a(23) = 276 \\$ and \\$ b(23) = 253\\$.

This function is equivalent to \\$b(n) = n\ len(3^n) = n \lceil log\_{10}(1+3^n)\rceil\\$. Thanks to the ceiling, both functions overlap for integer arguments in the range from \\$0\\$ to \\$22\\$:

source
> 3 votes

# Answer
# APL (Dyalog Unicode), ~~17~~ 15 bytes, safe

```
⌈∊∘1 5+.633*5-⊢

```

Try it online!

The first 13 terms (1-based) are:

```
2 1 1 1 2 2 3 4 7 10 16 25 39

```

Hint: The intended solution uses one of the least used built-in functions.

---

The intended code is the following:

# APL (Dyalog Unicode), 10 bytes

```
⌊(2*⍳)⌹⌽∘⍳

```

Try it online!
> 2 votes

# Answer
# JavaScript (ES6), 12 bytes (Cracked)

This one is rather easy.

```
n=>n*(8*n+1)

```

Try it online!

This is A139275:

$$a(n) = n(8n+1)$$

Your code must support \\$0\le n\<9\\$:

$$0, 9, 34, 75, 132, 205, 294, 399, 520$$

And as per the challenge rules, it must diverge beyond.
> 2 votes

# Answer
# Jelly, 6 bytes, Safe!

```
<4+ạ2ȯ

```

This defines a **zero-indexed** sequence where:

$$ a(n) = \begin{cases} 1 & n\<3 \\ 2 & n=3 \\ n-2 & n\>3 \end{cases}$$

As such the first sixteen values \\$a(0)\cdots a(15)\\$ are `1,1,1,2,2,3,4,5,6,7,8,9,10,11,12,13`

**Try it online!** (here is a single value version)

This is not currently in the OEIS (although A34138 will work as a crack if short enough)

### Intended Crack

> The sequence above agrees with the count of decimal digits of the first \\$16\\$ terms of A062569, the sum of the divisors of the factorial of \\$n\\$ (also zero-indexed).
> The \\$17^{\text{th}}\\$ term of A062569, however, is \\$107004539285280\\$ which has \\$15\\$ digits, not \\$14=a(16)\\$.
> The required code is **five** bytes in Jelly, `!ÆsDL`.
> 2 votes

# Answer
# \>\<\>, 276 bytes (Cracked)

```
1$1-:?!v$:      1[0$          >:?!va2[$:{:@%:{$-{,]v
       >$n; v              <  ^   >~{]02.1+1+ffr+1r<
 :}[r]{  [01>:{*@@+$a*l2=?!^~]+ff+9+1g"3"=?v"3"ff+9+1pf0.
 :}[l01-$>    $:0(?v$@$:@@:@)?v@@1-$}v     >"2"ff+9+1p00.
>.       ^-1l v!?} <  .4a}$@@$<   .4a<
^26{]r0[}:{]~{<

```

Try it online! Call this one with `-v n` to get the n-th element (1-indexed)

```
1$1-:?!;$::n84*o1[0$          >:?!va2[$:{:@%:{$-{,]v
            v              <  ^   >~{]02.1+1+ffr+1r<
 :}[r]{  [01>:{*@@+$a*l2=?!^~]+ff+9+1g"3"=?v"3"ff+9+1pf0.
 :}[l01-$>    $:0(?v$@$:@@:@)?v@@1-$}v     >"2"ff+9+1p00.
>.       ^-1l v!?} <  .4a}$@@$<   .4a<
^26{]r0[}:{]~{<

```

Try it online! Call with `-v n` to get a list of n-1 elements starting at 1

Online Fish Interpreter

A long and complex one, this is OEIS A004000.

> Let a(n) = k, form m by Reversing the digits of k, Add m to k Then Sort the digits of the sum into increasing order to get a(n+1).
>
> Example: 668 -\> 668 + 866 = 1534 -\> 1345.

Because the code in \>\<\> is quite long, the challenge is to crack it for \\$n = 34\\$. These 34 elements make a total of 290 bytes, just a bit too much to hardcode the result ;)
Here are the 34 first elements 1-indexed

```
1 2 4 8 16 77 145 668 1345 6677 13444 55778 133345 666677 1333444 5567777 12333445 66666677 133333444 556667777 1233334444 5566667777 12333334444 55666667777 123333334444 556666667777 1233333334444 5566666667777 12333333334444 55666666667777 123333333334444 556666666667777 1233333333334444 5566666666667777

```
> 2 votes

# Answer
# Malbolge, 10 bytes

```
ub&;$9]J6

```

Note that the code ends with an 0x14 (device control 4) byte.

Try it online!

The 0-indexed sequence to crack is `[9, 19, 29]`.
> 2 votes

# Answer
# JavaScript, 26 bytes (Cracked)

```
let f=x=>x>1?f(x-1)*f(x-2)+1:1

for (x of [0,1,2,3,4,5,6,7]) {
  console.log(x + ' -> ' + f(x))
}
```

OEIS A007660

Output is the first 6 elements with 0 indexing (1,1,2,3,7,22)

(somewhat shifted from what OEIS has it listed as)

Just creating a simple to solve answer to kick things off

Try it online!
> 1 votes

# Answer
# JavaScript, 16 bytes (Cracked)

```
g=
x=>Math.exp(x)|0

tmp=[0,1,2,3,4]
console.log(tmp.map(g).join(','))
```

First 5 elements of OEIS149 (\\$\lfloor e^n\rfloor\\$)

Required inputs to match are 0,1,2,3,4.

Try it online!
> 1 votes

# Answer
# Husk, 5 bytes (cracked by Jonathan Allan)

This one is A000030 shifted by \\$16\\$:

```
←d+16

```

Try it online!

The sequence is 0-indexed, output for \\$ 0 \leq n \< 23 \\$:

$$ 1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3 $$

### Explanation

```
←d+16  -- example input:  23
  +16  -- add 16:         39
 d     -- digits:         [3,9]
←      -- extract first:  3

```

### Solution

> `LdΣ`
> 1 votes

# Answer
# JavaScript, 25 bytes (Cracked 21 bytes)

```
f=
x=>[7,11,12,13,13][x]||14

for(i=0;i<15;i++)
  console.log(i+"->"+f(i))
```

Sequence of 7,11,12,13,13 followed by infinite 14s.

Intended solution 22 bytes:

> x=Math.atan(x+1)\*10|0

Try it online!
> 1 votes

# Answer
# JavaScript, 22 bytes (Cracked)

```
f=
x=>(3-(5/63)**.5)**x|1

for(y=0;y<16;y++)
  console.log(y +"->"+f(y))
```

This is 0 indexed and accuracy is required up to an input of 15. It can not be found on OEIS

My solution 20 bytes

> x=\>163\**(32\*x/163)|1

Try it online!
> 0 votes

# Answer
# \>\<\>, 42 bytes, cracked

```
i3%0v
642 .
840
789
159
a 1
v<<
n
l
?
\/
;

```

Try it online!

Sequence to crack (0-indexed): `101786, 5844, 19902` (not on OEIS).

Intended solution, for reference.
> 0 votes

# Answer
# Pascal (FPC), 86 bytes (cracked)

```
var n:word;begin read(n);write(n div 2+n div 4+n div 8+n div 16+n div 32+n div 64)end.

```

Try it online!

The sequence must be equal up to \\$n=120\\$. The sequence from input 0 to input 120 is

```
0   0   1   1   3   3   4   4   7   7   8   8  10  10  11  11  15  15  16  16  18  18  19  19  22  22  23  23  25  25  26  26  31  31  32  32  34  34  35  35  38  38  39  39  41  41  42  42  46  46  47  47  49  49  50  50  53  53  54  54  56  56  57  57  63  63  64  64  66  66  67  67  70  70  71  71  73  73  74  74  78  78  79  79  81  81  82  82  85  85  86  86  88  88  89  89  94  94  95  95  97  97  98  98 101 101 102 102 104 104 105 105 109 109 110 110 112 112 113 113 116

```

---

My original solution was
> `var n,i,s:word;begin read(n);i:=2;repeat s:=s+n div i;i:=i*2until i>n;write(s)end.`

but r\_64 made it even better!
> 0 votes

# Answer
# Perl 6, 53 bytes

```
{(1,2,2,{$!=++$;prepend(@,2-$!%2 xx$_).pop}...*)[$_]}

```

Try it online!

Anonymous code-block that returns the 0-indexed Kolakoski sequence (OEIS A000002). Solutions are required to match the first 130 elements, so that for some `n > 129` it differs from the Kolakoski sequence.
> 0 votes

---
Tags: code-golf, sequence, cops-and-robbers
---


title: How many bytes is it

text:
# Question
Title: How many bytes is it
This time, we want render the count of bytes in a human readable way to user. Let's write a program (a full one or a function or other acceptable formats) to do this.

## Input

An non-negative integer, in range \\$0\leq n\<2^{31}\\$, which means n bytes.

## Output

A string, the human friendly representation of n bytes.

## Convention

* If n is less than 1000, add `B` after n and output; otherwise...
* Convert to a number less than 1000, plus one of these units: KiB, MiB, GiB; round the number to 3 figures
* For more details of conversion, check out these testcases

## Testcases

```
0 -> 0B
1 -> 1B
42 -> 42B
999 -> 999B
1000 -> 0.98KiB
1024 -> 1.00KiB
2018 -> 1.97KiB
10086 -> 9.85KiB
100010 -> 97.7KiB
456789 -> 446KiB
20080705 -> 19.2MiB
954437177 -> 910MiB
1084587701 -> 1.01GiB
1207959551 -> 1.12GiB
2147483647 -> 2.00GiB

```

# Rules

* This is , so shortest bytes win
* Standard loopholes forbidden
* You should output exactly the same to the testcase:
    + No white space or other symbols between number and units;
    + Use `KiB`, not `KB`, `kib`, or `kb`;
    + Leading or trailing white spaces are optional

# Answer
> 4 votes
## JavaScript (ES6), ~~78~~ 74 bytes

```
f=(n,i)=>n<999.5?i?n.toPrecision(n<1^3)+' KMG'[i]+'iB':n+'B':f(n/1024,-~i)
```

```
<input oninput=o.textContent=f(this.value)><pre id=o>
```

Edit: Saved 4 bytes thanks to @Arnauld.

# Answer
> 2 votes
# Python3, 90 bytes

## (~~76~~ 70 bytes 3-most-significant-digits version)

```
h=lambda v,u=0:v>999.4and h(v/1024,u+2)or"%.*f%sB"%(u and(v<10)+(v<100),v,"KiMiGi"[u-2:u])

```

Version whose outputs are strictly adherent to test cases and author's suggestions.

```
list(map(lambda v: print("{} --> {}".format(v, h(v))), (0, 1, 42, 999, 1000, 124, 2018, 10086, 100010, 456789, 20080705, 954437177, 1084587701, 1207959551, 2147483647, 1023079)))

0 --> 0B
1 --> 1B
42 --> 42B
999 --> 999B
1000 --> 0.98KiB
1024 --> 1.00KiB
2018 --> 1.97KiB
10086 --> 9.85KiB
100010 --> 97.7KiB
456789 --> 446KiB
20080705 --> 19.2MiB
954437177 --> 910MiB
1084587701 --> 1.01GiB
1207959551 --> 1.12GiB
2147483647 --> 2.00GiB
1023079 --> 999KiB
1023488 --> 0.98MiB
1043333 --> 0.99MiB
1043334 --> 1.00MiB

```

Try it online!

Here, a version that produces the most 3 significant digits for the test cases.

```
h=lambda v,u=0:v<1e3and("%.3G%sB"%(v,"KiMiGi"[u-2:u]))or h(v/1024,u+2)

```

The original test cases:

```
list(map(lambda v: print("{} --> {}".format(v, h(v))), (0, 1, 42, 999, 1000, 124, 2018, 10086, 100010, 456789, 20080705, 954437177, 1084587701, 1207959551, 2147483647)))

0 --> 0B
1 --> 1B
42 --> 42B
999 --> 999B
1000 --> 0.977KiB
124 --> 124B
2018 --> 1.97KiB
10086 --> 9.85KiB
100010 --> 97.7KiB
456789 --> 446KiB
20080705 --> 19.2MiB
954437177 --> 910MiB
1084587701 --> 1.01GiB
1207959551 --> 1.12GiB
2147483647 --> 2GiB

```

Try it online!

# Answer
> 2 votes
# C (gcc), ~~108~~ 102 bytes

Works as Yimin Rong suggests.

```
f(float i){char*a="GiMiKi"+6;while(i>=999.5)i/=1024,a-=2;printf("%.*f%.2sB",*a&i<100?i<10?2:1:0,i,a);}

```

Try it online!

Unglofed

```
f(float i){
    char*a="GiMiKi"+6;
    while(i>=999.5)
        i/=1024,a-=2;
    printf("%.*f%.2sB",*a&i<100?i<10?2:1:0,i,a);
}

```

# C (gcc), ~~108~~ ~~101~~ 99 bytes

Works as O.O.Balance suggests.

```
f(float i){char*a="GiMiKi"+6;while(i>999)i/=1024,a-=2;printf("%.*f%.2sB",*a&i<100?i<10?2:1:0,i,a);}

```

Try it online!

Unglofed

```
f(float i){
    char*a="GiMiKi"+6;
    while(i>999)
        i/=1024,a-=2;
    printf("%.*f%.2sB",*a&i<100?i<10?2:1:0,i,a);
}

```

# Answer
> 1 votes
# Java 8, ~~130~~ ~~112~~ 108 bytes

```
n->n<1e3?n+"B":"".format("%.3G"+(n<1e9?n<1e6?"K":"M":"G")+"iB",n<1e9?n<1e6?n/1024.:n/1048576.:n/1073741824.)

```

Uses 3 *significant* figures, as per the original challenge. Try it online here.

Thanks to Jakob for golfing 4 bytes.

Ungolfed:

```
n -> // lambda
n < 1e3 // special case: number of bytes is < 1000
    ? n + "B" // output the number of bytes
    : "".format("%.3G" // otherwise output 3 significant digits
    + (n < 1e9 // if it's less than 1 billion bytes
        ? n < 1e6 // and it's less than a million bytes
            ? "K" // output kibibytes
            : "M" // else output mebibytes
        : "G") // else output gibibytes
        + "iB", // common suffix
        n < 1e9 // if it's less than 1 billion bytes
            ? n < 1e6 // if it's less than 1 million bytes
                ? n/1024.     // convert to kibibytes
                : n/1048576.  // else convert to mebibytes
            : n/1073741824. ) // else convert to gibibytes

```

# Answer
> 1 votes
# APL (Dyalog Classic), 60 bytes

```
{'BKMGi'[i,4 0/⍨×i],⍨v⍕⍨(3-≢⍕⌊v←⍵÷i⊃p)××i←⍵+.≥1e3×p←1024*⍳4}

```

Try it online!

# Answer
> 1 votes
# Rust, 275 bytes

```
fn h(n:u32)->String{let i=[(30,"Gi"),(20,"Mi"),(10,"Ki"),(0,"")].iter().map(|x| (n as f32/2f32.powi(x.0),x.1)).filter(|y| y.0<999.5).last().unwrap();format!("{}{}B",if n<1000{format!("{}",n)}else{format!("{:.4}",format!("{:.2}",i.0)).trim_right_matches(".").to_string()},i.1)}

```

The basic idea is borrowed from the other answers, but formatting the string to have the proper number of significant digits, not have trailing decimal points, and not have numbers like 423.78 takes over half of the code... and it still rounds wrong (19.1 should be 19.2)

# Answer
> 1 votes
# Stax, 34 bytes

```
ì▌╚ƒ░¿n↕─.êN┴▀m▌@àΔ*¡I⌠'}¿Äüz♥∞└6]

```

Run and debug it

Writing this, I ran into a bug in stax's log10 operation. Log10 of 1000 yields `2.9999....`, which is particularly unhelpful for this challenge. I ended up using string length instead. Unpacked, ungolfed, and commented, it looks like this.

```
Vk<             is input less than 1000?
{               start block one
  yp'BP         print input followed by "B"
}               end block one
{               start block two
  x             push input as number
  y%v3/X        push (len(input) - 1) / 3, and store in the X register
  A*|2          multiply by 10, then get calculate two-power
  :_2j          floating point division, rounded to 2 places as a string
  p             print without trailing newline
  "GKM"x@.iB+P  use x register to index into "GKM" string, then concat "ib" and print
}               end block two
?               if-else based on initial condition

```

Run this one

# Answer
> 0 votes
# Python 3, ~~87~~ ~~81~~ ~~80~~ bytes

```
def f(n):
 for u in'','Ki','Mi','Gi':
  if n<1e3:return"%.3G%sB"%(n,u)
  n/=1024

```

Try it online!

**This does not work, I will need to think about how to fix it.**

-6 bytes from Jo King

-1 bytes from Stewie Griffin

# Answer
> 0 votes
# C, 154 ~~165~~ ~~191~~ ~~189~~ bytes (full program)

Big thanks to O.O.Balance and l4m2 for suggestions and providing this TIO and this TIO!

```
double atof(),x;main(i,v)char**v;{x=atof(*++v);if(x<1e3)printf("%sB",*v);else{for(;x>=999.5;++i)x/=1024;printf("%.*f%ciB",2-(int)log10(x),x,"KMG"[i-3]);}}

```

Save as `doit.c`, compile using `gcc -o doit doit.c -lm`, and run:

```
> ./doit 1000
0.98KiB

```

Test cases:

```
> for i in 0 1 42 999 1000 1024 2018 10086 100010 456789 1023079 1023488 20080705 954437177 1084587701 1207959551 2147483647 ; do ./doit $i ; echo; done
0B
1B
42B
999B
0.98KiB
1.00KiB
1.97KiB
9.85KiB
97.7KiB
446KiB
999KiB
0.98MiB
19.2MiB
910MiB
1.01GiB
1.12GiB
2.00GiB

```

# Answer
> 0 votes
# C (gcc), 135 bytes

```
e;double atof(),x;main(i,v)int**v;{for(x=atof(*++v);x>=999.5;e++)x/=1024;printf(e?"%.*f%ciB":"%.*fB",e?2-(int)log10(x):0,x,".KMG"[e]);}

```

Try it online!

Quite change from Yimin Rong's solution

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


title: Reducing a Python Script

text:
# Question
Title: Reducing a Python Script
Does anyone have any suggestions as to how I could shorten this program?

```
_=map(ord,raw_input());_=[10if y==88else 0if y==45else 58-_[x-1]if y==47else y-48for x,y in enumerate(_)];t=0;exec('t+=sum(_[:2+(_[0]+_[1]>=10)]);_=_[2-(_[0]==10):];'*10);print t

```

Run it online

I'd like to write a bowling calculator. I'm fairly proficient in python so I chose that language.

The trick is that the input string is made up of frames not split by white-space and the spares, strikes, and misses are marked by `/`, `X`, and `-` respectively. (note that there are no `0` in the code, `-` is used instead)

Here is an example line `X7/9-X-88/-6XXX81`, this line would have a score of `167`.

As you can see, most of my characters are spent on mapping these special characters to their actual bowl scores. I do this by taking their `ord` values and then replacing the `X` and `-` with `10` and `0` respectively. I then find the `/` rolls and set their value as ten minus the previous roll.

After this, I calculate the final game score by looping over 10 frames (the size of a line of bowling), chunking the line array based on if the frame was a strike spare or normal roll, and then reducing the array going forward.

I feel like this is the best way to perform this challenge as a golf challenge, but I'm not sure if I'm reducing it enough.

# Answer
> 5 votes
# 1.

The portion `2+(_[0]+_[1]>=10)` could be rewritten as `2+(_[0]+_[1]>9)` to save two bytes. In a similar vein `2-(_[0]==10)` can be rewritten as `2-(_[0]>9)`, since `10` is the only possible value greater than `9`.

```
a=map(ord,raw_input());a=[10if y==88else 0if y==45else 58-a[x-1]if y==47else y-48for x,y in enumerate(a)]
t=0;exec('t+=sum(a[:2+(a[0]+a[1]>9)]);a=a[2-(a[0]>9):];'*10);print t

```

Try it online!

(I also renamed `_` to `a`, because even though it's code-golf we don't have to make it unreadable)

# 2.

You can also use a dictionary instead of conditionals to saves some bytes.

```
a=raw_input();a=[{y:ord(y)-48,'X':10,'-':0,'/':58-ord(a[x-1])}[y]for x,y in enumerate(a)]
t=0;exec('t+=sum(a[:2+(a[0]+a[1]>9)]);a=a[2-(a[0]>9):];'*10);print t

```

Try it online!

# 3.

Don't `enumerate`. `enumerate` tends to be too long for it's own good. Here you want to get the last character, which can better be acheived with a `zip`.

```
a=raw_input();a=[{y:ord(y)-48,'X':10,'-':0,'/':58-ord(x)}[y]for x,y in zip('-'+a,a)]
t=0;exec('t+=sum(a[:2+(a[0]+a[1]>9)]);a=a[2-(a[0]>9):];'*10);print t

```

Try it online!

---

If you combine this with @user202729's two tips you get 149 bytes.

```
a=raw_input();a=[[10,0,58-ord(x),ord(y)-48]['X-/'.find(y)]for x,y in zip('-'+a,a)]
t=0;exec't+=sum(a[:2+(a[0]+a[1]>9)]);a=a[2-(a[0]>9):];'*10;print t

```

Try it online!

---

Here's another version that is also 149 bytes:

```
a=raw_input();a=[['-123456789X'.find(y),58-ord(x)][y=='/']for x,y in zip('-'+a,a)]
t=0;exec't+=sum(a[:2+(a[0]+a[1]>9)]);a=a[2-(a[0]>9):];'*10;print t

```

Try it online!

# Answer
> 3 votes
# Shorten the conditional using `str.find`

Compare:

```
Mine:        [10,0,58-_[x-1],y-48]['X-/'.find(chr(y))]
Mine (char): [10,0,58-ord(a[x-1]),ord(y)-48]['X-/'.find(y)]
WW's:        {y:ord(y)-48,'X':10,'-':0,'/':58-ord(a[x-1])}[y]
Original:    10if y==88else 0if y==45else 58-_[x-1]if y==47else y-48

```

# Answer
> 3 votes
# 146 bytes

Based on Cat Wizard's "another version".

Basically I include `/` into the string so `find` returns `0` (falsy value), then use `or` to replace that `0` with the desired result.

```
a=raw_input();a=[('/-123456789X'.find(y)or 59-ord(x))-1for x,y in zip('-'+a,a)]
t=0;exec't+=sum(a[:2+(a[0]+a[1]>9)]);a=a[2-(a[0]>9):];'*10;print t

```

Try it online!

Explanation: `x or y` == `x if x else y`. So:

```
   '/-123456789X'.find(y)or 59-ord(x)
== '/-123456789X'.find(y) if '/-123456789X'.find(y) else 59-ord(x)
== '/-123456789X'.find(y) if '/-123456789X'.find(y) != 0 else 59-ord(x)
== '/-123456789X'.find(y) if y != '/' else 59-ord(x)

```

# Answer
> 2 votes
# Remove `()` around parameter of `exec`

`exec` is a command, not a function. This saves 2 bytes.

# Answer
> 1 votes
Is there a reason why you need to use `raw_input()` and not replace it with `input()` and wrap the input string in quotes e.g. "X7/9-X-88/-6XXX81"? That would save 4.

---
Tags: code-golf, tips, python
---


title: Make a program that prints its own size

text:
# Question
Title: Make a program that prints its own size
**Challenge:** Create a program that prints out the size of its own source code file.

For example, a 35 bytes size of program must print out 35. **Pre-calculation** is not valid. What I mean by pre-calculation is:

```
 // test.js -> its size is 15 byte
 console.log(15)

```

**It must dynamically calculate the size of own source code file.** The winner is who prints the minimum number , same as who has the minimum size of code.

# Answer
# APL (Dyalog Unicode), 10 bytesSBCS

```
≢⊃⌽⎕NR⊃⎕SI

```

Try it online! Prints 11 because TIO's APL is set up to auto-format the code, but on a system where this isn't the case, it prints 10:

`⎕SI`**S**tate **I**ndicator (list of all functions on the stack)

pick the first one (i.e. the currently running function)

`⎕NR`**N**ested **R**epresentation (one character list per line)

reverse (to bring the actual code line to the front)

pick the first (i.e. the code line)

tally the characters of that
> 2 votes

# Answer
# Python 3, 32 bytes

Not much to say really, opens the file and checks the length of its contents as a string.

```
print(len([*open(__file__)][0]))

```

There might be something shorter but I couldn't think of it.

*Edit: Try it Online! (stolen from the comments - thanks for the reminder!)*
> 0 votes

# Answer
# JavaScript (Node.js), ~~40~~ 20 bytes

*-20 thanks to @Shaggy*

```
f=_=>("f="+f).length

```

```
f=_=>("f="+f).length

alert(f())
```
> 0 votes

---
Tags: code-golf, self-referential
---


title: Pocket Pokemon Type Evaluator

text:
# Question
Title: Pocket Pokemon Type Evaluator
Yes, I know there are already three pokemon type questions, but almost all submissions hardcode the whole chart in one way or other. I think it'd be nice to change the requirement a bit to encourage more shortcut-taking typically seen in decision problems.

# Objective

Write a program/function/whatever that accepts the attacking type and the defending type(s), and output something that can be identified as the final multiplier.

As usual, you can see the pokemon type chart here. Also available as text form (copied from another question linked above and modified a bit):

```
                                            Attacking Type
                No  Fi  Fl  Po  Gr  Ro  Bu  Gh  St  Fr  Wa  Gr  El  Ps  Ic  Dr  Da  Fa
    Normal        1   2   1   1   1   1   1   0   1   1   1   1   1   1   1   1   1   1
    Fighting      1   1   2   1   1 0.5 0.5   1   1   1   1   1   1   2   1   1 0.5   2
D   Flying        1 0.5   1   1   0   2 0.5   1   1   1   1 0.5   2   1   2   1   1   1
e   Poison        1 0.5   1 0.5   2   1 0.5   1   1   1   1 0.5   1   2   1   1   1 0.5
f   Ground        1   1   1 0.5   1 0.5   1   1   1   1   2   2   0   1   2   1   1   1
e   Rock        0.5   2 0.5 0.5   2   1   1   1   2 0.5   2   2   1   1   1   1   1   1
n   Bug           1 0.5   2   1 0.5   2   1   1   1   2   1 0.5   1   1   1   1   1   1
d   Ghost         0   0   1 0.5   1   1 0.5   2   1   1   1   1   1   1   1   1   2   1
i   Steel       0.5   2 0.5   0   2 0.5 0.5   1 0.5   2   1 0.5   1 0.5 0.5 0.5   1 0.5
n   Fire          1   1   1   1   2   2 0.5   1 0.5 0.5   2 0.5   1   1 0.5   1   1 0.5
g   Water         1   1   1   1   1   1   1   1 0.5 0.5 0.5   2   2   1 0.5   1   1   1
    Grass         1   1   2   2 0.5   1   2   1   1   2 0.5 0.5 0.5   1   2   1   1   1
T   Electric      1   1 0.5   1   2   1   1   1 0.5   1   1   1 0.5   1   1   1   1   1
y   Psychic       1 0.5   1   1   1   1   2   2   1   1   1   1   1 0.5   1   1   2   1
p   Ice           1   2   1   1   1   2   1   1   2   2   1   1   1   1 0.5   1   1   1
e   Dragon        1   1   1   1   1   1   1   1   1 0.5 0.5 0.5 0.5   1   2   2   1   2
    Dark          1   2   1   1   1   1   2 0.5   1   1   1   1   1   0   1   1 0.5   2
    Fairy         1 0.5   1   2   1   1 0.5   1   2   1   1   1   1   1   1   0 0.5   1

```

You can choose to either accept one or two defending types (the final multiplier for two defending types is just the product of all individual defending types). Both types of submissions are allowed, as they will be in separate categories.

# Rules

You can choose any methods of input in any form, structure or order (e.g `['fire',['water','rock']]`/`['fire',['rock']]`/`['fire','rock']`, `'water,ice,ghost'`/`'water,ghost'`,`dragondragonsteel`/`dragondragon`).

The only requirement is that the types being inputted must be exactly their names and nothing else. Moreover, the types are required to be in *one* case only: so if you choose "psychic/Psychic/PSYCHIC", you must also use the same case for every other types (e.g "poison/Poison/POISON"). The available casing are: all lowercase, capital case and all uppercase.

You can output anything as long as different multipliers corresponds to one and only one output value.

There will not be two defensive types of the same type.

Standard loopholes are disallowed.

Shortest byte wins.

# Answer
# JavaScript (ES6), ~~270~~ ~~246~~ 221 bytes

Takes input in currying syntax `(a)(d)` where ***a*** is the attacking type as a string and ***d*** are the defending type(s) as an array of strings. The case doesn't matter.

Returns a standard multiplier as a float.

```
a=>d=>d.map(d=>r*='0124'["ijfkj{jjnjjJ[kefjiZj[jxnjni^YnEW]vfeziiz]okjZmniV{oZvjhjnmj[zrfijij[yVzej[jjejjhujkmjZkZ[fjiuznjjz~zjfRjbkjy".charCodeAt((i=g(d)*18+g(a))/3)>>i%3*2&3]/2,g=s=>parseInt(s,36)*64%97%54%21%18,r=1)&&r

```

Try it online! or check the whole chart

### How?

The base-36 interpretation \\$N\\$ of a given Pokemon type string is converted to a coordinate \\$C\\$ in \\$\[0..17\]\\$ using the following minimal perfect hash function:

$$C=((((N\times64)\bmod97)\bmod54)\bmod21)\bmod18$$

The chart is rearranged using the new coordinates and encoded as a single string with 6 bits of payload data per character, using ASCII codes in the range \\$\[64..127\]\\$.

There are 2 bits per cell, so the length of the string is \\$(18\times18\times2)/6=108\\$ characters.

For the curious, here is the code that encodes the string.
> 3 votes

# Answer
# Python 2, 305 bytes

```
def f(l):d=[int(t[2:],36)%123%28%21for t in l];return reduce(lambda x,y:x*int("eJx1UIENwDAIekkM/982FW3skprUzA4oCHe6O6Jb9F05XXeATlDIouUndGLGRUYxTDD6o0YlhSmh/adnW7o8DzS6O9PWAmM9WnbLssktWgLjoNG1iwAw/RM4DqCIaZH3mv6l5MkF22fKKp6Vxtnji05OrsnADjaX+AByt1Y8".decode('base64').decode('zip')[d[0]*21:][y])/2.,d[1:],1)

```

Try it online!

Also hardcoding the whole matrix..
> 0 votes

# Answer
# C (gcc), 382 363 bytes

I wanted to try something a little different, so I made a sparse array of the values that were not equal to 1 and encoded them in a base-90 format so that the column that they are on could be converted to +/-1.0 and added to a 1.0 multiplier.

Thanks to ceilingcat for the suggestion.

```
*y[]={"8(;","i56n9(q@wyD","j8o;t?","678:)tz","#ln9qr>u","4k7o;rw","456:;<tvyD","!pvC","n;<=?wz","8oq<=twB","mnr=>B","56mn9;<s>B","k%s>?B","jl;@1","km;<=tAx",";x2","4pvCD","j6;<xy"};i,j;float f(int**s){int k[3]={};float f=1;for(i=18;i--;)for(j=3;j--;s[j]&&!strcmp(z[i],s[j])?k[j]=i:0);for(char*t=y[*k];i=*t-33,*t++;)for(j=0;++j<3;)f*=i%18-k[j]?1:i/18/2.;return f;}

```

Try it online!
> 0 votes

# Answer
## ABAP, 691 bytes

### Form-Subroutine taking two or three types in capital case

```
DATA:x(180) TYPE x,v type x,b,c.DEFINE g.GET BIT:&1 + 1 OF &2 INTO b,&1 + 2 OF &2 INTO c.SET BIT:7 of v TO b,8 of v TO c.IF v = 3.o = 2.ELSE.o = v / 2.ENDIF. END-OF-DEFINITION.
DEFINE f.FIND &1(3) IN'NorFigFlyPoiGroRocBugGhoSteFrrWatGraElePsyIceDraDarFai'RESULTS data(&2). END-OF-DEFINITION.
FORM f USING a d e.DATA(o) ='1.00'.x ='BAA8AAAAA0AE96AABA709A36A9EEA099E6A9BA90A99AAF2EA075EADFAAA09E7AB9AAA009A7AAAAE074D6799590AAF65DA690AAAA57E6A0AF6EB56EA0A6EA6A6AA09AAFAA9AE0BABAFAA6A0AAAA956FB0BAADAA8A709BA6EAA860'.f:a
r,d s.DATA(l) = r-offset / 3 * 2.DATA(n) = o.IF strlen( e ) > 2.f e t.n = ( t-offset / 3 ) * 5.g l x+n.n = o.ENDIF.o = ( s-offset / 3 ) * 5.g l x+o.o = o * n.WRITE o.ENDFORM.

```

Newlines in the code replace required spaces around the `END-OF-DEFINITION` keywords. Might as well keep it as "readable" as possible.

Can be called by another program like so:

```
REPORT z.
 PERFORM f USING 'Fighting' 'Normal' 'Rock'.

```

Result: `4`

```
REPORT z.
 PERFORM f USING 'Ghost' 'Normal' ''.

```

Result: `0`

```
REPORT z.
 PERFORM f USING 'Fairy' 'Poison' 'Normal'.

```

Result: `0.5`

## Explanation

Geez, what a monster. Far from competitive as per usual, but I learned a lot about handling bits and bytes in ABAP - or rather that I don't want to do it ever again.

The type weakness table was converted to bit pairs:
`00 = 0x`, `01 = 0.5x`, `10 = 1x`, `11 = 2x`
Each row of the table was then converted to 5 bytes each and all concatenated into one 180 character long byte-like string, which is hard coded into the program obviously.

The bytes for each row are padded with a trailing zero because ABAP doesn't work with half a byte offsets - or at least I couldn't get it to work properly. I couldn't use a higher number base either (like base-64) due to how ABAP handles them and how complicated and lengthy it gets to do so. Also dealing with overflows. Meh.

```
DATA:                "Multiple declarations
  x(180) TYPE x,     "Byte-like string of length 180, holds the type weakness table
  v      TYPE x,     "One byte
  b, c.              "One letter chars for saving the values of bits (implicit char -> number conversion)

DEFINE g.  "Define a macro for reading two bits, we need this multiple times
  GET BIT: "Get bits from the hex encoded weakness table; index starts at 1
    &1 + 1 OF &2 INTO b, "get bit 1 ==> offset + 1
    &1 + 2 OF &2 INTO c. "get bit 2 ==> offset + 2

    SET BIT: "Unfortunately this is the best way of copying over bits (that I am aware of) to another value. Sets the two least significant bits so we get a value between 0 and 3.
     7 of v TO b, "Set result bit 1
     8 of v TO c. "Set result bit 2

    "This is the best I could come up with.
    IF v = 3. "If it's a binary 11 (3 in base10)
      o = 2.  "then it's double damage
    ELSE.  "For everything else the bit's base10 value can simply be halved, as 0/2=0, 1/2 =.5, 2/2=1.
      o = v / 2.
    ENDIF.
END-OF-DEFINITION. "End of macro bits

DEFINE f. "Define macro for finding the column/row of types in the weaknesses table both horizontally or vertically
  "Find first occurrence of the first three letters of the type and save the result to a newly initialized variable
  FIND &1(3) IN 'NorFigFlyPoiGroRocBugGhoSteFrrWatGraElePsyIceDraDarFai' RESULTS data(&2).
END-OF-DEFINITION. "End of macro types

FORM f USING a d e. "This subroutine has three parameters: [a]ttack, [d]efender primary, d[e]fender secondary
  DATA(o) ='1.00'. "Quick declaration of a number with 2 decimals

  "The type weakness table, encoded as binary, written in hexadecimal.
  "Each table row corresponds to 4.5 bytes = 36 bits, padded with half a byte of 0's => 40 bits = 5 bytes = 10 characters each
  x ='BAA8AAAAA0AE96AABA709A36A9EEA099E6A9BA90A99AAF2EA075EADFAAA09E7AB9AAA009A7AAAAE074D6799590AAF65DA690AAAA57E6A0AF6EB56EA0A6EA6A6AA09AAFAA9AE0BABAFAA6A0AAAA956FB0BAADAA8A709BA6EAA860'.

  f:a r,d s. "Call type index macro for the attack and primary defender type, saves the result in r (for attacker) and s (for defender)
  DATA(l) = r-offset / 3 * 2. "Find the attacker's "table column". Each column is 2 bits wide, but type abbreviations are 3 letters

  DATA(n) = o. "Result of the secondary defender's type weakness will be saved here; default (if no type is given) = 1x from o's default value

  IF strlen( e ) > 2. "When there was a secondary type given (length of type name > 2 characters)
    f e t. "Call type index macro for the secondary defender type.
    n = ( t-offset / 3 ) * 5. "Divide offset by 3 because abbreviations are 3 letters wide, then multiply by 5 to find the correct "table row" (5 bytes per row)
    g l x+n. "Call the bit reading macro; use attacker's column offset in bits and the defender's secondary type's row offset in bytes
    n = o.   "Save the resulting number to n temporarily
  ENDIF.

  o = ( s-offset / 3 ) * 5. "Get primary type's row offset in bytes
  g l x+o. "Call bit reading macro: attacker's column offset (bits), defender's primary row offset (bytes)
  o = o * n. "Multiply weakness by secondary weakness
  WRITE o.   "Print result
ENDFORM. "End of subroutine

```

*Phew*. How's that for some way too verbose code. There might be a better way to do it, but I doubt anyone else is mad enough to try golfing in ABAP. Still, suggestions are welcome, of course!
> 0 votes

---
Tags: code-golf, classification
---