title: TYPOGLYCEMIA - Cna Yuo Raed Tihs?

text:
# Question
Title: TYPOGLYCEMIA - Cna Yuo Raed Tihs?
**What is Typoglycemia?**

Typoglycemia is a term that refers to the phenomenon where readers are able to understand text even when the letters in the middle of words are jumbled, as long as the first and last letters of each word remain in their correct positions. For example,

> Aoccdrnig to a rscheearch at Cmabrigde Uinervtisy, it dseno’t mtaetr in waht oerdr the ltteres in a wrod are, the olny iproamtnt tihng is taht the frsit and lsat ltteer be in the rghit pclae.
>
> The rset can be a taotl mses and you can sitll raed it whotuit a pboerlm.
>
> Tihs is bcuseae the huamn mnid deos not raed ervey lteter by istlef, but the wrod as a wlohe. Azanmig huh? Yaeh, and I awlyas tghuhot slpeling was ipmorantt!

However, in this challenge we will implement a minor variation.

**Typo Injection Rules**

For each sentence, errors will be injected into words longer than four letters. All such words will contain exactly one error. All words with four letters or less will contain no errors.

For example, here are the simple rules applied to this sentence:

```
The boy could not solve the problem so he asked for help.

```

| Rule Number | Description | Example |
| --- | --- | --- |
| 0 | Swap the first two letters of the word. | The boy **oc**uld not **os**lve the **rp**oblem so he **sa**ked for help. |
| 1 | Swap the second and third letters of the word. | The boy c**uo**ld not s**lo**ve the p**or**blem so he a**ks**ed for help. |
| 2 | For even-length words, swap the middle two letters.
For odd-length words, swap the left-of-middle and middle letters. | The boy c**uo**ld not s**lo**ve the pr**bo**lem so he a**ks**ed for help. |
| 3 | Swap the third- and second-to-last letters of the word. | The boy co**lu**d not so**vl**e the prob**el**m so he as**ek**d for help. |
| 4 | Swap the last two letters of the word. | The boy cou**dl** not sol**ev** the probl**me** so he ask**de** for help. |

# Challenge

Input a sentence and start with rule 0 for the first word, regardless of its length. If a word has `four or fewer` letters, skip modifying it but still advance to the next rule when moving to the next word in the sentence. Cycle through the rules 0-4 for each eligible word and repeat the cycle as necessary until the end of the sentence.

**Input**

A sentence.

**Output**

A sentence with each word modified according to the applicable rule.

# Test Cases

**Input**

> The quick brown fox jumps over the lazy dog.

**Output**

> The qiuck borwn fox jumsp over the lazy dog.

---

**Input**

> According to a researcher at Cambridge University, it doesn't matter in what order the letters in a word are, the only important thing is that the first and last letter be at the right place. The rest can be a total mess and you can still read it without problem. This is because the human mind does not read every letter by itself but the word as a whole.

**Output**

> cAcording to a researcehr at aCmbridge Uinversity, it does'nt mattre in what odrer the lettesr in a word are, the only ipmortant tihng is that the frist and last lettre be at the rihgt plac.e The rest can be a ottal mess and you can tsill read it withuot proble.m This is beacuse the humna mind does not read eveyr eltter by iteslf but the word as a whoel.

# Answer
> 3 votes
# Python 3, ~~159~~ ~~156~~ ~~154~~ ~~144~~ 138 bytes

```
def f(t,*R):
 for*C,in t.split():s=len(C);g=s>4;i=g*[2,4,s,-4,-2][len(R)%5]//2-1;C[i],C[i+g]=C[i+g],C[i];R+=''.join(C),
 return' '.join(R)

```

Try it online!

* *-3 bytes* by using a lambda for `g`
* *-2 bytes* by inlining `c`
* *-10 bytes* by removing `g`
* *-6 bytes* by removing the if-statement

---

A function `f` that accepts the sentence as a string and returns the modified sentence as string.

**How does it work?**

Create a empty tuple. At the end, this tuple will be joined to a string and `R`eturned.

Declare a for-loop. Since every iteration adds an element to `R`, the size of `R` equals to the current iteration number, 0-indexed. The loop says:

* for each word in the `t`ext provided as input, transform it into a list of `C`haracters
* get its `s`ize and check if it's `g`reater than 4
    + if it is, get the current rule number (remainder of the division between the current iteration number and 5), retrieve the factor corresponding to that rule (`[2,4,s,-4,-2]`), integer-divide it by 2 (`//2`), subtract one (`-1`), and set `i` to the result
        - for rule 0, it will give \\$\lfloor \frac{2}{2} \rfloor\ - 1 = 1-1=0\\$ (a.k.a. the first letter)
        - for rule 1, it will give \\$\lfloor \frac{4}{2} \rfloor - 1 = 2-1=1\\$ (a.k.a. the second letter)
        - for rule 2, it will give \\$\lfloor \frac{s}{2} \rfloor - 1\\$ (a.k.a. the left-middle letter)
        - for rule 3, it will give \\$\lfloor \frac{-4}{2} \rfloor - 1=-2-1=-3\\$ (a.k.a. the third-to-last latter)
        - for rule 4, it will give \\$\lfloor \frac{-2}{2} \rfloor - 1=-1-1=-2\\$ (a.k.a. the second-to-last latter)
    + otherwise, set `i` to \\$\lfloor \frac{0}{2} \rfloor - 1=0-1=-1\\$
* Swap the letter at index `i` with the letter at index `i+g`. The expression `i+g` evaluates to `i+1` if the size of the word is `g`reater than 4 (i.e. the next letter after `i`), otherwise evaluates to `i` (i.e. the same letter as `i`, equivalent to "do nothing")
* Convert the list of `C`haracters to a string again, and add it to `R`

Join the accumulator to a string and return it.

# Answer
> 4 votes
# Rattle, ~~181~~171 bytes

```
\ |P3II^s0P3[=#+3g`n[^32g1+s1][32g1>4*1[1g2[0g1<^`g>$<sg1>^`]g2[1g1<^`>g>$<s<g1>^`]g2[2g1<^`g1/2>^`g<$>sg1>^`g1/2<^`]g2[3<<g<$>s>>]g2[4<g<$>s>]]=s1g2+%5s2]>]`g0-[=#+3g`b]`

```

Try it Online!

This is not necessarily the shortest this code can get but it's a start.

# Explanation

```
|                           take input ("\ " adds a space)
 P3                         move pointer to slot 3 (slots 0,1,2 will be used differently)
   I                        place all characters from input in consecutive memory slots
    I^                      get length of input
      s0                    save length of input in slot 0
        P3                  set the pointer to 3
          [...]`            loop over each character of the input

```

Inside this main loop, `[^32...]` just increments a counter if the current character is not a space. If the character is a space (`[32...]`), it applies the applicable rule (`[0...]` for rule 0, etc.) then increments the rule counter before resetting the word-length counter.

```
g0[=#+3g`b]`

```

This just reads over each modified character and outputs the final string.

# Answer
> 3 votes
# Perl 5 \+ `-040plF`, 60 bytes

```
@F>4&&s;^.{@{[(@F-2,0,1,0|@F/2-1,@F-3)[$.%5]]}}\K(.)(.);$2$1
```

Try it online!

## Explanation

First the flags: `-040` (in combination with the implied `-n` from `-p`) splits input strings on space and runs the code for each, `-p` implies `-n` (which reads input automatically and stores in `$_`) and `-p`rints out `$_` at the end of the script, `-l` strips off the space for processing and adds it back on when `print`ing, and `-F` splits the string so that each char of the input is stored in `@F`.

If `@F` contains more than 4 elements (i.e. the string is longer than 4 chars) run a `s;`ubstituion on `$_` swapping the next two chars after the first `n` (e.g `s/.{n}(.)(.)/$2$1/`), where `n` is defined using an inline array, indexed using `$.` (which is the current "line" of input, which since we're using space to split our "lines" is the, 1-indexed, word we're working on) modulo `5`. The values of `n` are `0` (first two chars), `1` (second and third), `0|@F/2-1` (the middle two, or left-most of middle and middle), `@F-3` (the first two of the last three), `@F-2` (the last two), but the list is shifted by one as we need to account for the 1-indexed count. The `s///`ubstitution is delimited by `;` so that we can use the implied `;` from the `while ($_ = <STDIN>) {`...`;}` produced by `-n`.

# Answer
> 2 votes
# C (gcc), 240 bytes

```
#include <string.h>
a,b,l,r;f(char*s){r=0;char*w=strtok(s," ");while(w){l=strlen(w);if(l>4){a=r==0?0:r==1?1:r==2?l/2:r==3?l-3:l-2;b=r<2?a+1:r==2?l/2-1:r==3?l-2:l-1;w[a]^=w[b];w[b]^=w[a];w[a]^=w[b];}printf("%s ",w);w=strtok(0," ");r=-~r%5;}}

```

Try it online!

**How it works?**

Nothing too magical here but the main gist is

* Split the sentence into words. (space delimited)
* Perform an XOR swap of the two characters without using a temporary variable.

---

**Output**

> The qiuck borwn fox jumsp over the lazy dog.
>
> cAcording to a researcehr at aCmbridge Uinversity, it does'nt mattre in what odrer the lettesr in a word are, the only ipmortant tihng is that the frist and last lettre be at the rihgt plac.e The rest can be a ottal mess and you can tsill read it withuot proble.m This is beacuse the humna mind does not read eveyr eltter by iteslf but the word as a whoel.

# Answer
> 2 votes
# Perl 5 `-p`, 118 bytes

```
s|\S+|$p=("..",'.\K..',"."x(($z=length$&)/2-1).'\K..','..(?=.$)','..$')[$i++%5];$z>4?$&=~s;$p;reverse$&=~/./g;er:$&|ge

```

Try it online!

# Answer
> 2 votes
# Uiua SBCS, ~~59~~ 57 bytes

```
/$"_ _"≡⊔(□(◌|⍜⊏⇌)>4⧻,⊟+1.(0|1|-1⌊÷2⧻.|¯3|¯2))◿5⇡⧻.⊜□≠@ .

```

Try it!

# Answer
> 2 votes
# 05AB1E, 39 bytes

```
#εDg©4›i1Ý2L®;D<‚®3-D>‚D>)ćDrNè©è®Rǝ]ðý

```

Try it online.

**Explanation:**

```
#                   # Split the (implicit) input-sentence on spaces
 ε                  # Map over each word:
  D                 #  Duplicate the current word
   g                #  Pop the copy, and push its length
    ©               #  Store this length in variable `®` (without popping)
     4›i            #  If the length is larger than 4:
        1Ý          #   Push [0,1]
        2L          #   Push [1,2]
        ®;          #   Push halve the length
          D<        #   Duplicate it, and decrease it by 1
            ‚       #   Pair the two together: [length/2,length/2-1]
        ®3-         #   Push the length-3
           D>       #   Duplicate, and increase it by 1
             ‚      #   Pair the two together: [length-3,length-2]
        D           #   Duplicate the pair
         >          #   Increase both values in the copy by 1: [length-2,length-1]
        )           #   Wrap all values on the stack into a list
         ć          #   Extract the head; push first item and remainder-list separately
          D         #   Duplicate the extracted word
           r        #   Reverse the order from pairList,word,word to word,word,pairList
            Nè      #   Modular index the current map-index into the list of pairs
              ©     #   Store this as new variable `®` (without popping)
               è    #   Index into the word to get the pair of characters
                ®   #   Push index-pair `®` again
                 R  #   Reverse it
                  ǝ #   Insert the characters back into the word at those indices
                    #  (implicit else: use the duplicated unmodified word instead)
 ]                  # Close both the if-statement and map
  ðý                # Join it back together with space delimiter
                    # (after which the modified sentence is output implicitly as result)

```

`©è®Rǝ` is taken from my answer for the *Swap Two Values in a List* challenge.

# Answer
> 2 votes
# Bash (GNU sed + tr), ~~188~~ 177 bytes

```
tr \  \\n|sed -E '/.{5}/!b
1~5s/../ & /
2~5s/(.)(..)/\1 \2 /
3~5{s/.+/ & /
:1 s/ (.)(..+)(.) /\1 \2 \3/
t1}
4~5s/(..)(.)$/ \1 \2/
5~5s/..$/ & /
s/ (.)(.)(.?) /\2\1\3/'|tr \\n \

```

Try it online!

* `rt`anslate wrods to liens and back
* Skip sohrt wodrs immediateyl
* Tag traget charcaters for each rule by frmaing them with psaces (use loop to move psaces iwnard from both ends for rule #2)
* Finally swap hcaracters
* Otpionally add `|haed -c-1` to kill traliing spcae (+10 hcars)

# Answer
> 2 votes
# Ruby, ~~94~~ 93 characters

```
->s{i=0;s.gsub(/\S+/){|w|r=[-1,1,2,w.size/2,-2][(i+=1)%5];w[4]&&(w[r],w[r-1]=w[r-1],w[r]);w}}

```

Sample run:

```
irb(main):003:0> ->s{i=0;s.gsub(/\S+/){|w|r=[-1,1,2,w.size/2,-2][(i+=1)%5];w[4]&&(w[r],w[r-1]=w[r-1],w[r]);w}}['The quick brown fox jumps over the lazy dog.']
=> "The qiuck borwn fox jumsp over the lazy dog."

```

Try it online!

# Answer
> 1 votes
# Charcoal, 48 bytes

```
⪫Ｅ⪪Ｓ ⭆⟦⁻⊗§⟦¹¦²÷Ｌι²⁻Ｌι²⊖Ｌι⟧κ›Ｌι⁴⟧⭆ι⎇⊖↔⁻⊗ξλν§ι⁻λξ

```

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

```
⪫Ｅ⪪Ｓ ...

```

Split the input on spaces and map over each word separately.

```
⭆⟦⁻⊗§⟦¹¦²÷Ｌι²⁻Ｌι²⊖Ｌι⟧κ›Ｌι⁴⟧...

```

Get the sum of the positions that need to be swapped. This is twice the upper position minus `1`, except for words that are fewer than five characters long, in which case any even value will do. The upper position is calculated in a similar way to @enzo's Python answer. The resulting value is wrapped in a list and iterated over so that it can be referred to twice in the expression below.

```
⭆ι⎇⊖↔⁻⊗ξλν§ι⁻λξ

```

Map over the characters of the word, swapping the characters at positions `-~x/2` and `~-x/2` (if `x` is odd).

# Answer
> 1 votes
# Retina 0.8.2, 212 bytes

```
S`
((.)(.)(...+)|(.+))((¶.)(.)(.)(..+)|(¶.+))?((¶(?=.{5})(.)+)(.)(.)((?<-14>.)+.?)(?(14)^)|(¶.+))?((¶..+)(.)(.)(.)|(¶.+))?((¶...+)(.)(.)|(¶.+))?
$3$2$4$5$7$9$8$10$11$13$16$15$17$18$20$22$21$23$24$26$28$27$29
¶

```

Try it online! Link includes test cases. This regex is just too ugly to explain, I mean it has 29 capturing groups for goodness sake. So let's move on to the slightly shorter direct Retina 1 port:

```
S`
#5`(.)(.)(...+)|(.+)
$2$1$3$4
(.)(.)(.)(..+)|(.+)
$1$3$2$4$5
(?=.{5})((.)+)(.)(.)((?<-2>.)+.?)(?(2)^)|(.+)
$1$4$3$5$6
(..+)(.)(.)(.)|(.+)
$1$3$2$4$5
(...+)(.)(.)|(.+)
$1$3$2$4
¶

```

Try it online! Link includes test cases. Explanation:

```
S`
¶

```

Split the input string on spaces before processing and finish by joining the words with spaces.

```
#5`

```

Perform each of `5` substitutions in turn. What this does is that after each replacement is made, the next match is performed using the next substitution's regex. This also needs to happen for the short words, which is why the matches all have to include a "default case", plus also they must match the whole word exactly, rather than just the parts of the word being substituted.

```
(.)(.)(...+)|(.+)
$2$1$3$4

```

The 1st, 6th, 11th etc. words have their first two characters exchanged if there are at least three more characters left.

```
(.)(.)(.)(..+)|(.+)
$1$3$2$4$5

```

The 2nd, 7th, 12th etc. words have their second and third characters exchanged if there are at least two more characters left.

```
(?=.{5})((.)+)(.)(.)((?<-2>.)+.?)(?(2)^)|(.+)
$1$4$3$5$6

```

The 3rd, 8th, 13th etc. words have their middle characters exchanged if there are at least five characters in the word. A .NET balancing group is used to ensure that there are at least as many characters after the middle characters as there were before.

```
(..+)(.)(.)(.)|(.+)
$1$3$2$4$5

```

The 4th, 9th, 14th etc. words have their second and third last characters exchanged if they follow at least two characters.

```
(...+)(.)(.)|(.+)
$1$3$2$4

```

The 5th, 10th, 15th etc. words have their last two characters exchanged if they follow at least three characters.

However, Retina 1 can do better than this - you can iterate over every `5`th line starting at the line of your choice using a per-line compound stage with a step limit, like this:

```
S`
,5,%V`^..(?=...)
1,5,%V`(?<=^.)..(?=..)
2,5,%V`(?<=(?=.{5})(.)+)..(?=(?<-1>.)+.?$)(?(1)^)
3,5,%V`(?<=..)..(?=.$)
4,5,%V`(?<=...)..$
¶

```

Try it online! Link includes test cases. Explanation: Here because the step limits on the per-line stages guarantee that the right regex runs on the right lines, we can simply run reVerse stages that match the appropriate characters of each word.

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

```
s=>s.replace(/\S+/g,w=>w[s=++s%5|0,4]?w.slice(0,q=s<2?s:(w.length-2>>2/s)-s%2)+w[q+1]+w[q]+w.slice(q+2):w)

```

Try it online!

### Commented

```
s =>               // s = input string, re-used as the rule counter
s.replace(         // replace in s,
  /\S+/g,          // looking for 'words' (punctuation included)
  w =>             // for each word w in s:
  w[               //
    s = ++s % 5    //   increment the rule counter,
        | 0,       //   or set it to 0 if it's still NaN'ish
    4              //   test the 5th character
  ] ?              //   if the word contains at least 5 characters:
    w.slice(       //     extract the left part:
      0,           //       from 0
      q =          //       to q - 1, where q is defined as:
      s < 2 ?      //         if s < 2:
        s          //           use s (rules 0 and 1)
      :            //         else:
        ( w.length //           use the word length
          - 2      //           minus 2 (default value for rule 4)
          >> 2 / s //           halved and floored if this is rule 2
        ) - s % 2  //           minus 1 if this is rule 3
    ) +            //     end of slice()
    w[q + 1] +     //     \__ followed by the characters at q and q+1,
    w[q] +         //     /   swapped
    w.slice(q + 2) //     followed by the right part
  :                //   else:
    w              //     leave w unchanged
)                  // end of replace()

```

# Answer
> 1 votes
# Jelly, 25 bytes

```
ḲẈ’_‘:¥ṛṠ5ƭ€2!a@>ʋ4‘œ?"ḲK

```

A monadic Link that accepts a list of characters and yields a list of characters reordered as described by the rules.

**Try it online!**

### How?

Swapping the \\$i^{\text{th}}\\$ and \\$(i+1)^{\text{th}}\\$ characters of a length \\$N\\$ string gives the \\$((N-i)!+1)^{\text{th}}\\$ permutation of the string in a list of all permutations of that string ordered by the original characters' indices. The code calculates these indices, forces the values for short words to \\$1\\$, and then uses the `œ?` atom to calculate the required permutations of each word.

```
ḲẈ’_‘:¥ṛṠ5ƭ€2!a@>ʋ4‘œ?"ḲK - Link: list of characters, Text
Ḳ                         - {Text} split at spaces
 Ẉ                        - {that} length of each -> Sizes
                 ʋ4       - last four links as a dyad - f(Sizes, 4):
           €              -   for each {Size in Sizes}:
         5ƭ 2             -     apply the last five links in turn - f(Size, 2):
  ’                       -       {Size} decrement        -> (R0): Size - 1
   _                      -       {Size} subtract {2}     -> (R1): Size - 2
      ¥                   -       last two links as a dyad - f(Size, 2):
    ‘                     -         {Size} increment
     :                    -         integer divide by {2} -> (R2): (Size + 1) div 2
       ṛ                  -       right argument          -> (R3): 2
        Ṡ                 -       {Size} sign             -> (R4): 1
                                 -> N-i from the description above this code-block
             !            -   {that} factorial (vectorises)
                >         -   {Size} greater than {4}?
               @          -   with swapped arguments:
              a           -     {isLong} logical AND {the factorial} (vectorises)
                               -> replaces the factorial with 0 when Size<5
                   ‘      - increment (vectorises) -> WordPermValues
                       Ḳ  - {Text} split at spaces -> Words
                      "   - zip with:
                    œ?    -   permutation at index {WordPermValue} of {Word}
                        K - {that} joined with spaces

```

# Answer
> 1 votes
# , ~~61~~ 60 bytes

```
;:inv@(A.&.>~[:(<@0 1|:4&<*#!@$1,~2,~>.@-:,~1 2-~/])#&>)&cut

```

Try it online!

`'The quick brown fox jumps over the lazy dog.'`, eg:

* `&cut` Chop input into boxed words:

```
┌───┬─────┬─────┬───┬─────┬────┬───┬────┬────┐
│The│quick│brown│fox│jumps│over│the│lazy│dog.│
└───┴─────┴─────┴───┴─────┴────┴───┴────┴────┘

```
* `#&>` Lengths of each word:

```
3 5 5 3 5 4 3 4 4

```
* J has an "anagram" primitive `A.`, which associates a single number to every possible permutation of a list. We now notice the following:

+ Swapping the final two elements of any list has anagram number `1`.
    + Swapping the two before that has anagram number `2`.
    + Swapping the "middle two" (with left bias) has number `factorial(ceiling(length/2))`.
    + Swapping indexes `1` and `2` has number `factorial(length-2)`
    + Swapping indexes `0` and `1` has number `factorial(length-1)`
* `1,~2,~>.@-:,~1 2-~/]` This constructs a 5 row matrix where each row represents the transforms described above (without factorial applied yet -- we'll do that momentarily) applied to *every element of the length list*:

```
2 4 4 2 4 3 2 3 3 <-- length - 1
1 3 3 1 3 2 1 2 2 <-- length - 2
2 3 3 2 3 2 2 2 2 <-- ceil(length/2)
2 2 2 2 2 2 2 2 2 <-- 2
1 1 1 1 1 1 1 1 1 <-- 1

```
* `#$` Extend the rows cyclically until the matrix is square:

```
2 4 4 2 4 3 2 3 3
1 3 3 1 3 2 1 2 2
2 3 3 2 3 2 2 2 2
2 2 2 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1
2 4 4 2 4 3 2 3 3
1 3 3 1 3 2 1 2 2
2 3 3 2 3 2 2 2 2
2 2 2 2 2 2 2 2 2

```
* `!@` Take the factorial of each:

```
2 24 24 2 24 6 2 6 6
1  6  6 1  6 2 1 2 2
2  6  6 2  6 2 2 2 2
2  2  2 2  2 2 2 2 2
1  1  1 1  1 1 1 1 1
2 24 24 2 24 6 2 6 6
1  6  6 1  6 2 1 2 2
2  6  6 2  6 2 2 2 2
2  2  2 2  2 2 2 2 2

```
* `4&<*` Zero out any rows where the words have length 4 or less:

```
0 0 0 0 0 0 0 0 0
1 6 6 1 6 2 1 2 2
2 6 6 2 6 2 2 2 2
0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0

```
* `<@0 1|:` And take the main diagonal of the above matrix:

```
0 6 6 0 1 0 0 0 0

```

We now have the anagram number we need for each word in the list.
* `A.&.>~` Apply the anagram to each boxed word:

```
┌───┬─────┬─────┬───┬─────┬────┬───┬────┬────┐
│The│qiuck│borwn│fox│jumsp│over│the│lazy│dog.│
└───┴─────┴─────┴───┴─────┴────┴───┴────┴────┘

```
* `;:inv@` Unbox and join with spaces (weirdly `cut` as a monad does not have its natural inverse (join on spaces) defined, otherwise we could save 5 bytes):

```
The qiuck borwn fox jumsp over the lazy dog.

```

---
Tags: code-golf, natural-language
---


title: Cosine similarity of two vectors

text:
# Question
Title: Cosine similarity of two vectors
The cosine similarity of two vectors \\$A\\$ and \\$B\\$ is defined using their dot product and magnitude as:

\\$\frac{A\cdot B}{\\|A\\|\\|B\\|}\\$

Or in other terms

\\$\frac{\sum\_{i=1}^nA\_iB\_i}{\sqrt{\sum\_{i=1}^nA\_i^2}\sqrt{\sum\_{i=1}^nB\_i^2}}\\$

# Challenge

Given two nonempty, nonzero vectors containing only integers (can be taken as lists) calculate their cosine similarity.

* If their lengths are not equal, then the shorter vector should be padded on the right to length of the longer vector with zeroes.

Input and output may be done via any reasonable method.

Test cases below.

```
[1,2,3], [4,5,6] => ~0.974
[9, 62, 0, 3], [25, 3, 6] => ~0.25
[-7, 4, 9, 8], [16, 1, -2, 5] => ~-0.35
[82, -9], [7, 52, 3] => ~0.024

```

This is , so the shortest answer wins.

# Answer
# Desmos, 42 bytes

This non-padding version miraculously works out:

```
f(a,b)=total(ab)/(a^2.totalb^2.total)^{.5}

```

Try It On Desmos!

Try It On Desmos! - Prettified

I originally had constructed an answer that was 123 bytes (around 3 times longer than with no padding!!!) long that did actually do the padding, but then I realized, to my complete surprise, that the test case outputs were matching on both my padding and no-padding answers (which is this 42 byte answer), even for test cases that I made up myself. This led me to dig a bit deeper into why this was the case, resulting in the explanation below.

### Explanation

The question essentially asks to pad the shorter list with zeros at the end to make both lists the same, and then multiply each element of the lists together and sum them, then divide it by the square root of the product of the sums of the elements of each of the two lists squared.

Now let's say that the unpadded, original input lists are `a=[a_1,a_2,...,a_A]` and `b=[b_1,b_2,...,b_B]`, where the capitalized version of the list represents the length of the list. WLOG, assume that `A<B`. Now let `c` and `d` be the padded versions of `a` and `b` respectively, meaning `c=[a_1,a_2,...,a_A,0,...,0]`, where there are `B-A` zeros, and `d=[b_1,b_2,...,b_B]`, which is `b` unchanged.

Now to explain my non-padding answer first:

In Desmos, every time an operation is applied to two lists, it will almost always clip the resulting list to the length of the shorter list out of the two lists. This includes multiplication (implicitly vectorized), which is used in this answer.

For the numerator of the formula given in the question, it is essentially equivalent to using vectorized multiplication on the two lists (which will multiply the lists element-by-element), and then taking the total sum of that vectorized product. We know that vectorized multiplication will clip the lists to the length of the shorter lists, which means that when we take the product `a*b`, we will get the result `[a_1 * b_1, a_2 * b_2,...,a_A * b_A]`, where it is clipped off at the shorter list `a`. Taking the total of this would give `a_1 * b_1 + a_2 * b_2 + ... + a_A * b_A`.

Wait! Now let's take a look at what happens when we take the product `c*d` and sum that list instead. Recall that `c=[a_1,a_2,...,a_A,0,...,0]` and `d=[b_1,b_2,...,b_B]`, so `c*d` would be `[a_1 * b_1, a_2 * b_2,...,a_A * b_A, 0 * b_(A+1),...,0 * b_B]`. Taking the sum of all those terms gives `a_1 * b_1 + a_2 * b_2 + ... + a_A * b_A`, due to all the zeros vanishing from the sum. But this is the exact same sum that we got without padding!!! This indicates that padding at least does not affect the final result of the numerator of the formula, so it is fine to take the sum without padding the two lists beforehand, as it will result in the same answer as with padding anyways.

Now let's consider what is happening in the denominator. In my answer with no padding, I am simply just multiplying each of the lists by themselves (i.e. squaring them), and then summing the resulting elements. So basically, we have that `a^2 = [(a_1)^2, (a_2)^2,...,(a_A)^2]` and `b^2 = [(b_1)^2, (b_2)^2,...,(b_B)^2]`, which means that their sums are `(a_1)^2 + (a_2)^2 + ... + (a_A)^2` and `(b_1)^2 + (b_2)^2 + ... + (b_B)^2` respectively.

But now consider the sums when there is padding involved. We then have that `c^2 = [(a_1)^2, (a_2)^2,...,(a_A)^2, 0^2,...,0^2]`, and `d^2` would be the same as `b^2` because as stated earlier, `d` is the same as `b` unchanged. So, the sum of `d^2` would obviously match that of `b^2`. But what about the sum of `c^2`? We have that the sum of `c^2` is `(a_1)^2 + (a_2)^2 + ... + (a_A)^2 + 0^2 + ... + 0^2`, but because all the zeros just vanish, the sum simplifies down to `(a_1)^2 + (a_2)^2 + ... + (a_A)^2`. Comparing this to the sum that we got with no padding, we can see that they are exactly the same!!!

Obviously, we have assumed that `A<B` at the very start of our proof. But what happens if `B>A`? Then simply just switch all the `a`'s and `b`'s, `A` and `B`'s, and also `c` and `d` and you will have the proof for the `B>A` case.

Lastly, what happens if `A=B`; in other words, what happens if they are both the same length? The clipping will shorten the longer list into the same length of the shorter list, but because they are the same length, this will not affect either of the lists. Similarly, padding will lengthen the shorter length to match the length of the longer list, but again, because the two lists are the exact same length, this won't affect either of the lists. Because both clipping and padding preserve the original lists, both of them will obviously result in the same calculations and therefore the same outputs as well.

Thus, by proving that the sums in both the numerator and denominator are the same with both padding (which is what the question is asking for) and with no padding (which is what is happening in my answer), my answer is valid, even though I am not actually doing any padding like the question asks for.
> 7 votes

# Answer
# 05AB1E, 9 bytes

```
`*OInOtP/

```

Input as a pair of lists.

Try it online or verify all test cases.

**Explanation:**

```
`          # Push both lists of the (implicit) input-pair separately to the stack
 *         # Multiply the values at the same positions in the lists together
           # (discarding trailing items of unequal length input-lists)
  O        # Sum all these values together
   I       # Push the input-pair of lists again
    n      # Square each inner value
     O     # Sum the two inner lists
      t    # Take the square root of both sums
       P   # Take the product of this pair
        /  # Divide the earlier dot-product by this
           # (after which the result is output implicitly)

```

Here a minor equal-bytes alternative: `øPInOtP/O`. I haven't been able to find anything shorter unfortunately, but there are a lot of approaches for this at 1 or 2 bytes longer: try it online.
> 7 votes

# Answer
# Wolfram Language (Mathematica), ~~60~~ ~~31~~ 27 bytes

```
Dot@@Normalize/@PadRight@#&

```

Try it online!

Many thanks to @att and @ polfosol ఠ\_ఠ ! They should have posted their answers (-\_-)
> 6 votes

# Answer
# Jelly, 7 bytes

```
ÆḊ€÷ƒḋ/

```

A monadic Link that accepts the pair of vectors and yields their cosine similarity.

**Try it online!**

### How?

```
ÆḊ€÷ƒḋ/ - Link: pair of lists, V
  €     - for each vector:
ÆḊ      -   get its norm
      / - reduce V by:
     ḋ  -   dot-product
    ƒ   - starting with the dot-product reduce the norms by:
   ÷    -   division

```

---

Here's a dyadic version, also at seven bytes:

```
,ÆḊ€÷ƒḋ

```

Try it online!
> 6 votes

# Answer
# MATLAB, 37 32 bytes

-5 bytes thanks to @loopywalt

```
@(a,b)sum(diag(a'*b))/norm(a'*b)

```

Instead of padding `a` or `b` to the length of the other, or cropping it, which should be equivalent in the numerator, we take the outer product of the two vectors, then sum the diagonal (ie trace). This is equivalent to the dot product of the two vectors cropped to the shortest length.

Unfortunately, this doesn't work if the two vectors have different length, `trace` requires a square matrix:

```
@(a,b)trace(a'*b)/norm(a'*b)

```
> 6 votes

# Answer
# Vyxal `s`, 7 bytes

```
*□²Ṡ√Π/

```

Try it Online!

Link includes test cases.  flag prints numbers as decimals (for convenience) rather than as rationals, but is not needed.

*-1 thanks to @lyxal*

#### Explanation

```
*□²Ṡ√Π/  # Implicit input
*        # Vectorised multiplication
 □²      # Input list squared
   Ṡ√    # Sum and square root
     Π   # Product
      /  # Divide
         # s flag sums the list
         # Implicit output

```

Old:

```
Þ•2(?²∑√)*/  # Implicit input
Þ•           # Dot product: seems to handle the padding with 0s
  2(    )    # Repeat twice:
    ?        #  Next input
     ²       #  Squared
      ∑      #  Summed
       √     #  Square rooted
         *   # Multiply both
          /  # Divide
             # Implicit output

```
> 5 votes

# Answer
# , 40 bytes

```
\(x,y)sum(diag(z<-x%*%t(y)))/norm(z,"f")

```

Attempt This Online!

R port of Cris Luengo's MATLAB answer.

# , 48 bytes

```
\(x,y)(x%*%x*y%*%y)^-.5*(x*y)%*%!seq(!x)-seq(!y)

```

Attempt This Online!

A slight rearrangement and golf of Dominic van Essen's answer, posted at his request.

Works by maximizing operator precedence and vector recycling.
> 5 votes

# Answer
# Python NumPy, 50 bytes

```
lambda a,b:(z:=a*b[:,1>0]).trace()/(z*z).sum()**.5

```

Attempt This Online!
> 5 votes

# Answer
# TI-BASIC (TI-84),  ~~43~~ 41 bytes

Padding is expensive.

```
:Prompt A,B
:max(dim(ʟA),dim(ʟB→dim(ʟA
:Ans→dim(ʟB
:sum(ʟAʟB/√(sum(ʟB²)sum(ʟA²

```

Example usage:

```
prgmCOSSIM
A=?{9,62,0,3}
B=?{25,3,6}
              .2531554274

```

For comparison:

## TI-BASIC (TI-84), no padding, ~~19~~ 17 bytes

Errors when the inputs aren't equal length. Takes the first input via `Ans`.

```
:Prompt A
:sum(ʟAAns/√(sum(Ans²)sum(ʟA²

```

Example usage:

```
{1,2,3}:prgmCOSSIM
A=?{4,5,6}
               .974631462

```
> 4 votes

# Answer
# JavaScript (ES6), 76 bytes

Expects `(a)(b)`.

```
a=>b=>[...a+b].reduce(t=>t+~~a[i]*~~b[i++]/h(...a)/h(...b),i=0,h=Math.hypot)

```

Try it online!

### Commented

```
a =>             // outer function taking the 1st vector a[]
b =>             // inner function taking the 2nd vector b[]
[...a + b]       // build a large enough array to make sure that we
                 // iterate on all values of the largest vector
.reduce(t =>     // using t as an accumulator, for each entry in there:
  t +            //   add to t:
    ~~a[i]       //     either a[i] or 0
    * ~~b[i++]   //     multiplied by either b[i] or 0 (then increment i)
    / h(...a)    //     divided by hypot(a)
    / h(...b),   //     divided by hypot(b)
  i = 0,         //   start with t = i = 0
  h = Math.hypot //   h is an alias for Math.hypot
)                // end of reduce()

```
> 4 votes

# Answer
# , 52 bytes

*Edit: +2 bytes to fix when either vector is length-1, thanks to Giuseppe*

```
\(x,y,`?`=sum)?x*y*(seq(!x)==seq(!y))/(?x^2*?y^2)^.5

```

Attempt This Online!
> 4 votes

# Answer
# Pip `-x`, 17 bytes

```
$*_MS Zg/RT$+*SQg

```

Takes the vectors as two command-line arguments, each one formatted as a Pip list. Attempt This Online!

### Explanation

We use the equivalent formula \\$\sum\_{i=1}^n\frac{A\_i}{\sqrt{\sum\_{i=1}^nA\_i^2}}\frac{B\_i}{\sqrt{\sum\_{i=1}^nB\_i^2}}\\$:

```
$*_MS Zg/RT$+*SQg
                   ; g is list of command-line args, evaluated (-x flag)
              SQg  ; Square each value in the list of two vectors
           $+*     ; Sum each squared vector
         RT        ; Take the square root of each sum
       g/          ; Divide the list of two vectors by that list of two magnitudes
      Z            ; Zip (transpose) the list of two vectors, pairing up corresponding
                   ; elements and trimming the longer vector to the length of the
                   ; shorter one (which, at the dot product stage, is equivalent to
                   ; right-padding the shorter one with zeros)
   MS              ; Map this function to each pair of values and sum the results:
$*_                ;   Take the product of the values

```
> 4 votes

# Answer
# Pyth, ~~13~~ 11 bytes

*-2 bytes thanks to FryAmTheEggman*

```
cF+s*MCQ.aM

```

Try it online!

### Explanation

```
cF+s*MCQ.aMQ    # implicitly add Q
                # implicitly assign Q = eval(input())
      CQ        # transpose the input, truncating to the shortest element
    *M          # map each element to its product
   s            # sum the elements
  +             # prepend this to
        .aMQ    # the input elements mapped to their norms
cF              # fold this over division

```
> 4 votes

# Answer
# APL(Dyalog Unicode), 17 bytes SBCS

```
↓∘↑+.×.÷.5*⍨1⊥¨×⍨

```

Try it on APLgolf!

Lots of dots.. .

Input an array containing the two vectors.
> 4 votes

# Answer
# Brachylog, 20 bytes

```
z₀×ᵐ+D&{^₂ᵐ+√}ᵐ×;D↔/

```

Try it online!

### Explanation

```
z₀×ᵐ+D&{^₂ᵐ+√}ᵐ×;D↔/
                      Input is a list of two lists representing the two vectors
z₀                    Zip the two vectors, clipping to the shorter length
  ×ᵐ                  Multiply each pair of corresponding values
    +                 Sum the products
     D                Save this value as D (for Dot product)
      &               Start over with the original list of lists
       {     }ᵐ       Do this to each vector:
        ^₂ᵐ             Square each of its elements
           +            Sum the squares
            √           Get the square root of the sum
               ×      Multiply the two results
                ;D    Pair with D from earlier
                  ↔   Reverse the list, putting D first
                   /  Divide

```
> 4 votes

# Answer
# Python, 73 bytes

*-95 bytes thanks to `Neil`, -3 bytes thanks to `att` and -3 bytes thanks to `xnor`.*

This works despite the `zip` function stopping at the shorter sequence, since we right pad with `0`. Essentially, the elements of the longer sequence do not affect the calculation.

```
lambda a,b:d(a,b)/(d(a,a)*d(b,b))**.5;d=lambda*a:sum(map(int.__mul__,*a))

```

Attempt This Online!

*P.S. I edited out the other versions of this answer made with `scipy`, `numpy` and `scikit-learn`, because they were significantly longer.*
> 3 votes

# Answer
# Octave, ~~110~~ 61 bytes

saved 49 bytes thanks to the comment

```
@(A,B)A(1:(p=min(numel(A),numel(B))))*B(1:p)'/norm(A)/norm(B)

```

Try it online!
> 3 votes

# Answer
# Julia 1.0, ~~68~~ ~~60~~ ~~44~~ 43 bytes

```
x^y=sum(prod,zip(x,y))
a\b=a^b/√(a^a*b^b)

```

Try it online!

* The power operator `^` is redefined for the intermediate function. This adds a few bytes where a square or square root is needed, but its high precedence in order of operations cuts down on parentheses used.
* `zip` is used to accommodate vectors with different lengths.
    + Otherwise, `x^y=sum(x.*y)` could be used.

Alternatively, `LSHFunctions.cossim` could be adapted for this challenge.

* -8 bytes thanks to Giuseppe: rewrite with an improved formula
* -16 bytes (!!) thanks to Giuseppe: `sum` supports a calling function
* -1 byte thanks to MarcMush: replace `sqrt` with
> 3 votes

# Answer
# Vyxal, 9 bytes

```
Þ•∇"²Ṡ√Π/

```

Edit: Thunno ninja'd me but kinda want to leave my answer here as it (was) shorter

Try it Online!

**How it works:**

```
Þ•∇"²Ṡ√Π/
Þ•          Calculate the dot product
  ∇         Shift stack
   "        Pair the vectors
    ²Ṡ√     Square, take vectorised sum and square root
       Π/   Push product and divide

```
> 2 votes

# Answer
# Charcoal, ~~16~~ 14 bytes

```
Ｉ∕Σ×θη₂ΠＥ²ΣＸＡ²

```

Attempt This Online! Link is to verbose version of code. Explanation:

```
    θ           First input
   ×            Vectorised multiply by
     η          Second input
  Σ             Take the sum
 ∕              Divided by
         ²      Literal integer `2`
        Ｅ       Map over implicit range
            Ａ   Next input
           Ｘ    Vectorised raise to power
             ²  Literal integer `2`
          Σ     Take the sum
       Π        Take the product
      ₂         Take the square root
Ｉ               Cast to string
                Implicitly print

```
> 2 votes

# Answer
# Pyt, 20 bytes

```
Đ←Đ04Ș*Ʃ⇹²Ʃ↔+²Ʃ⇹↔*√/

```

Try it online!

```
Đ←Đ04Ș                       Gets stack set up for calculations
      *Ʃ                     A·B
        ⇹²Ʃ↔+²Ʃ⇹↔*√          ||A||*||B||
                   /         divide; implicit print

```
> 2 votes

# Answer
# Factor \+ `math.similarity`, 17 bytes

```
cosine-similarity

```

Attempt This Online!
> 2 votes

# Answer
# Nibbles, 14.5 bytes (29 nibbles)

```
^/^+*100!$_*~*;~$+.$^$~$_-2

```

Nibbles only handles integers, and perhaps isn't the ideal language to calculate a value that will always lie in the range between `-1` and `1`. So this program outputs the cosine similarity multiplied by 100: the extra code for this costs +3.5 bytes - without it, the program would be `/+!$_*^*;~$+.$^$~$_-2` (11 bytes), but can only output to an accuracy of zero decimal places, so either `1`, `0` or `-1`.

```
^/^+*100!$_*~*;~$+.$^$~$_-2
                                # First get the dot-product multiplied by 100:
        !                       #   zip together
         $_                     #   arg1 and arg2
           *                    #   by multiplication
    *100                        #   multiply each element by 100
   +                            #   and get the sum
  ^         ~                   # and then square the dot-product;
                                # Now get the squares of the product of the magnitudes:
              ;~$               #   apply to arg1 and save as function:
                  .$            #     map over each element:
                    ^$~         #       square
                 +              #     and sum the squared elements
                       $_       #   apply the same function to arg2
             *                  #   and multiply the two results together;
 /                              # Now divide the squared 100x dot-product
                                # by the squares of the product of the magnitudes
^                        -2     # and return the square-root of the result

```
> 2 votes

# Answer
# Raku, 45 bytes

```
->\a,\b{sum(a Z*b)/sqrt sum(a Z*a)*sum b Z*b}

```

Try it online!

This is a straightforward translation of the cosine similarity formula. `x Z* y` zips two lists together with multiplication, and `sum` and `sqrt` are self-explanatory.
> 2 votes

# Answer
# BQN, ~~20~~ 17 bytes

*-3 bytes thanks to att*

```
D←+´⊣×≠⊸↑
D÷×○√○D

```

The first line defines a helper function; the second line is the solution, an anonymous tacit function that takes two lists of numbers as left and right arguments. Try it at BQN online!

### Explanation

The helper function `D` calculates the dot product of two vectors (or, given one argument, the dot product of a vector with itself). The default behavior of  turned out to be *very* convenient here.

```
D←+´⊣×≠⊸↑
D←         Assign this function to D:
      ≠⊸↑    Take (length of left arg) elements from (right arg)
               If left arg is shorter, trims right arg to that length
               If left arg is longer, pads right arg with zeros
    ⊣×       Multiply itemwise with left arg
  +´         Sum

D÷×○√○D
     ○D  Apply D to each argument (i.e. multiply it by itself and sum)
   ○√    Apply square root to each of those sums (magnitude of each vector)
  ×      Multiply those two results
D        Apply D to both arguments (i.e. get their dot product)
 ÷       Divide the dot product by the product of magnitudes

```
> 2 votes

# Answer
# jq, 68 bytes

```
(transpose|map((.[0]*.[1])?)|add)/(map(map(.*.)|add|sqrt)|.[0]*.[1])

```

Try it online!

`transpose` pads the arrays with `null`s, which we then simply remove with `?` when the multiplication fails, instead of replacing with zero.
> 2 votes

# Answer
# Arturo, 69 bytes

```
$[a b][//∑map couple a b'p->∏p∏map@[a b]=>[sqrt∑map&'x->x^2]]

```

Try it
> 1 votes

# Answer
# Japt v2.0a0, 13 bytes

```
í*V x÷NËx²¬Ã×

```

Try it
> 1 votes

# Answer
# JavaScript, 175 bytes

```
(e,r)=>(l="length",p=(e,r)=>Array.from({...e,[l]:r[l]},e=>e??0),e[l]<r[l]?e=p(e,r):r=p(r,e),e[_="reduce"]((e,$,c)=>e+$*r[c],0)/(e[_]((e,r)=>e+r*r,0)*r[_]((e,r)=>e+r*r,0))**.5)

```

Try it:

```
c=

// start code
(e,r)=>(l="length",p=(e,r)=>Array.from({...e,[l]:r[l]},e=>e??0),e[l]<r[l]?e=p(e,r):r=p(r,e),e[_="reduce"]((e,$,c)=>e+$*r[c],0)/(e[_]((e,r)=>e+r*r,0)*r[_]((e,r)=>e+r*r,0))**.5)
// end code

console.log(c([1,2,3], [4,5,6]))
console.log(c([9, 62, 0, 3], [25, 3, 6]))
console.log(c([-7, 4, 9, 8], [16, 1, -2, 5]))
console.log(c([82, -9], [7, 52, 3]))
```
> 0 votes

# Answer
# Uiua SBCS, ~~17~~ 16 bytes

```
÷/×√∩/+⍉×.⟜/×⬚0⊟

```

Try it!
> 0 votes

# Answer
# APL(NARS), 36 chars

```
{+/¨×/{⍵÷√+/⍵*2}¨(⍺,0⍴⍨≢⍵)(⍵,0⍴⍨≢⍺)}

```

test:

```
  g←{+/¨×/{⍵÷√+/⍵*2}¨(⍺,0⍴⍨≢⍵)(⍵,0⍴⍨≢⍺)}
  1 2 3 g 4 5 6
0.9746318462
  1 2 3 0  g 4 5 6
0.9746318462
  1 2 3 0 g 4 5 6 0 0 0 0 0
0.9746318462

```
> 0 votes

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


title: Counting rankings

text:
# Question
Title: Counting rankings
There is a competition with \\$n\\$ participants in total. Alice is one of the participants. The outcome of the competition is given as a ranking per participant with a possibility of ties; e.g. there can be three participants who won 2nd place, and the next best participant gets the 5th place.

More rigorously, a participant's rank is defined as *the number of other participants who performed strictly better than them plus 1*.

If Alice scored \\$k\\$th place in the competition, what is the number of possible distinct outcomes of the competition? Two outcomes are distinct if there exists a participant whose ranking is different between the two.

As a worked example, let's say \\$n = 3\\$ and the participants are Alice, Bob, and Charlie. If Alice is 1st, Bob is 2nd, and Charlie is 3rd, the outcome can be written as `{Alice: 1, Bob: 2, Charlie: 3}`, or `[1, 2, 3]` in short. This outcome is distinct from `[1, 3, 2]` or `[1, 2, 2]`. This notation is used in the test cases below.

Assume that \\$n\\$ and \\$k\\$ are integers and \\$1 \le k \le n\\$.

Standard rules apply. The shortest code in bytes wins.

## Test cases

```
n, k -> ans (possible rankings; Alice is the first in the array)
1, 1 -> 1 ([1])
2, 1 -> 2 ([1,1], [1,2])
2, 2 -> 1 ([2,1])
3, 1 -> 6 ([1,1,1], [1,1,3], [1,3,1], [1,2,2], [1,2,3], [1,3,2])
3, 2 -> 4 ([2,1,3], [2,3,1], [2,2,1], [2,1,2])
3, 3 -> 3 ([3,1,1], [3,1,2], [3,2,1])
4, 1 -> 26
4, 2 -> 18
4, 3 -> 18
4, 4 -> 13

```

For a given \\$n\\$, sum of outputs over \\$1 \le k \le n\\$ is A000670. The output for \\$k = 1\\$ is A000629.

Imaginary brownie points for answers that solve the challenge without generating all possible rankings.

# Answer
> 6 votes
# Python 3, ~~93~~ ~~84~~ 77 bytes

-9 bytes thanks to @xnor!

Going for the brownie points, but still exponential runtime ;)

```
f=lambda n,k,d=1:(n<2or~-n*(f(n-1,k,d+1)*(d!=k-1)+f(n-1,k-d)))/(d-(k==1)or 1)

```

Try it online!

# Answer
> 4 votes
# Python 3, ~~124~~ ~~119~~ 117 bytes

*-5 bytes thanks to enzo.*

```
lambda n,k:sum(all(r==sum(q<r for q in s)for r in s)for s in product([k-1],*[range(n)]*(n-1)))
from itertools import*

```

Try it online!

This uses the `sum` function two times too many, considering the algorithm doesn't involve any addition at all...

## Explanation

The algorithm is pretty simple. Let's assume there are \\$n = 3\\$ contestants and Alice's rank \\$k = 1\\$. The ranks that follow will be 0-indexed because it's more convenient to work with. First, it generates a list of possible rankings where Alice's rank, or the first rank in the list, is \\$0\\$. This is done by taking the Cartesian product of the singleton list \\$\[0\]\\$ with \\$n - 1 = 2\\$ copies of \\$\[0, 3)\\$.

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

```

Then, it knocks out invalid rankings by checking if each rank is equal to "the number of other participants who performed strictly better than them", or in other words, the number of ranks lower than the rank in question.

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

```

Finally, it returns the number of rankings remaining, which is \\$6\\$.

# Answer
> 4 votes
# APL(Dyalog Unicode), ~~58~~ 57 bytes SBCS

```
{⍵÷⍨⍺(⊣{n×⍵÷1⌈(⌽-⍺∘=)⍳n←≢⍵}¯1↓⊢/⍤⊢+⊢×(≠∨=∘⍳)∘≢)⍣⍵⊢0,⍨⍵⍴1}

```

Try it on APLgolf!

A dynamic programming adaption of my recursive Python answer. Runs in \\$ \mathcal{O}(n^2) \\$. A brute force approach would 25 bytes:

```
{⊃+⌿⍺=1+↑∪(+/∘.<⍨)¨,⍳⍵⍴⍵}

```

Try it on APLgolf!

# Answer
> 3 votes
# JavaScript (ES6), 63 bytes

A port of ovs' great Python answer. Now including the optimization suggested by xnor.

Expects `(n, k)`.

```
f=(n,k,d=1)=>(--n?n*=(~d+k&&f(n,k,d+1))+f(n,k-d):1)/(d-!~-k||1)

```

Try it online!

---

# JavaScript (ES7), 114 bytes

Expects `(n)(k)`.

```
n=>k=>eval("for(j=t=n**n;j--;)t-=(a=[...Array(n)].map((_,i)=>x=j/n**i%n|0)).some(r=>a.map(v=>q-=v<r,q=r)|q|~x+k)")

```

Try it online!

### Commented

This is a version without `eval()` for readability.

```
n =>                 // outer function taking n
k => {               // inner function taking k
  for(               // loop:
    j = t = n ** n;  //   start with j = t = n ** n, where:
                     //     j = iteration counter
                     //     t = success counter
    j--;             //   stop once j = 0 has been processed
  )                  //
    t -=             //   decrement t for each failure
    ( a =            //   let a[] be an array of n entries,
      [...Array(n)]  //   which are turned into 0-indexed rankings
      .map((_, i) => //   for each value at index i in a[]:
        x =          //     save the last value in x
        j / n ** i   //     fill with an integer in [0 .. n-1],
        % n | 0      //     according to j and i
      )              //   end of map()
    ).some(r =>      //   for each ranking r in a[]:
      a.map(v =>     //     for each ranking v in a[]:
        q -= v < r,  //       decrement q if v < r
        q = r        //       starting with q = r
      )              //     end of map()
      | q            //     some() is triggered if q != 0
      | ~x + k       //     or x != k - 1 (i.e. the last ranking
                     //     is not Alice's ranking)
    );               //   end of some() / end of for()
  return t           // return the success counter
}                    //

```

# Answer
> 3 votes
# Nekomata \+ `-n`, 11 bytes

```
RJ:ᵐhmj↕ũh=

```

Attempt This Online!

```
RJ:ᵐhmj↕ũh=     Take input n, k
R               Range from 1 to n
 J              Split the range into a list of parts
  :ᵐhm          Replace every element in each part with the head of the part
                For example, [[1],[2,3],[4,5]] -> [[1],[2,2],[4,4]]
      j         Join the list of parts into a single list
       ↕        Take a permutation
        ũ       Remove duplicate permutations
         h=     Check if the head of the list is equal to k

```

`-n` counts the number of solutions.

# Answer
> 2 votes
# 05AB1E, 15 bytes

```
L¤ãʒ<Ðδ›OQ}€нQO

```

Port of *@totallyhuman*'s Python answer, so make sure to upvote that answer as well!

Try it online or verify all test cases.

**Explanation:**

```
L           # Push a list in the range [1, first (implicit) input-integer n]
 ¤          # Push its last item (without popping): n
  ã         # Cartesian product to get all n-sized lists using [1,n]-ranged integers
   ʒ        # Filter it by:
    <       #  Decrease all values in the list by 1
     Ð      #  Triplicate the list
      δ     #  Pop two, and apply double-vectorized:
       ›    #   Larger than check
        O   #  Sum each inner list/row together
         Q  #  Check if this list of sums equals the original list we've triplicated
     }€н    # After the filter: only leave the first item of each remaining list
        Q   # Check for each whether it equals the second (implicit) input-integer k
         O  # Sum those checks together
            # (which is output implicitly as result)

```

# Answer
> 2 votes
# Jelly, 27 bytes (fast version)

```
cⱮ`€U;ḋ¥ƒ1H1¦ṖṚ,Ʋ⁹ịⱮPḤ×c×÷⁸

```

A dyadic Link that accepts \\$n\\$ on the left and \\$k\\$ on the right and yields the count of weak orderings given a labelled item's rank.

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

### How?

First calculates the first \\$n+1\\$ Fubini numbers (A000670): \\$F(a) \forall a \in \[0,n\]\\$.

This is achieved by expanding the recursive calculation \\$F(a) = \sum\_{j=1}^a{F(a-j)\binom{a}{j}}, F(0)=1\\$ as a reduction of dot-products over the relevant portion of Pascal's triangle. (I think this can probably be golfed a little by using the recursive calculation itself.)

Then uses that to calculate half of the number of necklaces of partitions of n+1 labelled beads (\\$\frac{1}{2}\\$A000629) which is simply \\$F\\$ but with the first term halved: \\$\frac{N(a)}{2} \forall a \in \[0,n\]\\$

Finally applies the formula suggested by Nitrodon in the comments:

$$R(n,k)=F(k-1)N(n-k)\binom{n-1}{k-1}$$

```
cⱮ`€U;ḋ¥ƒ1H1¦ṖṚ,Ʋ⁹ịⱮPḤ×c×÷⁸ - Link: n, k
   €                        - for each {v in [1..n]}:
 Ɱ`                         -   map across {w in [1..v]} with:
c                           -     {v} choose {w}
    U                       - reverse each -> [[1C1], [2C2, 2C1], [3C3, 3C2, 3C1], ...]
        ƒ1                  - starting with 1 reduce by:
       ¥                    -   last two links as a dyad f(current, next):
      ḋ                     -     {current} dot-product {next}
     ;                      -     {current} concatenate {that}
                               -> [F(a) for a in [0..n]] = Fubinis
                Ʋ           - last four links as a monad - f(Fubinis):
          H1¦               -   halve the first term
             Ṗ              -   remove the last term
              Ṛ             -   reverse
               ,            -   pair {Fubinis} -> [Necklaces/2, Fubinis]
                 ⁹ịⱮ        - kth element of each -> [N(n-k)/2, F(k-1)]
                    P       - product
                     Ḥ      - double -> F(k-1)*N(n-k)
                       c    - {n} choose {k}
                      ×     - multiply -> F(k-1) * N(n-k) * nCk
                        ×   - multiply by {k}
                         ÷⁸ - divide by {n} -> F(k-1) * N(n-k) * (n-1)C(k-1)

```

# Answer
> 2 votes
# Ruby, 212 bytes

## ... but runs in polynomial time!

```
def f(n)=n<1?1: n*f(n-1)
$r={}
def r(n, k)=$r[[n,k]]=k**n-(1...k).sum{|i|f(k)/f(i)/f(k-i)*$r[[n,i]]}
def q(x)=x<1?1:(1..x).sum{|i|r(x,i)}
def s(n, k)=(0..(n-k)).sum{|e|f(n-1)/f(k-1)/f(n-k-e)/f(e)*q(k-1)*q(n-k-e)}

```

The final solution is function `s`, which takes *n* and *k* as arguments.

### How does it work?

Divides *n* \- 1 people into three categories: those who were strictly better than Alice, those who were equal, and those strictly worse. We know that exactly *k* \- 1 people ranked better than Alice, we just need to iterate over how many were equal: minimum of 0, maximum *n* \- *k*.

There are 3 auxiliary functions. Function `f` is just factorial definition. Function `r` calculates how many ways to distribute *n* people into exactly *k* distinct ranks, and must be memoized else the running time goes exponential. Function `q` calculates how many ways do distribute *x* people into any number of ranks (it is just a summation of `r`).

# Answer
> 1 votes
# Charcoal, 36 bytes

```
ＮθＮηＩＬΦＥＸθ⊖θ⊞Ｏ﹪÷ιＸθ…⁰⊖θθ⊖η⬤ι⁼λＬΦι‹νλ

```

Try it online! Link is to verbose version of code. Explanation: Based on @totallyhuman's Python answer.

```
Ｎθ                                      Input `n` as a number
  Ｎη                                    Input `k` as a number
         θ                              Input `n`
        Ｘ                               Raised to power
           θ                            Input `n`
          ⊖                             Decremented
       Ｅ                                Map over implicit range
                ι                       Current value
               ÷                        Vectorised integer divided by
                  θ                     Input `n`
                 Ｘ                      Vectorised raised to power
                   …                    Range from
                    ⁰                   Literal integer `0` to
                       θ                Input `n`
                      ⊖                 Decremented
              ﹪                         Vectorised modulo
                       θ                Input `n`
            ⊞Ｏ                          Concatenated with
                         η              Input `k`
                        ⊖               Decremented
      Φ                                 Filtered where
                           ι            Current list
                          ⬤             All elements satisfy
                                 ι      Current list
                               Φ        Filtered where
                                  ν     Inner element
                                 ‹      Is less than
                                   λ    Outer element
                              Ｌ         Take the length
                            ⁼           Equals
                             λ          Current element
     Ｌ                                  Take the length
    Ｉ                                   Cast to string
                                        Implicitly print

```

# Answer
> 1 votes
# Jelly, 13 bytes (golf version)

```
ṗ`<Ɱ`§‘ƊƑƇḢ€ċ

```

A dyadic Link that accepts \\$n\\$ on the left and \\$k\\$ on the right and yields the count of weak orderings given a labelled item's rank.

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

### How?

```
ṗ`<Ɱ`§‘ƊƑƇḢ€ċ - Link: n, k
ṗ`            - {n} Cartesian power {n} -> all length n words of alphabet [1..n]
         Ƈ    - filter keep those for which:
        Ƒ     -   is invariant under?:
       Ɗ      -     last three links as a monad - f(word):
  <Ɱ`         -       {word} less than mapped over {word}
     §        -       sums -> [count of elements less than i for i in word]
      ‘       -       increment {those}
                 -> all valid rankings
          Ḣ€  - head each -> Alice's rank in each valid ranking
            ċ - count occurrences of {k}

```

# Answer
> 0 votes
# Python3, 222 bytes

```
from itertools import*
R=range
def f(n,k):
 t=0
 q=[(1,{*R(n)},{})]
 for a,b,c in q:
  if not b:t+=c.get(k,[-1])[0]==0
  else:
   for i in R(len(b)):
    for C in combinations(b,i+1):q+=[(a+i+1,b-{*C},{**c,a:C})]
 return t

```

Try it online!

# Answer
> 0 votes
# JavaScript (Node.js), 120 bytes

```
n=>g=(k,...s)=>(s[n-1]?k==s[0]&[...s].sort((a,b)=>a-b).every(u=(t,i)=>t==u|(u=t)==i+1):g(k,n,...s))+(--s[0]?g(k,...s):0)

```

Try it online!

# Answer
> 0 votes
# Desmos, 102 bytes

```
f(n,k)=∑_{a=0}^{n^n/n-1}0^{[(B[B<i].count-i)^2fori=B].max}
B=mod(floor((na+(k-1)n^n)/n^{[1...n]}),n)

```

Try It On Desmos!

Try It On Desmos! - Prettified

Eh, this is so scuffed but it works so whatever lmao.

---
Tags: code-golf, math, combinatorics
---


# Question
Title: Code-Golf: Lattice Points inside a Circle
The following picture shows the problem:

Write a function that, given an integer as the circle radius, calculates the number of lattice points inside the *centered* circle (including the boundary).

The image shows:

```
f[1] = 5  (blue points)
f[2] = 13 (blue + red points)

```

other values for your checking/debugging:

```
f[3]    = 29
f[10]   = 317
f[1000] = 3,141,549
f[2000] = 12,566,345

```

Should have a reasonable performance. Let's say less than a minute for f\[1000\].

Shortest code wins. Usual Code-Golf rules apply.

Please post the calculation and timing of f\[1001\] as an example.

# Answer
## J, 21 19 18

```
+/@,@(>:|@j./~@i:)

```

Builds complexes from -x-xj to x+xj and takes magnitude.

Edit: With `>:`

Edit 2: With hook and monadic `~`. Runs a few times slower for some reason, but still 10-ish seconds for f(1000).
> 9 votes

# Answer
## J, ~~27~~ 21

```
3 :'+/,y>:%:+/~*:i:y'

```

Very brutal: computes *sqrt(x²+y²)* over the *\[-n,n\]* range and counts items *≤n*. Still very acceptable times for 1000.

**Edit**: `i:y` is quite a bit shorter than `y-i.>:+:y`. Thanks Jesse Millikan!
> 5 votes

# Answer
## Ruby 1.9, ~~62 58~~ 54 characters

```
f=->r{1+4*eval((0..r).map{|i|"%d"%(r*r-i*i)**0.5}*?+)}

```

Example:

```
f[1001]
=> 3147833

t=Time.now;f[1001];Time.now-t
=> 0.003361411

```
> 4 votes

# Answer
**Python 55 Chars**

```
f=lambda n:1+4*sum(int((n*n-i*i)**.5)for i in range(n))

```
> 4 votes

# Answer
## Haskell, 41 bytes

```
f n=1+4*sum[floor$sqrt$n*n-x*x|x<-[0..n]]

```

Counts points in the quadrant `x>=0, y>0`, multiplies by 4, adds 1 for the center point.
> 3 votes

# Answer
# Uiua, 13 bytes

```
∧+1×4⌊√×⊃+-⇡.

```

Try it online!

Uses the formula on A057655 \\$ 1+4\sum\_{k=0}^{n}{\left\lfloor\sqrt{n^2-k^2}\right\rfloor} \\$, and uses the fact that `k=n` part can be removed.

```
∧+1×4⌊√×⊃+-⇡.    input: integer n
            ⇡.    keep n and generate the range for k
       ×⊃+-      (n+k) * (n-k) for each k
      ⌊√          sqrt, floor
∧+1×4            multiply 4, sum, and add 1

```
> 3 votes

# Answer
# Haskell, 44 bytes

```
f n|w<-[-n..n]=sum[1|x<-w,y<-w,x*x+y*y<=n*n]

```
> 2 votes

# Answer
# Japt `-x`, 12 bytes

```
òUn)ï Ëx²§U²

```

Try it online!

Explanation:

```
òUn)            #Get the range [-input ... input]
    ï           #Get each pair of numbers in that range
      Ë         #For each pair:
       x        # Get the sum...
        ²       # Of the squares
         §      # Check if that sum is less than or equal to...
          U²    # The input squared
                #Output the number of pairs that passed the check

```
> 2 votes

# Answer
## JavaScript (ES6), 80 bytes

```
n=>(a=[...Array(n+n+1)].map(_=>i--,i=n)).map(x=>a.map(y=>r+=x*x+y*y<=n*n),r=0)|r

```

Alternative version, also 80 bytes:

```
n=>[...Array(n+n+1)].map((_,x,a)=>a.map((_,y)=>r+=x*x+(y-=n)*y<=n*n,x-=n),r=0)|r

```

ES7 version, also 80 bytes:

```
n=>[...Array(n+n+1)].map((_,x,a)=>a.map((_,y)=>r+=(x-n)**2+(y-n)**2<=n*n),r=0)|r

```
> 1 votes

# Answer
## Python 2, 48 bytes

```
f=lambda n,i=0:i>n or(n*n-i*i)**.5//1*4+f(n,i+1)

```

Like fR0DDY's solution, but recursive, and returns a float. Returning an int is 51 bytes:

```
f=lambda n,i=0:i>n or 4*int((n*n-i*i)**.5)+f(n,i+1)

```
> 1 votes

# Answer
# PHP, 85 83 bytes

The code:

```
function f($n){for($x=$n;$x;$c+=$x,$y++)for(;$n*$n<$x*$x+$y*$y;$x--);return$c*4+1;}

```

Its outcome (check https://3v4l.org/bC0cY for multiple PHP versions):

```
f(1001)=3147833
time=0.000236 seconds.

```

The ungolfed code:

```
/**
 * Count all the points having x > 0, y >= 0 (a quarter of the circle)
 * then multiply by 4 and add the origin.
 *
 * Walk the lattice points in zig-zag starting at ($n,0) towards (0,$n), in the
 * neighbourhood of the circle. While outside the circle, go left.
 * Go one line up and repeat until $x == 0.
 * This way it checks about 2*$n points (i.e. its complexity is linear, O(n))
 *
 * @param int $n
 * @return int
 */
function countLatticePoints2($n)
{
    $count = 0;
    // Start on the topmost right point of the circle ($n,0), go towards the topmost point (0,$n)
    // Stop when reach it (but don't count it)
    for ($y = 0, $x = $n; $x > 0; $y ++) {
        // While outside the circle, go left;
        for (; $n * $n < $x * $x + $y * $y; $x --) {
            // Nothing here
        }
        // ($x,$y) is the rightmost lattice point on row $y that is inside the circle
        // There are exactly $x lattice points on the row $y that have x > 0
        $count += $x;
    }
    // Four quarters plus the center
    return 4 * $count + 1;
}

```

A naive implementation that checks `$n*($n+1)` points (and runs 1000 times slower but still computes `f(1001)` in less than 0.5 seconds) and the test suite (using the sample data provided in the question) can be found on github.
> 1 votes

# Answer
# APL (Dyalog Extended), 14 bytes

```
{≢⍸⍵≥|⌾⍀⍨⍵…-⍵}

```

Try it online!

Despite lacking the `i:` (inclusive range from -n to n) builtin of J, APL Extended has shorter syntax in other areas.

```
{≢⍸⍵≥|⌾⍀⍨⍵…-⍵}            Monadic function taking an argument n.
           ⍵…-⍵             n, n-1, ..., -n
      ⌾⍀                   Make a table of complex numbers
                            (equivalent to ∘.{⍺+1J×⍵} in Dyalog APL)
         ⍨                  with both real and imaginary parts from that list.
      |                       Take their magnitudes.
    ⍵≥                        1 where a magnitude are is at most n, and 0 elsewhere.
 ⍸                           Get all indices of truthy values.
≢                            Find the length of the resulting list.

```
> 1 votes

# Answer
# C (gcc), 60 bytes

```
r,a;f(x){for(a=r=x*x;a--;)r-=hypot(a%x+1,a/x)>x;x=4*r+1;}

```

Try it online!

Loops over the first quadrant, multiplies the result by 4 and adds one. Slightly less golfed

```
r,a;
f(x){
  for(a=r=x*x;a--;)
    r-=hypot(a%x+1,a/x)>x;
  x=4*r+1;
}

```
> 1 votes

# Answer
# Scala, 55 bytes

Try it online!

```
n=>(0 until n).map(i=>Math.sqrt(n*n-i*i).toInt).sum*4+1

```
> 1 votes

# Answer
# JavaScript (ES7), 42 bytes

```
f=(n,k=n)=>k--?((n*n-k*k)**.5<<2)+f(n,k):1

```

Try it online!
> 1 votes

# Answer
# Clojure/ClojureScript, 85 chars

```
#(apply + 1(for[m[(inc %)]x(range 1 m)y(range m):when(<=(+(* x x)(* y y))(* % %))]4))

```

Brute forces the first quadrant, including the y axis but not the x axis. Generates a 4 for every point, then adds them together with 1 for the origin. Runs in under 2 seconds for input of 1000.

Abuses the hell out of `for` to define a variable and save a few characters. Doing the same to create an alias for `range` doesn't save any characters (and makes it run significantly slower), and it seems unlikely that you're going to save anything by making a square function.
> 0 votes

# Answer
## Pyke, 14 bytes

```
QFXQX-_,B)s}}h

```

Try it here!
> 0 votes

# Answer
## Mathematica, 35 characters

```
f[n_]:=Sum[SquaresR[2,k],{k,0,n^2}]

```

Lifted from https://oeis.org/A000328

https://reference.wolfram.com/language/ref/SquaresR.html

`SquaresR[2,k]` is the number of ways to represent k as the sum of two squares, which is the same as the number of lattice points on a circle of radius k^2. Sum from k=0 to k=n^2 to find all the points on or inside a circle of radius n.
> 0 votes

# Answer
# Tcl, 111 bytes

```
lassign {1001 0 -1} r R x
while {[incr x]<$r} {set R [expr {$R+floor(sqrt($r*$r-$x*$x))}]}
puts [expr {4*$R+1}]

```

Simple discrete **x** loop over quadrant I, counting largest **y** using the Pythagorean Theorem at each step. Result is 4 times the sum plus one (for the center point).

The size of the program depends on the value of **r**. Replace `{1001 0 -1}` with `"$argv 0 -1"` and you can run it with any command-line argument value for **r**.

Computes f(1001) → `3147833.0` in about 1030 microseconds, AMD Sempron 130 2.6GHz 64-bit processor, Windows 7.

Obviously, the larger the radius, the closer the approximation to PI: f(10000001) runs in about 30 seconds producing a 15-digit value, which is about the precision of a IEEE double.
> 0 votes

# Answer
# Stax, 11 bytes

```
ä÷²M╨⌐■╝^₧░

```

Run and debug it
> 0 votes

# Answer
## Pascal, 128 B

This just walks the lattice grid and checks whether the distance to the origin is less than or equal to the radius.

```
type Z=integer;function f(r:Z):Z;var x,y,n:Z;begin
n:=0;for x:=-r to r do for y:=-r to r do n:=n+ord(sqrt(x*x+y*y)<=r);f:=n
end;

```

User time on a *busy* Linux x86‑64 machine for calculating `f(1001) = 3147833`: ca. 80 ms. Calculate just the points in one quadrant to cut the time.
> 0 votes

# Answer
# C (gcc), 116 bytes

```
a,x,y;c(r){for(x=-r;x<=r;x++)for(y=-r;y<=r;a+=x*x+y*y<=r*r,y++);return a;}main(r){scanf("%u",&r);printf("%d",c(r));}

```

**How it works**

This inefficient method draws a square around the circle then iterates through all lattice points \\$(x,y)\\$ within it and checking if \\$x^2+y^2 \le r^2 \\$.

Try it online!
> 0 votes

# Answer
# APL (Dyalog Unicode) (SBCS), 28 bytes

```
{1+4×⍵++/,(×⍨⍵)≥+/¨×⍨∘.,⍨⍳⍵}
{                          } dfn
                     ∘.,⍨⍳⍵  get cartesian square of 1..n
                   ×⍨        square each half of each pair
                +/¨          add each half of each pair
       +/,     ≥             count sums greater than
          (×⍨⍵)                  the input squared
 1+4×⍵+                      add the input, multiply by 4, and add 1

```

Finds the lattice points in one quadrant, then multiplies it by 4 and adds the points on the axes.

Try it online!
> 0 votes

# Answer
# 05AB1E, 9 bytes

```
(Ÿn¬sãO@O

```

Port of *@KamilDrakari*'s Japt answer, so make sure to upvote that answer as well!

Try it online or verify all test cases. (Runs `1001` in about 3.5 seconds on TIO.)

**Explanation:**

```
(          # Negate the (implicit) input-integer
 Ÿ         # Push a list in the range [(implicit) input,-input]
  n        # Square each inner value
   ¬       # Push the first item (without popping the list), which is input²
    s      # Swap so the list is at the top again
     ã     # Cartesian power of 2 to get all possible pairs
      O    # Sum all those inner pairs together
       @   # Check for each whether the input² is >= this value
        O  # Sum to get the amount of truthy values
           # (which is output implicitly as result)

```

Try it online with a step-by-step output.
> 0 votes

# Answer
# APL(NARS), 25 chars

```
{1+4×+/⌊√(⍵*2)-¨2*⍨¯1+⍳⍵}

```

test:

```
  f←{1+4×+/⌊√(⍵*2)-¨2*⍨¯1+⍳⍵}
  f 0
1
  f 1
5
  f 3
29
  f 10
317
  f 1000
3141549
  f 2000
12566345

```
> 0 votes

---
Tags: code-golf, geometry, restricted-time
---


title: Significant Whitespace: Cops

text:
# Question
Title: Significant Whitespace: Cops
For the purpose of this challenge, we'll define **whitespace** as *only* linefeeds (0x0A) and spaces (0x20). Note that most languages and regex flavours consider many other characters as whitespace as well, both inside and outside the ASCII range so you might not be able to make use of the corresponding built-ins.

## The Cops' Challenge

You should write a program or function in a language of your choice, which takes a string, consisting of ASCII (except NUL) characters, as input and outputs it with all whitespace removed. For example if you received the following input:

```
H e l l o,
 W o r l  d!

```

You should output

```
Hello,World!

```

Your submission will then be your *source code* with all whitespace removed (the same process as passing your solution as input to itself, although your solution may also contain characters outside the ASCII range). Your goal is to make it as hard as possible to figure out where whitespace needs to be inserted to recover a valid solution in your language of choice. Note that robbers may insert fewer whitespace than you removed, but not more. Also remember that robbers don't have to match your exact code, they just have to find any valid solution.

Your answer should contain the following:

* The language (and version if necessary) in which you wrote your solution.
* The byte count of your solution *before* removing whitespace.
* Your solution with whitespace removed.

Your solution may be either a program or function, but not a snippet and you must not assume a REPL environment. You may take input via STDIN, command-line argument or function argument and output via STDOUT, function return value or function (out) parameter.

In the interest of fairness, there must be a freely available interpreter or compiler for your chosen language.

You must not use built-ins for hashing, encryption or random number generation (even if you seed the random number generator to a fixed value). Your solution must be able to process any string of 100 characters or less in under 10 seconds on a reasonable desktop machine.

If your answer has not been cracked within 7 days (168 hours), you may reveal your own solution at which point your answer is considered *safe*. As long as you don't reveal your solution, it may still be cracked by robbers, even if the 7 days have already passed. The shortest safe answer wins (measured before removing whitespace).

If your answer does get cracked, please indicate this in the header of your answer, along with a link to the corresponding robber's answer.

**Go here for the robbers' part.**

### Uncracked Submissions

```
<script>site = 'meta.codegolf'; postID = 5686; isAnswer = false; QUESTION_ID = 103182;</script><script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script><script>jQuery(function(){var u='https://api.stackexchange.com/2.2/';if(isAnswer)u+='answers/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJeRCD';else u+='questions/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJO6t)';jQuery.get(u,function(b){function d(s){return jQuery('<textarea>').html(s).text()};function r(l){return new RegExp('<pre class="snippet-code-'+l+'\\b[^>]*><code>([\\s\\S]*?)</code></pre>')};b=b.items[0].body;var j=r('js').exec(b),c=r('css').exec(b),h=r('html').exec(b);if(c!==null)jQuery('head').append(jQuery('<style>').text(d(c[1])));if (h!==null)jQuery('body').append(d(h[1]));if(j!==null)jQuery('body').append(jQuery('<script>').text(d(j[1])))})})</script>
```

# Answer
> 18 votes
# Haskell, 100 bytes, cracked by nimi

```
main=interact$iddoidlinesidwordsdoidoidoid=doiddoid<-dooiidoid<-dooiddoiddodoid

```

This is a full program and a dadaistic poem.

---

**Code with withspace** (Try it online!)

```
main=interact$id doid lines id words
doid oi d o id=do
 iddoid<-do oi id
 oid<-do o iddoid
 do d oid

```

Still looking quite poetic, if you ask me.

**De-obfuscated**

```
main = interact f
f s = do
 l <- lines s
 w <- words l
 id w

```

**Explanation**

The `do`-notation is only syntactic sugar, so `f` can equivalently be written as

```
f s = lines s >>= words >>= id

```

For lists the `>>=`-operator is defined as `concatMap`, so `f` becomes

```
f = concat . map id . concat . map words . lines

```

So given an input `"a b\nc"`, `lines` splits the input at newlines `["a b","c"]`, `words` splits each line at white space yielding `[["a","b"],["c"]]` (as I realised only now this includes newlines, so `lines` actually isn't needed). Concatenating once gives `["a","b","c"]`, `id` is the identity function and as such has no effect and the final concatenation yields the string `"abc"`.

# Answer
> 13 votes
# C, 475 bytes, cracked by Riley

Certain parts of C make it really really easy to see where whitespace should go. The c pre-processor, however, does not. So this code is sort of in two halves: up to line 17 (236 characters with whitespace) the code is virtually unobfuscated, and after that (239 characters with whitespace), good luck!

Not gonna win this competition by a long shot, but I wanted to see what could be done with the c pre-processor.

```
#include<unistd.h>#defineachar#defineb*#definecwrite#definedstdin#defineestdout#definefread#defineg(#defineh)#defineiwhile#definejif#definek0#definel&#definem,#definen=#defineo;#definep1#definegpmlmlh#defineabo#definemldmp#definejgdoabo#definelbabod#definegfhaboc#definejgmben#definepmlfg#definegpmlbintmain(){ajgajgmljgigpmlkmlgpmlhjgd!=''&&gpm!='\n'gfgpmlgpmlo}

```

Compiles (with warnings, if you enable them) with `gcc -std=c89 -ansi` and works like `cat file | ./a.out`

---

This was cracked much faster than I thought, congrats! My strategy was to use `#defines` to remove obvious token boundaries (like ';') and then use more `#defines` to make it REALLY unintuitive how they were shuffled around.

This, by the way, is what the code looks like after only the obvious whitespace has been added:

```
#include <unistd.h>
#define a char
#define b *
#define c write
#define d stdin
#define e stdout
#define f read
#define g (
#define h )
#define i while
#define j if
#define k 0
#define l &
#define m ,
#define n =
#define o ;
#define p 1
// thus begins the obfuscation
#define gpmlmlh
#define abo
#define mldmp
#define jgdoabo
#define lbabod
#define gfhaboc
#define jgmben
#define pmlfg
#define gpmlb
int main(){
    ajgajgmljgigpmlkmlgpmlhjgd!=''&&gpm!='\n'gfgpmlgpmlo
}

```

# Answer
> 10 votes
# Octave, 69 bytes, SAFE!

```
@(U)eval([85329685312682956148388531268295156241''])

```

**Input format:** Newlines can't be inputted directly in the command prompt. Create the string by concatenation like this:

```
str = ['This is ',10,'a',10,'string']
str = This is
a
string

```

Call the function like this (add whitespace):

```
f=@(U)eval([85329685312682956148388531268295156241''])
f(['This is ',10,'a',10,'string'])

```

**Original code:**

You only needed 66 bytes for this to work, but I wrote 69 in the header in order to not give away too much information.

The original code looks like this:

```
@(U)eval([853 296 853 126 829 561 48 38 853 126 829 51 562 41 ''])

```

**Explanation:**

```
@(U)eval(.....)    % Anonymous function taking U as the input variable

```

`U` is code point `85` in the ASCII table, so it would appear like the first space should be after `85`. *Wrong!*

If we insert the space after `853` instead, we should get character number `853`, right..? Using `char` to check if that's a recognizable character:

```
char(853)
warning: range error for conversion to character value

```

However, we don't use `char` in the code, we use the shorter version where we concatenate the numbers with an empty string `[853 '']`. Instead of giving an out of range error, the shorter version simply takes the numbers modulus 256.

It just so happen to be that `85+3*256 = 853`. While `char(853)` gives a warning, `[853,'']` returns `U`.

The obvious way to do this task in Octave is:

```
@(U)U(U~=10&U~=32)

```

We know that there has to be an opening parentheses (code point 40) after the first `U`. `29` obviously doesn't fit so we shift the space one further right and get `296`. `mod(296,256) = 40`. Bingo!

Continue like this and end up with the sequence:

```
[853 296 853 126 829 561 48 38 853 126 829 51 562 41 '']
ans = U(U~=10&U~=32)

```

Finally, we use `eval` to turn the string into code.

# Answer
> 7 votes
# Befunge-93, 58 bytes, Safe!

```
_vv$v<~:!`:<#^0*@-:0*5|845\+`-v0,<#-^<

```

Try it online!

**Original Program**

```
_vv
 $ v<
 ~:!`
 :<#^0
*  @
-:0
*5 |
8
45
\+`
-
v0,<
#-
^<

```

Try it online!

The trick to this was that the path of execution was more vertical than horizontal, then various spaces were inserted at random in the code to further shuffle the vertical paths. Once the line breaks and whitespace were finally removed, there was hopefully then very little to indicate how the operations related to each other.

In case that wasn't difficult enough, I also threw in a bit of interleaving, so a number of operations ended up being executed by different code paths flowing perpendicular to each other. The idea being that if you thought you'd found the correct position for a particular command, you wouldn't realise you might need to use it again later in the code.

Not sure if it was worth all that effort trying to make things complicated, or people didn't even bother trying to solve it. :)

**Code Explanation**

```
_      Since an empty stack is treated as zero, this initially just branches right.
v      The program flow is then directed downwards.
$      And this drop command initially does nothing because the stack is still empty.
~      A character is read from stdin.
::     Two duplicates are created.
55+-   We subtract 10 from the first copy (the 0- is just a nop to confuse things).
\48*-  And subtract 32 from the second copy.
*      The product of those two will be zero if the character is a newline or space.
_      So if we got whitespace, our branch goes right again repeating the loop.

v      If not, we go left, wrapping around till we hit the down arrow in column 3.
:<:    Again we make two duplicates of the character.
0`!|   One copy is used to compare if it's not greater than zero.
@      If it's not (i.e. it's the EOF), the branch goes up and we terminate.
<      Otherwise we go down and to the left.
,      Output the second copy of the character, leaving one remaining on the stack.
0      Push a zero to force the next branch right.
v      Redirect the flow down, wrapping to the top again.
_      Back at our initial branch, the zero we pushed forces us right.
v      Again the program flow is directed downwards.
$      And the drop command gets rid of the last duplicate character.
~      So now we're back reading the next character and the loop repeats.

```

# Answer
> 7 votes
## JavaScript ES6, 199 bytes, cracked by SLuck49

A rather bulky entry with 33 bytes of whitespace to add.

```
s=>eval(atob`ISYgJiAtOkI8Qk97BRBeaxZFShoUZSsiOGkMenNy`.replace(/./g,(c,i)=>String.fromCharCode(c.charCodeAt()^(k+="SecretCode".split(/\w/)[i%11].length)),k=0)).join``

```

# Answer
> 6 votes
# \>\<\>, 40 bytes, Cracked by Teal pelican

```
v<<i/\:=::a?0/>/1?o-=="?;">^

```

I used fishlanguage.com by the way, just in case there are differences between interpreters.

# Answer
> 5 votes
# C#6, 201 bytes, Cracked by Link Ng

```
usingSystem.Linq;_=>string./**/#iftrueJoin(/*"*//*/""/**//*/"*/",#elseConcat(//*/,#endiffrommin""letp=$@"{@""[1]}"fromiin(_.Replace(p,@""))where!new[]{p[0]^32^10}.Contains(i)select@i);

```

184 bytes collapsed, leaving you 17 bytes of whitespace.

Cracked solution using the `Concat` whereas my intended solution used the `Join`, here's the intended solution:

```
_=>string./**/
#if true
Join(/*"* //*/""/**//*/"* /",#elseConcat(//*/,
#endif
from m in" "let p=$@"{@"  "[1]}"from i in(_.Replace(p,@"
"))where!new[]{p[0]^32^10}.Contains(i)select@i);

```

# Answer
> 5 votes
# MATL, 22 bytes. Cracked and cracked.

This is a program that takes input through STDIN and produces the output through STDOUT.

Code without spaces or newlines:

```
t'@*'dm1e5%Mdw%Y(

```

The **input format** is a little awkward because of how MATL takes string input. Strings with newlines cannot be entered directly through STDIN, because each input has to be a single line (newline marks the end of input). So the format is as follows:

1. A string is enclosed with **single quotes**. If the string content includes single quotes, they are **escaped by duplicating**. Example: `'I''m a string'`
2. To enter a string with newlines one needs to split the string at newlines and concatenate everything (by means of square brackets), including numbers as **ASCII codes**. For example, consider the string formed by my first and last names with a newline in between. It would be entered as `['Luis' 10 'Mendo']`.

This allows entering any other (possibly non-printable) ASCII codes. So the string in item 1 above could be alternatively entered as `['I' 39 'm ' 97 32 'string']`. Check it here.

The only condition is that at least one of the parts within the brackets is a string. That forces any numbers to be interpreted as ASCII codes when concatenating.

~~Sorry about the awkward~~ Good luck using this format!

## Original solution

```
t' @ *'dm1e 5%
Mdw%Y
(

```

Each `%` is a comment symbol, and so the rest of the line is ignored.

Spaces do nothing, but serve as separators. For example, `1e5`, without the space, would be interpreted as the number `100000`.

`t` takes the input and duplicates it.

`' @ *'` pushes that string, and `d` computes its consecutive differences, which gives `[32 -32 10]` (the `-32` is useless).

`m` gives a logical row array indicating which characters are `32` or `10` (or `-32`).

`1` followed by `e` reshapes as a row. This is no-op here.

`5` followed by `M` pushes `1` again (last input to the most recent multiple-input function, which is `e`).

`d` computes consecutive differentes of `1`, and so gives `[]` (empty array).

`w` swaps, and finally `(` assigns `[]` to whitespace characters, i.e. removes them.

# Answer
> 5 votes
# Java, 3241 + 28 Bytes for a big Integer import

This entry is solely to prove the possibility of a purely cryptographically secure entry. I believe this is within the rules, but if it is against the spirit, please let me know and I will delete out of fairness. I will leave this "unsafe" indefinitely until such a time when (and if) a crack gets found. This is a monstrosity and could surely be further optimized, but here it is.

```
interfacer{staticvoidmain(String[]A){Strings=",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",q=",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",a="",b="";for(Stringt:s.split(",")){a+=t.length();}for(Stringt:q.split(",")){b+=t.length();}if((newBigInteger(a).multiply(newBigInteger(b)).toString()).equals("3649760552772806991406184564114682549877113954361462782925976763675666255653486225665808494957477900238166874367635068317805381406282572366371821972593595701388544127398102379288357379612333197280663769935384647844344358594407966485992727383589962048236726744715096711312156760311643104858212670342667229690568585229658813910569607411855770280546861422837629553847973043531578541545436967345783407835402474562087790816775240815912495599135241317")){System.out.println(A[0].replaceAll("","").replaceAll("\n",""));}}}

```

Out of fairness to robbers, here is it with all the "obvious" whitespace added.

```
interface r {

    static void main(String[] A) {
        String s = ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", q = ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,", a = "", b = "";
        for (String t : s.split(",")) {
            a += t.length();
        }
        for (String t : q.split(",")) {
            b += t.length();
        }
        if ((new BigInteger(a).multiply(new BigInteger(b)).toString()).equals("3649760552772806991406184564114682549877113954361462782925976763675666255653486225665808494957477900238166874367635068317805381406282572366371821972593595701388544127398102379288357379612333197280663769935384647844344358594407966485992727383589962048236726744715096711312156760311643104858212670342667229690568585229658813910569607411855770280546861422837629553847973043531578541545436967345783407835402474562087790816775240815912495599135241317")) {
            System.out.println(A[0].replaceAll("", "").replaceAll("\n", ""));
        }
    }
}

```

Good luck, I would love to see this cracked. In fact I will even institute an unlimited bounty on this. If at any point you do crack this, you will be awarded **500 rep** infinite accolade on stack exchange (as well as likely a wonderful mathetatical paper).

---

# Answer
> 4 votes
# Ruby, 86 bytes + 1 flag = 87 (cracked by Dom Hastings)

Requires command-line flag `-p`.

```
eval"(T$}{(!//;:678?32.&&)".gsub(/|(.)/){$1&&$&.ord.^($'.count('')).chr}

```

The code is actually valid in this form, it's just a no-op.

# Answer
> 4 votes
# RProgN, 15 Bytes Cracked!

```
''`R""`R

```

You can toy with the code here. A relatively simple solution, hopefully the annoying nature of how RProgN handles strings will leave this uncracked.

## Original Program

```
' ' ` R
"
" ` R

```

## Explination

Firstly, the input is implicitly pushed to the stack. Stack: `<INPUT>`

Then, we use ' ' to push a space to the stack. Stack: `<INPUT> " "`

the \` actually tries to push a string represented by \`(WORD) but because there's whitespace after it, it just pushes an empty string. Stack: `<INPUT> " " ""`

The R here is sugar for the Replace command. Stack: `<INPUTWITHOUTSPACES>`

Next, the "NEWLINE" pushes a string containing a newline, which is nice because RProgN doesn't use escapes, it just straight up lets you push a string like that. Stack `<INPUTWOSPACES> "\n"`

Then, we use the \` trick again, and Replace, which gives our output.

# Answer
> 4 votes
# Beam, 72 bytes, Safe!

Now for a 2d language. Can be played with on TIO Nexus.

```
s'''>`+++)+Ss`n\
 n`sS+(+++`<``/
 >rgn\
 ^ @<(\
     H         <
 ^    /

```

A fairly straight forward program without a lot in there to try and fool people.

```
s'''>`+++)+Ss`n\ # Sets the memory slot 0 to 0, 10 to 10 and 32 to 32. n will redirect down
 n`sS+(+++`<``/  # since memory != store. \ is a red herring and not hit.
 >rgn\           # read in from input and set store to memory value. For all characters
 ^ @<(\          # other than space, LF and end of input this will be different and n will
     H         < # redirect down then through to the print and back to read. Space, LF and
 ^    /          # end of input get directed to the ( which tests for 0. This will redirect
                 # space and LF to path back to read, otherwise it will skip over and halt

```

# Answer
> 4 votes
# Labyrinth, 127 bytes

```
);""{"".@"-;,""""":"##"*"(:"+":}-;{";;"*#{:;"#""+("-;"";;"})"";""""""""

```

Hopefully I did this right :) this is my first cops and robbers entry.

## Original Code

```
 ) ;""{"".@
"-;, "" ""
"  :
" ##
" *
" (:
"  +
"  :}-;{
"    ; ;
" *#{: ;
" #    "
" +("-;"
"    ; ;
"    })"
"      ;
""""""""

```

# Answer
> 3 votes
# C, 140 bytes, cracked by Riley

Let's start with an easy one.

```
#include<stdio.h>intmain(){inta=getchar();while(a!=EOF){//\a=getchar();if(a!=10&&a!=32)//\\putchar(a^10^32);putchar(a);a=getchar();}}

```

(I hope I'm doing this right.)

# Answer
> 3 votes
# Befunge 98, 65 bytes, cracked by Pietu1998

```
~v>#@>::':'0--\'[';--!8v1+!*1+j!j,v>#@

```

# Original program

```
~v           >#@
 >::':'0--\'[';--!8v1+!
*1+j !j,     v     >
#@

```

# Answer
> 3 votes
## JavaScript ES6, 380 bytes, safe

This is the kind of entry that I was initially planning to release. It's huge and has nearly no chance to win, but I *think* it should be cryptographically strong enough to withstand 7 days. Now, I may be proven wrong!

67 bytes of whitespace to add.

```
s=>{for(k=`|||`.split`|`.map(s=>s.replace(/\s/g,c=>(k-=(c<'')+1,n=n<<2|k&3),k=n=0)&&n),x=10106050295,y=-4955405499,i=32,d=2654435769,t=d*i;i--;y-=(x<<4^x>>>5)+x^t+k[t>>>11&3],t-=d,x-=(y<<4^y>>>5)+y^t+k[t&3]);returns[atob(([x,y].map(n=>String.fromCharCode(n&255,n>>8&255,n>>16&255,n>>24)).join``))](/[\n]/).join``}

```

### Solution

This is an implementation of the Extended Tiny Encryption Algorithm. The 64-bit whitespace-encoded key expands to the following 128-bit key:

```
K = [0xd224de37, 0x89e34e79, 0xe34e7748, 0x939e2789]

```

*Source: Wikipedia*

Once decrypted and converted to ASCII, the 64-bit block `[x, y]` reads as `c3BsaXQ=`, which is the Base64 encoded representation of `split`.

```
let f =

s=>{for(k=`

|

  |

|

 `.split`|`.map(s=>s.replace(/\s/g,c=>(k-=(c<' ')+1,n=n<<2|k&3),k=n=0)&&n),x=10106050295,y=-4955405499,i=32,d=2654435769,t=d*i;i--;y-=(x<<4^x>>>5)+x^t+k[t>>>11&3],t-=d,x-=(y<<4^y>>>5)+y^t+k[t&3]);return s[atob(([x,y].map(n=>String.fromCharCode(n&255,n>>8&255,n>>16&255,n>>24)).join``))](/[ \n]/).join``}

console.log(f(`H e l l o
W o r l d`))
```

# Answer
> 3 votes
# Whitespace, ~~81~~ 74 bytes, Cracked!

```

```

Human readable version:

```
ttttttttttttttttttttt (21 tab characters)

```

I know this is an old challenge but hopefully someone is willing to have a go at cracking this. I attempted to optimise for bytecount but it may be possible to make something shorter with the same number of tab characters.

## Original Solution

```

```

Try it online!

## Explanation

```
ssstsssssn ; push 32
nssn  ; label ''
sns   ; dup 32 to use as address
tnts  ; getchar and store at address 32
sns   ; dup 32 to use for later subtraction
sns   ; dup 32 to use as address
ttt   ; retrieve character value
tsst  ; subtract 32 - char
ntsn  ; jez '' if result is 0 char was a space, loop without output
sns   ; dup 32 to use as address
ttt   ; retrieve character value
ssststsn ; push 10
tsst  ; subtract char - 10
ntsn  ; jez '' if result is 0 char was a linefeed, loop without output
sns   ; dup 32 to use as address
ttt   ; retrieve character value
tnss  ; putchar since it was not a space or linefeed
nsnn  ; jump '' loop

```

I didn't keep notes for this solution but I think I'd tried to keep the stack low by retrieving the value repeatedly which also inflated the tab count. The hope was to force a slightly unusual approach to meet the target tab count.

@thaliaarchi's 65 byte solution saves characters by leaving non-space/newline characters on the stack when it loops, this was an alternative approach I considered but didn't end up going with (though I also had a higher bytecount there :D). The 68 byte cracked solution with reordered comparisons and a -0 constant to match the required tab count very neatly hits the target with a tidy byte saving, only leaving garbage on the stack when a newline is encountered.

# Answer
> 2 votes
# , 37 bytes Cracked by nmjcman101

```
OVrS200@"kIi|D@"Aüî|D@"
```

Since this has unprintables, here is the readable version:

```
O<esc>Vr<C-a>S200<esc>@"kIi<C-v><C-v><esc>|D@"<esc>Aüî<esc>|D@"

```

Or if you prefer, a hexdump:

```
00000000: 4f1b 5672 0153 3230 301b 4022 6b49 6916  O.Vr.S200.@"kIi.
00000010: 161b 7c44 4022 1b41 fcee 1b7c 4440 22    ..|D@".A...|D@"

```

# Answer
> 2 votes
# Vitsy, 73 bytes, safe

This is downright evil.

```
5mW3m7m7m2mD&EPamX}<m15mEnl9mZD\[4m]^P-cm(D_2-3*bmD1-dmrnu-'

```

Good luck! 13 items of whitespace to add.

Original code:

```
5m
W3m7m
7m
2m
D&EPamX}
<m1
5mEn
l9mZ
D
\[4m]
^P-cm(D
_2-3*
bmD1-dmrnu-
'

```

Try it online!

This roughly simplifies down to:

```
<m1
W2\[2m]Z
l\[D&EP^P-_2-3*D1-rnu-(DX}]

```

# Answer
> 2 votes
# Minkolang v0.15, 88 bytes, Cracked!

```
$oI[dd""=$r'10'=1J,?1R]r$O3.14$$$Cdollars>$$$Ceverywhere>x

```

Try it online!

# Answer
> 1 votes
# reticular, 43 bytes, cracked

```
ISBqv<>>$$4jE:d/v$v?c+91d/v?E;!?l$/o$

```

The version on TIO is outdated, but you can get yourself a copy from the github.

# Answer
> 1 votes
## C#, 159 bytes, Cracked by milk

```
usingSystem.Linq;s=>string.Join("",string.Join("",s.Split(@"".Replace(newstring((char)0x0D,1),"").ToCharArray())).Select(c=>c+""!=""?c+"":"").ToArray());

```

153 collapsed so only 6 bytes of whitespace to find, shouldn't be too hard...

# Answer
> 1 votes
# S.I.L.O.S, 159 bytes Safe!

```
loadLinedef:lblgetagetzzzz/za=256:aX=getax=Xy=Xz=xx-10x|ifxbGOTOx:by-32y|ifycGOTOx:cprintCharX:xa+1z+1x=getaifxa:b

```

Should be fairly trivial. It is my first cops and robbers entry.

No one attacked it, probably due to the esoteric nature of my own language. Seems like a sleazy way to slide by, but it doesn't really matter as shorter ones are safe.

```
loadLine
def : lbl geta get z zz
z/z
a=256
:a
X=get a
x=X
y=X
z=x
x-10
x |
if x b
GOTO x
:b
y-32
y|
if y c
GOTO x
:c
printChar X
:x
a+1
z+ 1
x=get  a
if x a
:b

```

Feel free to try it online

# Answer
> 1 votes
# Wolfram, 132

Probably has more that one solution (hint: Mersenne)

```
StringReplace[#,""->"",Limit[x/(x-1),x->Boole[PrimeQ[
212821282128228281282128228821282128212821282-1]]]]&

```

**Solution**

```
StringReplace[#," "->"",Limit[x/(x-1),x->Boole[PrimeQ[
2 128 2 128 2 128 2 2 8 2 8 128 2 128 2 2 8 8 2 128 2 128 2 128 2 128 2-1]]]]&

```

# Answer
> 1 votes
# Vyxal, 11 bytes, 7 whitespace, cracked by lyxal

```
#ȧ‛(#FṘ₴#Ṙ‛

```

Try it Online! Should be pretty easy.

Lyxal got my intended solution exactly.

# Answer
> 1 votes
# Vyxal 3, 11 bytes, 1 whitespace needed

```
#?“""₉r""₉r

```

Try it Online!

Should be really really easy.

# Answer
> 0 votes
# tcc, 850 bytes

To avoid pasting a very long line I passed this through tr -d '\n ' | fold -b -w 60.

```
#!/usr/bin/tcc-run#include<stdio.h>typedefunsignedcharu;um[]
={104,105,16,152,94,131,43,42,112,214,53,207,116,170,185,210
};intmain(){uS[256];uk[256];ui,j,t;intc,n=0;FILE*f;f=fopen(_
_FILE__,"r");/*cannotfail*/while(-1!=(c=fgetc(f)))if(c==''||
c==10)k[++n]=c;fclose(f);i=0;do{S[i]=i;}while(++i!=0);j=0;i=
0;do{j=j+S[i]+k[i%n];t=S[i];S[i]=S[j];S[j]=t;}while(++i!=0);
i=0;do{if(S[i]!=m[i])j=1;}while(++i<sizeof(m));if(j==1){i=0;
do{printf("%d,",(int)S[i]);}while(++i<sizeof(m));printf("\n"
);}else{while(-1!=(c=fgetc(stdin)))if(c!=''&&c!=10)fputc(c,s
tdout);}returnj;}

```

---
Tags: code-golf, string, cops-and-robbers, whitespace
---