title: All your base palindromic belong to us

text:
# Question
Title: All your base palindromic belong to us
Generate the sequence *number of bases in which `n` is a palindrome* (OEIS A126071).

Specifically, the sequence is defined as follows: given a number `n`, express it in base `a` for `a = 1,2, ..., n`, and count how many of those expressions are palindromic. "Palindromic" is understood in terms of reversing the base-`a` digits of the expression as atomic units (thanks, @Martin Büttner). As an example, consider `n = 5`:

* `a=1`: the expression is `11111`: palindromic
* `a=2`: the expression is `101`: palindromic
* `a=3`: the expression is `12`: not palindromic
* `a=4`: the expression is `11`: palindromic
* `a=5`: the expression is `10`: not palindromic

Therefore the result for `n=5` is `3`. Note that OEIS uses bases `2, ..., n+1` instead of `1, ..., n` (thanks, @beaker). It's equivalent, because the expressions in base `1` and `n+1` are always palindromic.

The first values of the sequence are

```
 1, 1, 2, 2, 3, 2, 3, 3, 3, 4, 2, 3, 3, 3, 4, 4, 4, 4, 2, 4, 5, ...

```

Input is a positive integer `n`. Output is the first `n` terms of the sequence.

The program should theoretically work (given enough time and memory) for any `n` up to limitations caused by your default data type in any internal computations.

All functions allowed. Lowest number of bytes wins.

# Answer
## Pyth, 13 bytes

```
mlf_ITjLdSdSQ

```

The brevity of this is mostly due to the `I`nvaluable "`I`nvariant" command.

```
msf_ITjLdSdSQ       implicit: Q=input
m         d         map lambda d over
           SQ       Inclusive range 1 to Q
      jLdSd         Convert d to all the bases between 1 and d
  f                  filter lambda T:
   _IT                 is invariant under reverse
 l                  number that are invariant under reverse

```

If `True` is an acceptable output for `1`, `msm_IjdkSdSQ` (12 bytes) works.

Try it here.
> 9 votes

# Answer
# Jelly, 12 bytes

```
bRµ=UP€S
RÇ€

```

Try it online!

An old 14-byte version (The Jelly interpreter had a bug that made converting to unary impossible)

```
bR‘$µ=UP€S
RÇ€

```

Try it online!

### How it works

```
bR‘$µ=UP€S  Helper link. Argument: z

 R‘$        Apply range and increment, i.e., map z to [2, ..., z + 1].
            In the non-competing version R simply maps z to [1, ... z].
b           Convert z to each of the bases to the right.
    µ       Begin a new, monadic chain. Argument: base conversions
     =U     Compare the digits of each base with the reversed digits.
            = has depth 0, so [1,2,3]=[1,3,3] yields [1,0,1].
       P€   Take the product of the innermost arrays.
         S  Sum all resulting Booleans.

RÇ€         Main link. Argument: n

R           Yield [1, ..., n].
 Ç€         Apply the helper link to each.

```
> 7 votes

# Answer
# MATL, 19 ~~20~~ bytes

```
:"0@XK:Q"K@:YAtP=A+

```

Uses current release (10.1.0), which is earlier than this challenge.

**Try it online**!

### Explanation

```
:            % vector [1,2,...,N], where "N" is implicit input
"            % for each number in that vector
  0          % push 0
  @          % push number 1,2,...N corresponding to current iteration, say "n"
  XK         % copy n to clipboard
  :Q         % vector [2,3,...,n+1]
  "          % for each number "m" in that vector
    K        % push n
    @:       % vector [1,2,...,m]
    YA       % express n in base m with symbols 1,2,...,m
    tP       % duplicate and permute
    =A       % 1 if all entries are equal (palindrome), 0 otherwise
    +        % add that number
             % implicitly close the two loops and display stack contents

```
> 4 votes

# Answer
## CJam, 20 bytes

```
ri{)_,f{)b_W%=}1bp}/

```

Test it here.
> 2 votes

# Answer
## ES6, 149 bytes

```
n=>[...Array(n)].map((_,i)=>[...Array(i)].reduce((c,_,j)=>c+(''+(a=q(i+1,j+2,[]))==''+a.reverse()),1),q=(n,b,d)=>n<b?[n,...d]:q(n/b|0,b,[n%b,...d]))

```

Works for bases \> 36 too.
> 2 votes

# Answer
# Python 2, 97 bytes

```
c=1;n=int(input())
for b in range(2,n):
	a=[];z=n
	while z:a+=[z%b];z//=b
	c+=a[::-1]==a
print c

```

My first Python post, actually my first Python code at all
probably has some golfing potential.

Try it online!
> 2 votes

# Answer
# JavaScript (ES6), ~~105~~ 95 bytes

```
f=(n,b)=>b?b<2?1:f(n,b-1)+([...s=n.toString(b)].reverse().join``==s):n<2?[1]:[...f(n-1),f(n,n)]

```

## Explanation

Takes a number from 1 to 36 (the limitation of base conversion in JavaScript) and returns an array of the sequence.

Recursive function that checks for palindromes when a base is passed, else returns the sequence if just `n` is passed.

```
f=(n,b)=>

  // Base palindrome checking
  b?
    b<3?1:                 // return 1 for base-1, since toString(2)
    f(n,b-1)+(             // return the sum of all lower bases and check  this
      [...s=n.toString(b)] // s = n in base b
      .reverse().join``==s // add 1 if it is a palindrome
    )

  // Sequence generation
  :
    n<2?[1]:               // return 1 for the first value of the sequence
    [...f(n-1),f(n,n)]     // return the value for n after the previous values

```

## Test

```
var solution = f=(n,b)=>b?b<2?1:f(n,b-1)+([...s=n.toString(b)].reverse().join``==s):n<2?[1]:[...f(n-1),f(n,n)]
```

```
<input type="number" oninput="result.textContent=solution(+this.value)" />
<pre id="result"></pre>
```
> 1 votes

# Answer
# Haskell, 88 bytes

```
a!b|a<b=[a]|1>0=mod a b:(div a b)!b
f n=[1+sum[1|x<-[2..y],y!x==reverse(y!x)]|y<-[1..n]]

```
> 1 votes

# Answer
# Jelly, 8 bytes

```
bRfU$Lµ€

```

Try it online!

Alternatively:

```
bRŒḂ€Sµ€

```

Try it online!
> 1 votes

# Answer
# PHP, 73+1 bytes

```
while(++$i<$argn)$c+=strrev($n=base_convert($argn,10,$i+1))==$n;echo$c+1;

```

works for bases `1` to `36`. Run as pipe with `-nR` or try it online.
> 1 votes

# Answer
# PHP, 92+1 bytes:

```
for($b=$c=1;$b++<$n=$argn;$c+=$a==array_reverse($a))for($a=[];~~$n;$n/=$b)$a[]=$n%$b;echo$c;

```

works for all bases. Run as pipe with `-nR` or try it online.
> 1 votes

# Answer
# \>\<\>, 197+2 Bytes

+2 for -v flag

```
:1+0v    ;n\
1\  \$:@2(?/
:<~$/?)}:{:*}}@:{{
\   \~0${:}
>$:@1(?\::4[:&r&r]:$&@@&%:&@&$@-$,5[1+{]$~{{:@}}$@,$
~~1 \  \
?\~0>$:@2(?\$1-:@3+[}]4[}1-]=
 \  /@@r/!?/
r@+1/)0:<
  /?/$-1$~<
~$/       \-1

```

tio.run doesn't seem to return any output for n\>1, but you can verify it on https://fishlanguage.com. Input goes in the "Initial stack" box.
> 1 votes

# Answer
# Japt, 10 bytes

```
õ_õ!ìZ èêS

```

Try it

---

## Explanation

```
õ              :Range [1,input]
 _             :Map each Z
  õ            :  Range [1,Z] (let's call each X)
   !ìZ         :   Convert Z to a base X digit array
       è       :  Count
        êS     :   Palindromes

```
> 1 votes

# Answer
# Python 2, 85 bytes

```
def f(a):b,c=2,0;exec'd,m=[],a\nwhile m:d+=[m%b];m/=b\nc+=d[::-1]==d;b+=1;'*a;print c

```

Try it online!

Expects an integer as an argument.

Explanation:

```
# named function
def f(a):
    # initialize variable to track base (b) and to track palindromes (c)
    b,c=2,0
        # construct code
        '
        # initialize variable to store remainders (m) and to track divisor (d)
        m,d=[],a
        # while d is not zero,
        # add the current remainder to the array
        # and divide d by the base and assign the result back to d
        while d:m+=[m%b];d/=b
        # False == 0 and True == 1, so add 1 to total if m == reversed(m)
        c+=m[::-1]==m;
        # increment base
        # terminate with ; so that next statement can be executed separately
        b+=1;
        '
    # execute constructed statement (a) times
    exec'....................................................'*a
    # print result
    print c

```
> 1 votes

# Answer
# Husk, 13 bytes

```
mλṁoS=↔`B¹ḣ)ḣ

```

Try it online!

not sure if I can avoid using a lambda here.
> 1 votes

# Answer
# JavaScript (Node.js), 80 bytes

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

```

Try it online!

Add 1 at last manually
> 1 votes

# Answer
# Perl 5 `-Minteger -pa`, 81 bytes

```
map{@n=($t="@F")%$_;push@n,$t%$_ while$t/=$_;$\+="@n"eq"@{[reverse@n]}"}2..$_+1}{

```

Try it online!
> 0 votes

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


title: Can you decrypt me? (Cops)

text:
# Question
Title: Can you decrypt me? (Cops)
# Can you decrypt me?

## Cops

Cops, post obfuscated code that hides a number \\$n\\$ (n must not be greater than the program length) inside its code. If \\$n\\$ chars are changed (no additions or deletions), the program outputs exactly one \\$n\\$ (any amount of whitespace before or after is allowed.) Otherwise, it outputs something else. Both programs may not error, and there can be multiple solutions.

## Example

```
print(2)

```

N is 1.

---

Robbers' post:

```
print(1)

```

## Scoring

For the cops, the user with the most uncracked posts wins. If there is a tie, the user with the total minimum byte count wins.

# Answer
# C++ (gcc), 5204 bytes Cracked (intended way also listed)

```
#include <iostream>
using namespace std;
string secret = "secret";
void f1(){if(secret.length()!=6){cout<<"1111111";return;}int a[6]={secret[0]-' ',secret[1]-' ',secret[2]-' ',secret[3]-' ',secret[4]-' ',secret[5]-' '};for(int i=0;i<5;i++){if(a[i]>=a[i+1]){cout<<"1111111";return;}}for(int i=0;i<6;i++){if(a[i]<=0||a[i]>111){cout<<"1111111";return;}}for(int i=1;i<=111;i++){for(int j=i+1;j<=111;j++){for(int k=j+1;k<=111;k++){for(int l=k+1;l<=111;l++){for(int m=l+1;m<=111;m++){for(int n=m+1;n<=111;n++){int b[6]={i,j,k,l,m,n};bool yay=false;for(int o=1;o<(1<<6);o++){for(int p=1;p<(1<<6);p++){int asum=0;int bsum=0;for(int q=0;q<6;q++){if(o&(1<<q)){asum+=a[q];}if(p&(1<<q)){bsum+=b[q];}}if(asum==bsum){yay=true;break;}}if(yay){break;}}if(!yay){cout<<"1111111";return;}}}}}}}}
void f2(){if(secret.length()!=6){cout<<"1111111";return;}int a[6]={secret[0]-' ',secret[1]-' ',secret[2]-' ',secret[3]-' ',secret[4]-' ',secret[5]-' '};for(int i=0;i<5;i++){if(a[i]>=a[i+1]){cout<<"1111111";return;}}for(int i=0;i<6;i++){if(a[i]<=0||a[i]>111){cout<<"1111111";return;}}for(int i=1;i<=111;i++){for(int j=i+1;j<=111;j++){for(int k=j+1;k<=111;k++){for(int l=k+1;l<=111;l++){for(int m=l+1;m<=111;m++){for(int n=m+1;n<=111;n++){int b[6]={i,j,k,l,m,n};bool yay=false;for(int o=1;o<(1<<6);o++){for(int p=1;p<(1<<6);p++){int asum=0;int bsum=0;for(int q=0;q<6;q++){if(o&(1<<q)){asum+=a[q];}if(p&(1<<q)){bsum+=b[q];}}if(asum==bsum){yay=true;break;}}if(yay){break;}}if(!yay){cout<<"1111111";return;}}}}}}}}
void f3(){if(secret.length()!=6){cout<<"1111111";return;}int a[6]={secret[0]-' ',secret[1]-' ',secret[2]-' ',secret[3]-' ',secret[4]-' ',secret[5]-' '};for(int i=0;i<5;i++){if(a[i]>=a[i+1]){cout<<"1111111";return;}}for(int i=0;i<6;i++){if(a[i]<=0||a[i]>111){cout<<"1111111";return;}}for(int i=1;i<=111;i++){for(int j=i+1;j<=111;j++){for(int k=j+1;k<=111;k++){for(int l=k+1;l<=111;l++){for(int m=l+1;m<=111;m++){for(int n=m+1;n<=111;n++){int b[6]={i,j,k,l,m,n};bool yay=false;for(int o=1;o<(1<<6);o++){for(int p=1;p<(1<<6);p++){int asum=0;int bsum=0;for(int q=0;q<6;q++){if(o&(1<<q)){asum+=a[q];}if(p&(1<<q)){bsum+=b[q];}}if(asum==bsum){yay=true;break;}}if(yay){break;}}if(!yay){cout<<"1111111";return;}}}}}}}}
void f4(){if(secret.length()!=6){cout<<"1111111";return;}int a[6]={secret[0]-' ',secret[1]-' ',secret[2]-' ',secret[3]-' ',secret[4]-' ',secret[5]-' '};for(int i=0;i<5;i++){if(a[i]>=a[i+1]){cout<<"1111111";return;}}for(int i=0;i<6;i++){if(a[i]<=0||a[i]>111){cout<<"1111111";return;}}for(int i=1;i<=111;i++){for(int j=i+1;j<=111;j++){for(int k=j+1;k<=111;k++){for(int l=k+1;l<=111;l++){for(int m=l+1;m<=111;m++){for(int n=m+1;n<=111;n++){int b[6]={i,j,k,l,m,n};bool yay=false;for(int o=1;o<(1<<6);o++){for(int p=1;p<(1<<6);p++){int asum=0;int bsum=0;for(int q=0;q<6;q++){if(o&(1<<q)){asum+=a[q];}if(p&(1<<q)){bsum+=b[q];}}if(asum==bsum){yay=true;break;}}if(yay){break;}}if(!yay){cout<<"1111111";return;}}}}}}}}
void f5(){if(secret.length()!=6){cout<<"1111111";return;}int a[6]={secret[0]-' ',secret[1]-' ',secret[2]-' ',secret[3]-' ',secret[4]-' ',secret[5]-' '};for(int i=0;i<5;i++){if(a[i]>=a[i+1]){cout<<"1111111";return;}}for(int i=0;i<6;i++){if(a[i]<=0||a[i]>111){cout<<"1111111";return;}}for(int i=1;i<=111;i++){for(int j=i+1;j<=111;j++){for(int k=j+1;k<=111;k++){for(int l=k+1;l<=111;l++){for(int m=l+1;m<=111;m++){for(int n=m+1;n<=111;n++){int b[6]={i,j,k,l,m,n};bool yay=false;for(int o=1;o<(1<<6);o++){for(int p=1;p<(1<<6);p++){int asum=0;int bsum=0;for(int q=0;q<6;q++){if(o&(1<<q)){asum+=a[q];}if(p&(1<<q)){bsum+=b[q];}}if(asum==bsum){yay=true;break;}}if(yay){break;}}if(!yay){cout<<"1111111";return;}}}}}}}}
void f6(){if(secret.length()!=6){cout<<"1111111";return;}int a[6]={secret[0]-' ',secret[1]-' ',secret[2]-' ',secret[3]-' ',secret[4]-' ',secret[5]-' '};for(int i=0;i<5;i++){if(a[i]>=a[i+1]){cout<<"1111111";return;}}for(int i=0;i<6;i++){if(a[i]<=0||a[i]>111){cout<<"1111111";return;}}for(int i=1;i<=111;i++){for(int j=i+1;j<=111;j++){for(int k=j+1;k<=111;k++){for(int l=k+1;l<=111;l++){for(int m=l+1;m<=111;m++){for(int n=m+1;n<=111;n++){int b[6]={i,j,k,l,m,n};bool yay=false;for(int o=1;o<(1<<6);o++){for(int p=1;p<(1<<6);p++){int asum=0;int bsum=0;for(int q=0;q<6;q++){if(o&(1<<q)){asum+=a[q];}if(p&(1<<q)){bsum+=b[q];}}if(asum==bsum){yay=true;break;}}if(yay){break;}}if(!yay){cout<<"1111111";return;}}}}}}}}
void f7(){if(secret.length()!=6){cout<<"1111111";return;}int a[6]={secret[0]-' ',secret[1]-' ',secret[2]-' ',secret[3]-' ',secret[4]-' ',secret[5]-' '};for(int i=0;i<5;i++){if(a[i]>=a[i+1]){cout<<"1111111";return;}}for(int i=0;i<6;i++){if(a[i]<=0||a[i]>111){cout<<"1111111";return;}}for(int i=1;i<=111;i++){for(int j=i+1;j<=111;j++){for(int k=j+1;k<=111;k++){for(int l=k+1;l<=111;l++){for(int m=l+1;m<=111;m++){for(int n=m+1;n<=111;n++){int b[6]={i,j,k,l,m,n};bool yay=false;for(int o=1;o<(1<<6);o++){for(int p=1;p<(1<<6);p++){int asum=0;int bsum=0;for(int q=0;q<6;q++){if(o&(1<<q)){asum+=a[q];}if(p&(1<<q)){bsum+=b[q];}}if(asum==bsum){yay=true;break;}}if(yay){break;}}if(!yay){cout<<"1111111";return;}}}}}}}}
int main() {
    f1();
    f2();
    f3();
    f4();
    f5();
    f6();
    f7();
    cout<<6;
    f1();
    f2();
    f3();
    f4();
    f5();
    f6();
    f7();
}

```

Try it online!

Same as my previous submission, hopefully it is a bit more radiation hardened.

\\$n = 6\\$.
> 2 votes

# Answer
# C++ (gcc), 4960 bytes, Cracked

```
#include <iostream>
using namespace std;
string secret = "secret";
void f1(){if(secret.length()!=6){cout<<"1";return;}int a[6]={secret[0]-' ',secret[1]-' ',secret[2]-' ',secret[3]-' ',secret[4]-' ',secret[5]-' '};for(int i=0;i<5;i++){if(a[i]>=a[i+1]){cout<<"1";return;}}for(int i=0;i<6;i++){if(a[i]<=0||a[i]>111){cout<<"1";return;}}for(int i=1;i<=111;i++){for(int j=i+1;j<=111;j++){for(int k=j+1;k<=111;k++){for(int l=k+1;l<=111;l++){for(int m=l+1;m<=111;m++){for(int n=m+1;n<=111;n++){int b[6]={i,j,k,l,m,n};bool yay=false;for(int o=1;o<(1<<6);o++){for(int p=1;p<(1<<6);p++){int asum=0;int bsum=0;for(int q=0;q<6;q++){if(o&(1<<q)){asum+=a[q];}if(p&(1<<q)){bsum+=b[q];}}if(asum==bsum){yay=true;break;}}if(yay){break;}}if(!yay){cout<<"1";return;}}}}}}}}
void f2(){if(secret.length()!=6){cout<<"1";return;}int a[6]={secret[0]-' ',secret[1]-' ',secret[2]-' ',secret[3]-' ',secret[4]-' ',secret[5]-' '};for(int i=0;i<5;i++){if(a[i]>=a[i+1]){cout<<"1";return;}}for(int i=0;i<6;i++){if(a[i]<=0||a[i]>111){cout<<"1";return;}}for(int i=1;i<=111;i++){for(int j=i+1;j<=111;j++){for(int k=j+1;k<=111;k++){for(int l=k+1;l<=111;l++){for(int m=l+1;m<=111;m++){for(int n=m+1;n<=111;n++){int b[6]={i,j,k,l,m,n};bool yay=false;for(int o=1;o<(1<<6);o++){for(int p=1;p<(1<<6);p++){int asum=0;int bsum=0;for(int q=0;q<6;q++){if(o&(1<<q)){asum+=a[q];}if(p&(1<<q)){bsum+=b[q];}}if(asum==bsum){yay=true;break;}}if(yay){break;}}if(!yay){cout<<"1";return;}}}}}}}}
void f3(){if(secret.length()!=6){cout<<"1";return;}int a[6]={secret[0]-' ',secret[1]-' ',secret[2]-' ',secret[3]-' ',secret[4]-' ',secret[5]-' '};for(int i=0;i<5;i++){if(a[i]>=a[i+1]){cout<<"1";return;}}for(int i=0;i<6;i++){if(a[i]<=0||a[i]>111){cout<<"1";return;}}for(int i=1;i<=111;i++){for(int j=i+1;j<=111;j++){for(int k=j+1;k<=111;k++){for(int l=k+1;l<=111;l++){for(int m=l+1;m<=111;m++){for(int n=m+1;n<=111;n++){int b[6]={i,j,k,l,m,n};bool yay=false;for(int o=1;o<(1<<6);o++){for(int p=1;p<(1<<6);p++){int asum=0;int bsum=0;for(int q=0;q<6;q++){if(o&(1<<q)){asum+=a[q];}if(p&(1<<q)){bsum+=b[q];}}if(asum==bsum){yay=true;break;}}if(yay){break;}}if(!yay){cout<<"1";return;}}}}}}}}
void f4(){if(secret.length()!=6){cout<<"1";return;}int a[6]={secret[0]-' ',secret[1]-' ',secret[2]-' ',secret[3]-' ',secret[4]-' ',secret[5]-' '};for(int i=0;i<5;i++){if(a[i]>=a[i+1]){cout<<"1";return;}}for(int i=0;i<6;i++){if(a[i]<=0||a[i]>111){cout<<"1";return;}}for(int i=1;i<=111;i++){for(int j=i+1;j<=111;j++){for(int k=j+1;k<=111;k++){for(int l=k+1;l<=111;l++){for(int m=l+1;m<=111;m++){for(int n=m+1;n<=111;n++){int b[6]={i,j,k,l,m,n};bool yay=false;for(int o=1;o<(1<<6);o++){for(int p=1;p<(1<<6);p++){int asum=0;int bsum=0;for(int q=0;q<6;q++){if(o&(1<<q)){asum+=a[q];}if(p&(1<<q)){bsum+=b[q];}}if(asum==bsum){yay=true;break;}}if(yay){break;}}if(!yay){cout<<"1";return;}}}}}}}}
void f5(){if(secret.length()!=6){cout<<"1";return;}int a[6]={secret[0]-' ',secret[1]-' ',secret[2]-' ',secret[3]-' ',secret[4]-' ',secret[5]-' '};for(int i=0;i<5;i++){if(a[i]>=a[i+1]){cout<<"1";return;}}for(int i=0;i<6;i++){if(a[i]<=0||a[i]>111){cout<<"1";return;}}for(int i=1;i<=111;i++){for(int j=i+1;j<=111;j++){for(int k=j+1;k<=111;k++){for(int l=k+1;l<=111;l++){for(int m=l+1;m<=111;m++){for(int n=m+1;n<=111;n++){int b[6]={i,j,k,l,m,n};bool yay=false;for(int o=1;o<(1<<6);o++){for(int p=1;p<(1<<6);p++){int asum=0;int bsum=0;for(int q=0;q<6;q++){if(o&(1<<q)){asum+=a[q];}if(p&(1<<q)){bsum+=b[q];}}if(asum==bsum){yay=true;break;}}if(yay){break;}}if(!yay){cout<<"1";return;}}}}}}}}
void f6(){if(secret.length()!=6){cout<<"1";return;}int a[6]={secret[0]-' ',secret[1]-' ',secret[2]-' ',secret[3]-' ',secret[4]-' ',secret[5]-' '};for(int i=0;i<5;i++){if(a[i]>=a[i+1]){cout<<"1";return;}}for(int i=0;i<6;i++){if(a[i]<=0||a[i]>111){cout<<"1";return;}}for(int i=1;i<=111;i++){for(int j=i+1;j<=111;j++){for(int k=j+1;k<=111;k++){for(int l=k+1;l<=111;l++){for(int m=l+1;m<=111;m++){for(int n=m+1;n<=111;n++){int b[6]={i,j,k,l,m,n};bool yay=false;for(int o=1;o<(1<<6);o++){for(int p=1;p<(1<<6);p++){int asum=0;int bsum=0;for(int q=0;q<6;q++){if(o&(1<<q)){asum+=a[q];}if(p&(1<<q)){bsum+=b[q];}}if(asum==bsum){yay=true;break;}}if(yay){break;}}if(!yay){cout<<"1";return;}}}}}}}}
void f7(){if(secret.length()!=6){cout<<"1";return;}int a[6]={secret[0]-' ',secret[1]-' ',secret[2]-' ',secret[3]-' ',secret[4]-' ',secret[5]-' '};for(int i=0;i<5;i++){if(a[i]>=a[i+1]){cout<<"1";return;}}for(int i=0;i<6;i++){if(a[i]<=0||a[i]>111){cout<<"1";return;}}for(int i=1;i<=111;i++){for(int j=i+1;j<=111;j++){for(int k=j+1;k<=111;k++){for(int l=k+1;l<=111;l++){for(int m=l+1;m<=111;m++){for(int n=m+1;n<=111;n++){int b[6]={i,j,k,l,m,n};bool yay=false;for(int o=1;o<(1<<6);o++){for(int p=1;p<(1<<6);p++){int asum=0;int bsum=0;for(int q=0;q<6;q++){if(o&(1<<q)){asum+=a[q];}if(p&(1<<q)){bsum+=b[q];}}if(asum==bsum){yay=true;break;}}if(yay){break;}}if(!yay){cout<<"1";return;}}}}}}}}
int main() {f1();f2();f3();f4();f5();f6();f7();cout<<6;f1();f2();f3();f4();f5();f6();f7();}

```

Try it online!

Intended solution only modifies the characters in secret, and also takes very long to run.

The hidden n is \\$6\\$. If unchanged, the program outputs \\$111111161111111\\$.
> 1 votes

# Answer
# Python, 669 bytes, \\$n = 1\\$, Cracked

```
import lzma
exec(lzma.decompress(b'\xe0\x00E\x00A]\x004\x9bJg\xb8R<s\xda\xb0\xe5\xbe\xe9\xde\t\x02\x8d\x9d\x02LW\x8bw\x87\xf3mkn1\xc5\xd9\xd6\xe9\xc9E\xf25\xd3\xd7\x01\x91\xc2FM4\xe5sW\xd6\xaaR\x07j\xe7\xa3\x80\x05b\xfcZ9\x0en5\xc2\x00\x01\x00\x00r\x00\xe0\x00\x86\x00y]\x002\x9d\x88\xce\xe12k^\xffi\x8eN\xf1\x83j-\xf5\\\x86\xd9\x01\xb6\xban\xb5_B\xcb@\xeeZ\x05u\x9c,a\xf3\xd1\xf5y\x96\xd0\xf6\x11\x82y\x13\x9cUb:j\x13\xa72\xccl_J\x90*\xf0\x1b[t\x84\xcb\xad\xff>qg\xf7\xe7\x93L\x04\x8fT\x91\xfe\xc9\xd1\x84]\x9f\xcd\xa6\x9e3W[\xbb\xcb/A\xbbZr\x9fq\xf5Wj\xe4\xe0\\\xadt)\xea\xee\xa7]\x80A1\x04\x8e\x9aM\x00', format=lzma.FORMAT_RAW, filters=[{'id': lzma.FILTER_LZMA2}]))

```

Attempt This Online!
> 1 votes

# Answer
# brainfuck, 49 bytes, n=49, Cracked

```
++++++++++++++++++++++++++++++++++++++++++++++++.

```

Try it online!

Saturate question
> 1 votes

# Answer
# Python 3.8 (pre-release), 723 bytes, Cracked

```
P=3
p=[i*(P+1)+1*(i//2)for i in range(P)]
v=[(p[2]*(p[1]+1)+1)+(p[1]-1)*i for i in p]
I=[x*2-1+(v[2]-v[1]+1)*(i//2)for i,x in enumerate(v[::-1])]
t=[vars(__builtins__)[dir(__builtins__)[i]]for i in I]
m='_'.join(vars(t[0])[dir(t[0])[i]].__name__ for i in v)
M=vars(__builtins__)[dir(__builtins__)[v[2]+1]](''.join(x.__name__[:len(t)-i]for i,x in enumerate(t)))
l=t[2](M,m[2:v[1]-v[0]+1]+m[v[2]-v[1]+t[1](t[0](v[2])[-1]):])[-1::-1]
PP=[len(dir(t[2]))-p[2]-1,len(m),sum(len(dir(x))for x in t)//sum(p)+len(p)-1,I[1]%(len(dir(t[1]))+len(dir(t[2]))),sum(p)-1,sum(I)//sum(v)+len(p)-1,sum(p)-1,p[2],I[1]%(len(dir(t[1]))+len(dir(t[2]))),v[2]-v[0]-len(v)-1]
print(len(vars(t[0])[dir(t[0])[sum(PP[:P])]](t[0](),[l[i-1]for i in PP])))

```

Try it online!

The hidden \\$n\\$ is \\$9\\$. If unchanged, the program outputs \\$10\\$.
> 0 votes

# Answer
# Python, 651 bytes, \\$n=2\\$, Cracked

```
print(77925340277363824169293758807642437284508406489944233814731817114744334387054677199464359370358303681225801571736917189241020964424020531423054738521455432784731931386377196234255749859141710848221995*7660297729448052594468076976871308901099050010752258215140275334247136696601489292003583235840730794856813394396865245853772202539436917905108732823263342134564638227230398268672502337581353160403575356676232895580244410109024495577929416391%997624712161309143295415334518642567808466476564516128021383833912794511198191262082650250977292178811713461440089160581066992373718706289075971369001597094521060013695658387955211810675571614035311614)

```

Attempt This Online!
> 0 votes

# Answer
# brainfuck, 57 bytes, n=3, Cracked

```
++++++++++++++++++++++++++++++++++++++++++++++++++++++++.

```

Try it online!

Seems this question hard to make sth interesting
> 0 votes

# Answer
# Python, 873 bytes, \\$n = 4\\$, Cracked

```
import lzma;exec(lzma.decompress(b'\xe0\x00\x86\x00\x7f]\x00\x05\t\x8c\x1f48\x17VAca7\xfc\xaf\xf6\xcd(?\xfa\x11\xf2f\x12\xa8\xe8\xd5\xeb!\x99\xe1\xe7\x81i\x94\x9ej\xf1\x95\x1f\xdd\x83\x11\x01\x84\xb8\xa9=\xe2\xa6\xe6\x88\x8b\xb0\x8a\xacWkV\xc4!\xb4\xaf\\c\xfa\xbc\xf9\xb1\xee\x04\'\xe7d0pJ3B\x02\xcbH\xa2u\r6\xe2>4\xb8\x8f\xe1\x99\x1bW\x8c\x0cT/\xd7wt.{_\x89\t\xb1Ws\xdc\x7f.\xcc\xd6\xb8\x0f\x874\x8eH\xb4\xccq\xb7UV\x00\x00\x01\x00\x004\x00\x01\x00\x18a85aa25882b90aaa356ebd56b\x00\x01\x00\x00c\x00\x01\x00\x006\x00\x01\x00\x005\x00\x01\x00\ndf940ede04a\x00\x01\x00\x003\x00\xe0\x00T\x00A]\x002\r\x88&\x926K\xd9\xf0vNM\xc8\xee\x93\xdfB\xf5\xf5t\x85\x88:\xf9\xa5\xe0\xeb`\xc4\xbdK\xf6s%\xe4\xdf\xae\x1a\xe1-\t\x91\xda\xab\xd0\x10\xea\xa1\x9d\xcd\xec\xe9\x95hD\xb8\xfb\x90\x8e\xe8\x9d\x99"\x14\x00\x00', format=lzma.FORMAT_RAW, filters=[{"id": lzma.FILTER_LZMA2}]).decode())

```

Attempt This Online!

This response is much like my previous one but with an increased \\$n\\$ to prevent direct brute-force attacks. Understanding the crack to the earlier version should aid in cracking this one.
> 0 votes

# Answer
# ///, 8271 bytes, \\$n = 2\\$, Cracked

```
/~-/-~~//-~/~%--//-*///*\*/76543//~~~~~~~~~~~~%%%/***//~///*///%/4//-//~~~--********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************%%%

```

Try it online!

If unchanged, outputs:

```
[encoded data, 20502 characters]

```
> 0 votes

---
Tags: number, cops-and-robbers
---


title: Tips for golfing in R

text:
# Question
Title: Tips for golfing in R
I'm looking for tips for golfing in the R statistical language. R is perhaps an unconventional choice for Golf. However, it does certain things very compactly (sequences, randomness, vectors, and lists), many of the built-in functions have very short names, and it has an optional line terminator (;). What tips and tricks can you give to help solve code golf problems in R?

# Answer
Some tips:

1. In R, it's recommended to use `<-` over `=`. For golfing, the opposite holds since `=` is shorter...
2. If you call a function more than once, it is often beneficial to define a short alias for it:

```
as.numeric(x)+as.numeric(y)

a=as.numeric;a(x)+a(y)

```
3. Partial matching can be your friend, especially when functions return lists which you only need one item of. Compare `rle(x)$lengths` to `rle(x)$l`
4. Many challenges require you to read input. `scan` is often a good fit for this (the user ends the input by entring an empty line).

```
scan()    # reads numbers into a vector
scan(,'') # reads strings into a vector

```
5. Coercion can be useful. `t=1` is much shorter than `t=TRUE`. Alternatively, `switch` can save you precious characters as well, but you'll want to use 1,2 rather than 0,1.

```
if(length(x)) {} # TRUE if length != 0
sum(x<3)         # Adds all the TRUE:s (count TRUE)

```
6. If a function computes something complicated and you need various other types of calculations based on the same core value, it is often beneficial to either: a) break it up into smaller functions, b) return all the results you need as a list, or c) have it return different types of values depending on an argument to the function.
7. As in any language, know it well - R has thousands of functions, there is probably some that can solve the problem in very few characters - the trick is to know which ones!

Some obscure but useful functions:

```
sequence
diff
rle
embed
gl # Like rep(seq(),each=...) but returns a factor

```

Some built-in data sets and symbols:

```
letters     # 'a','b','c'...
LETTERS     # 'A','B','C'...
month.abb   # 'Jan','Feb'...
month.name  # 'January','Feburary'...
T           # TRUE
F           # FALSE
pi          # 3.14...

```
> 53 votes

# Answer
1. Instead of importing a package with `library`, grab the variable from the package using `::` . Compare the followings:

```
library(splancs);inout(...)
splancs::inout(...)

```

Of course, it is only valid if one single function is used from the package.
2. This is trivial but a rule of thumb for when to use @Tommy's trick of aliasing a function: if your function name has a length of `m` and is used `n` times, then alias only if `m*n > m+n+3` (because when defining the alias you spend `m+3` and then you still spend 1 everytime the alias is used). An example:

```
nrow(a)+nrow(b)     # 4*2 < 4+3+2
n=nrow;n(a)+n(b)
length(a)+length(b) # 6*2 > 6+3+2
l=length;l(a)+l(b)

```
3. Coercion as side-effect of functions:

* instead of using `as.integer`, character strings can be coerced to integer using `:` :

    ```
    as.integer("19")
    ("19":1)[1] #Shorter version using force coercion.

    ```
    * integer, numeric, etc. can be similarly coerced to character using `paste` instead of `as.character`:

    ```
    as.character(19)
    paste(19) #Shorter version using force coercion.

    ```
> 27 votes

# Answer
Some very specific golfing tips:

* if you need to extract the length of a vector, `sum(x|1)` is shorter than `length(x)` as long as `x` is numeric, integer, complex or logical.
* if you need to extract the last element of a vector, it may be cheaper (if possible) to initialise the vector *backwards* using `rev()` and then calling `x[1]` rather than `x[length(x)]` (or using the above tip, `x[sum(x|1)]`) (or `tail(x,1)` --- thanks Giuseppe!). A slight variation on this (where the second-last element was desired) can be seen here. Even if you can't initialise the vector backwards, `rev(x)[1]` is still shorter than `x[sum(x|1)]` (and it works for character vectors too). Sometimes you don't even need `rev`, for example using `n:1` instead of `1:n`.
* (As seen here). If you want to coerce a data frame to a matrix, don't use `as.matrix(x)`. Take the transpose of the transpose, `t(t(x))`.
* `if` is a formal function. For example, `"if"(x<y,2,3)` is shorter than `if(x<y)2 else 3` (though of course, `3-(x<y)` is shorter than either). This only saves characters if you don't need an extra pair of braces to formulate it this way, which you often do.
* For testing non-equality of numeric objects, `if(x-y)` is shorter than `if(x!=y)`. Any nonzero numeric is regarded as `TRUE`. If you are testing equality, say, `if(x==y)a else b` then try `if(x-y)b else a` instead. Also see the previous point.
* The function `el` is useful when you need to extract an item from a list. The most common example is probably `strsplit`: `el(strsplit(x,""))` is one fewer byte than `strsplit(x,"")[[1]]`.
* (As used here) Vector extension can save you characters: if vector `v` has length `n` you can assign into `v[n+1]` without error. For example, if you wanted to print the first ten factorials you could do: `v=1;for(i in 2:10)v[i]=v[i-1]*i` rather than `v=1:10:for(...)` (though as always, there is another, better, way: `cumprod(1:10)`)
* Sometimes, for text based challenges (particularly 2-D ones), it's easier to `plot` the text rather than `cat` it. the argument `pch=` to `plot` controls which characters are plotted. This can be shortened to `pc=` (which will also give a warning) to save a byte. Example here.
* To take the floor of a number, don't use `floor(x)`. Use `x%/%1` instead.
* To test if the elements of a numeric or integer vector are all equal, you can often use `sd` rather than something verbose such as `all.equal`. If all the elements are the same, their standard deviation is zero (`FALSE`) else the standard deviation is positive (`TRUE`). Example here.
* Some functions which you would expect to require integer input actually don't. For example, `seq(3.5)` will return `1 2 3` (the same is true for the `:` operator). This can avoid calls to `floor` and sometimes means you can use `/` instead of `%/%`.
* The most common function for text output is `cat`. But if you needed to use `print` for some reason, then you might be able to save a character by using `show` instead (which in most circumstances just calls `print` anyway though you forego any extra arguments like `digits`)
* don't forget about complex numbers! The functions to operate on them (`Re`, `Im`, `Mod`, `Arg`) have quite short names which can occasionally be useful, and complex numbers as a concept can sometimes yield simple solutions to some calculations.
* for functions with very long names (\>13–15 characters), you can use `get` to get at the function. For example, in R 3.4.4 with no packages loaded other than the default, `get(ls(9)[501])` is more economical than `getDLLRegisteredRoutines`. This can also get around source code restrictions such as this answer. Note that using this trick makes your code R-version-dependent (and perhaps platform dependent), so make sure you include the version in your header so it can be reproduced if necessary.
> 25 votes

# Answer
1. Abuse the builtins `T` and `F`. By default, they evaluate to `TRUE` and `FALSE`, which can be automatically converted to numerics `1` and `0`, and they can be re-defined at will. This means that you don't need to initialize a counter (e.g. `i=0` ... `i=i+1`), you can just use `T` or `F` as needed (and jump straight to `F=F+1` later).
2. Remember that functions return the last object called and do not need an explicit `return()` call.
3. Defining short aliases for commonly used functions is great, such as `p=paste`. If you use a function a lot, and with *exactly two* arguments, it is possible that an *infixing* alias will save you some bytes. Infixing aliases must be surrounded by `%`. For example:

```
`%p%`=paste

```

And subsequently `x%p%y`, which is 1 byte shorter than `p(x,y)`. The infixing alias definition is 4 bytes longer than the non-infixing `p=paste` though, so you have to be sure it's worth it.
> 19 votes

# Answer
1. You can assign a variable to the current environment while simultaneously supplying it as an argument to a function:

```
sum(x <- 4, y <- 5)
x
y

```
2. If you are subseting a `data.frame` and your condition depends on several of its columns, you can avoid repeating the `data.frame` name by using `with` (or `subset`).

```
d <- data.frame(a=letters[1:3], b=1:3, c=4:6, e=7:9)
with(d, d[a=='b' & b==2 & c==5 & e==8,])

```

instead of

```
d[d$a=='b' & d$b==2 & d$c==5 & d$e==8,]

```

Of course, this only saves characters if the length of your references to the `data.frame` exceeds the length of `with(,)`
3. `if...else` blocks can return the value of the final statement in which ever part of the block executes. For instance, instead of

```
a <- 3
if (a==1) y<-1 else
if (a==2) y<-2 else y<-3

```

you can write

```
y <- if (a==1) 1 else
     if (a==2) 2 else 3

```
> 16 votes

# Answer
# Using `if`, `ifelse`, and ``if``

There are several ways to do if-statements in R. Golf-optimal solutions can vary a lot.

### The basics

1. `if` is for control flow. It is not vectorized, i.e. can only evaluate conditions of length 1. It requires `else` to (optionally) return an else value.
2. `ifelse` is a function. It is vectorized, and can return values of arbitrary length. Its third argument (the else value) is obligatory.\*
3. ``if`` is a function, with the same syntax as `ifelse`. It is not vectorized, nor are any of the return arguments obligatory.

* It's not technically obligatory; `ifelse(TRUE,x)` works just fine, but it throws an error if the third argument is empty and the condition evaluates to `FALSE`. So it's only safe to use if you are sure that the condition is always `TRUE`, and if that's the case, why are you even bothering with an if-statement?

### Examples

These are all equivalent:

```
if(x)y else z # 13 bytes
ifelse(x,y,z) # 13 bytes
`if`(x,y,z)   # 11 bytes

```

Note that the spaces around `else` are not required if you are using strings directly in the code:

```
if(x)"foo"else"bar"   # 19 bytes
ifelse(x,"foo","bar") # 21 bytes
`if`(x,"foo","bar")   # 19 bytes

```

So far, ``if`` looks to be the winner, as long as we don't have vectorized input. But what about cases where we don't care about the else condition? Say we only want to execute some code if the condition is `TRUE`. For one line of code alone, `if` is usually best:

```
if(x)z=f(y)         # 11 bytes
ifelse(x,z<-f(y),0) # 19 bytes
`if`(x,z<-f(y))     # 15 bytes

```

For multiple lines of code, `if` is still the winner:

```
if(x){z=f(y);a=g(y)}        # 20 bytes
ifelse(x,{z=f(y);a=g(y)},0) # 27 bytes
`if`(x,{z=f(y);a=g(y)})     # 23 bytes

```

There's also the possibility where we *do* care about the else condition, and where we want to execute arbitrary code rather than return a value. In these cases, `if` and ``if`` are equivalent in byte count.

```
if(x)a=b else z=b   # 17 bytes
ifelse(x,a<-b,z<-b) # 19 bytes
`if`(x,a<-b,z<-b)   # 17 bytes

if(x){z=y;a=b}else z=b   # 22 bytes
ifelse(x,{z=y;a=b},z<-b) # 24 bytes
`if`(x,{z=y;a=b},z<-b)   # 22 bytes

if(x)a=b else{z=b;a=y}   # 22 bytes
ifelse(x,a<-b,{z=b;a=y}) # 24 bytes
`if`(x,a<-b,{z=b;a=y})   # 22 bytes

if(x){z=y;a=b}else{z=b;a=y}   # 27 bytes
ifelse(x,{z=y;a=b},{z=b;a=y}) # 29 bytes
`if`(x,{z=y;a=b},{z=b;a=y})   # 27 bytes

```

### Summary

1. Use `ifelse` when you have input of length \> 1.
2. If you're returning a simple value rather than executing many lines of code, using the ``if`` function is probably shorter than a full `if`...`else` statement.
3. If you just want a single value when `TRUE`, use `if`.
4. For executing arbitrary code, ``if`` and `if` are usually the same in terms of byte count; I recommend `if` mainly because it's easier to read.
> 16 votes

# Answer
## Do-while loops in R

Occasionally, I find myself wishing R had a `do-while` loop, because:

```
 some_code
while(condition){
 some_code # repeated
}

```

is far too long and very un-golfy. However, we can recover this behavior and shave off some bytes with the power of the `{` function.

`{` and `(` are each `.Primitive` functions in R.

The documentation for them reads:

> Effectively, `(` is semantically equivalent to the identity `function(x) x`, whereas `{` is slightly more interesting, see examples.

and under Value,

> For `(`, the result of evaluating the argument. This has visibility set, so will auto-print if used at top-level.
>
> For `{`, **the result of the last expression evaluated**. This has the visibility of the last evaluation.

(emphasis added)

So, what does this mean? It means a do-while loop is as simple as

```
while({some_code;condition})0

```

because the expressions inside `{}` are each evaluated, and only the *last one* is returned by `{`, allowing us to evaluate `some_code` before entering the loop, and it runs each time `condition` is `TRUE` (or truthy). The `0` is one of the many 1-byte expressions that forms the "real" body of the `while` loop.

Additionally, this can be combined with `print` (which invisibly returns its argument) to repeatedly print an intermediate result until (and including) it reaches `0`. An example of this can be found here.
> 15 votes

# Answer
1. **Save values in-line**: Others have mentioned that you can pass values in-order and assign them for use elsewhere, i.e.

```
 sum(x<- 1:10, y<- seq(10,1,2))

```

However, you can also *save* values inline for use *in the same line*!

For instance

```
    n=scan();(x=1:n)[abs(x-n/2)<4]

```

reads from `stdin`, creates a variable `x=1:n`, then indexes into `x` using that value of `x`. This can sometimes save bytes.

2. **Alias for the empty vector** You can use `{}` as the empty vector `c()` as they both return `NULL`.
3. **Base Conversion** For integer digits of `n` in base 10, use `n%/%10^(0:nchar(n))%%10`. This will leave a trailing zero, so if that is important to you, use `n%/%10^(1:nchar(n)-1)%%10` ot `n%/%10^(0:log10(n))`. This can be adapted to other bases, using `0:log(n,b)` instead of `log10(n)`.
4. **Using `seq` and `:`**: Rather than using `1:length(l)` (or `1:sum(x|1)`), you can use `seq(l)` as long as `l` is a `list` or `vector` of length greater than 1, as it defaults to `seq_along(l)`. If `l` is numeric and could potentially be length `1`, `seq(!l)` or `seq(a=l)` will do the trick.

Additionally, `:` will (with a warning) use the first element of its arguments.
5. **Removing attributes** Using `c()` on an `array` (or `matrix`) will do the same as `as.vector`; it generally removes non-name attributes.
6. **Factorial** Using `gamma(n+1)` is shorter than using `factorial(n)` and `factorial` is defined as `gamma(n+1)` anyway.
7. **Coin Flipping** When needing to do a random task 50% of the time, using `rt(1,1)<0` is shorter than `runif(1)<0.5` by three bytes.
8. **Extracting/Excluding elements** `head` and `tail` are often useful to extract the first/last few elements of an array; `head(x,-1)` extracts all but the last element and is shorter than using negative indexing, if you don't already know the length:

```
head(x,-1)
x[-length(x)]
x[-sum(x|1)]
```
> 14 votes

# Answer
1. Abuse `outer` to apply an arbitrary function to all the combinations of two lists. Imagine a matrix with i, j indexed by the first args, then you can define an arbitrary function(i,j) for each pair.
2. Use `Map` as a shortcut for `mapply`. My claim is that `mapply` is cheaper than a for loop in situations where you need to access the index. Abuse the list structure in R. `unlist` is expensive. `methods::el` allows you to cheaply unlist the first element. Try to use functions with list support natively.
3. Use `do.call` to generalize function calls with arbitrary inputs.
4. The accumulate args for `Reduce` is extremely helpful for code golf.
5. Writing to console line by line with `cat(blah, "\n")` is cheaper with `write(blah, 1)`. Hard coded strings with "\n" may be cheaper in some situations.
6. If a function comes with default arguments, you can use function(,,n-arg) to specify the n-th argument directly. Example:`seq(1, 10, , 101)` In some functions, partial argument matching is supported. Example: `seq(1, 10, l = 101)`.
7. If you see a challenge involving string manipulation, just press the back button and read the next question. `strsplit` is single handily responsible for ruining R golf.

Now for some newly discovered tips from 2018

8. `A[cbind(i,j)] = z` can be a good way to manipulate matrices. This operation is very byte efficient assuming you design `i, j, z` as vectors with correct lengths. You may save even more by calling the actual index/assign function `"[<-"(cbind(i,j), z)`. This way of calling returns the modified matrix.
9. Use a new line instead of `\n` for line breaks.
10. Squeezing down line counts can save you bytes. In-line assignment `lapply(A<-1:10,function(y) blah)` and function args assignment `function(X, U = X^2, V = X^3)` are ways of doing this.
11. So `"[<-"` is a function in R (and is related to my ancient question on SO)! That is the underlying function responsible for operations such as `x[1:5] = rnorm(5)`. The neat property of calling the function by name allows you to return the modified vector. In order words `"[<-"(x, 1:5, normr(5))` does almost the same thing as the code above except it returns the modified x. The related "length\<-", "names\<-", "anything\<-" all return modified output
> 13 votes

# Answer
# Implicit type conversion

The functions `as.character`, `as.numeric`, and `as.logical` are too byte-heavy. Let's trim them down.

## Conversion to logical from numeric (4 bytes)

Suppose `x` is a numeric vector. Using the logical not operator `!` implicitly recasts the numeric to a logical vector, where `0` is `FALSE` and nonzero values are `TRUE`. `!` then inverts that.

```
x=!x

```

`x=0:3;x=!x` returns `TRUE FALSE FALSE FALSE`.

## Conversion to character from numeric or logical (7 bytes)

This is a fun one. (From this tweet.)

```
x[0]=''

```

R sees that you're updating the vector `x` with `''`, which is of class `character`. So it casts `x` into class `character` so it's compatible with the new data point. Next, it goes to put `''` in the appropriate place... but the index `0` doesn't exist (this trick also works with `Inf`, `NaN`, `NA`, `NULL`, and so on). As a result, `x` is modified in class only.

`x=1:3;x[0]=''` returns `"1" "2" "3"`, and `x=c(TRUE,FALSE);x[0]=''` returns `"TRUE" "FALSE"`.

If you have a character object already defined in your workspace, you can use that instead of `''` to save a byte. E.g., `x[0]=y`!

## Conversion to character from numeric or logical under certain conditions (6 bytes)

J.Doe pointed out in the comments a six-byte solution:

```
c(x,"")

```

This works if `x` is atomic and if you intend to pass it to a function which requires an atomic vector. (The function may throw a warning about ignoring elements of the argument.)

# Conversion to numeric from logical (4 bytes)

You can use the funky indexing trick from above (e.g. `x[0]=3`), but there's actually a quicker way:

```
x=+x

```

The positive operator implicitly recasts the vector as a numeric vector, so `TRUE FALSE` becomes `1 0`.
> 13 votes

# Answer
# Change the meaning of operators

R operators are just functions that get special treatment by the parser. For example `<` is actually a function of two variables. These two lines of code do the same thing:

```
x < 3
`<`(x, 3)

```

You can reassign another function to an operator, and the parser will still do it's thing, including respecting operator precedence, but the final function call will be the new one rather than the original. For example:

```
`<`=rep

```

now means these two lines of code do the same thing:

```
rep("a", 3)
"a"<3

```

and precedence is respected, resulting in things like

```
"a"<3+2
#[1] "a" "a" "a" "a" "a"

```

See for example this answer, and also the operator precedence page. As a side effect, your code will become as cryptic as one written in a golf language.

Some operators like `+` and `-` can accept either one or two parameters, so you can even do things like:

```
`-`=sample
set.seed(1)
-5  # means sample(5)
#[1] 2 5 4 3 1
5-2 # means sample(5, 2)
#[1] 5 4

```

See for example this answer.

See also this answer for using `[` as a two-byte, three-argument operator.
> 11 votes

# Answer
# Scenarios where you can avoid `paste(...,collapse="")` and `strsplit`

These are a pain in the usual string challenges. There are some workarounds.

* `Reduce(paste0,letters)` for -5 bytes from `paste0(letters,collapse="")`
* A 2-byte golf where you have a list containing two vectors `c(1,2,3)` and `c(4,5,6)` and want to concatenate them element-wise to a string `"142536"`. Operator abuse gives you `p=paste0;"^"=Reduce;p^p^r` which saves two bytes on the usual `paste0` call.
* Instead of `paste0("(.{",n,"})")` to construct (eg) a regex for 20 bytes, consider a regex in a regex: `sub(0,"(.{0})",n)` for 17 bytes.

Sometimes (quite often, actually) you'll need to iterate through a vector of characters or strings, or split a word into letters. There are two common use cases: one where you need to take a vector of characters as input to a function or program, and one where you know the vector in advance and need to store it in your code somewhere.

a. Where you need to take a string as **input** and split it into either *words* or *characters*.

1. If you need **words** (including characters as a special case):

* If a newline `0x10` (ASCII 16) separating the words is OK, `x=scan(,"")` is preferred to wrapping your code in `function(s,x=el(strsplit(s," ")))`.
    * If the words can be separated by **any other whitespace**, including multiple spaces, tabs, newlines etc, you can use @ngm's **double scan trick**: `x=scan(,"",t=scan(,""))`. This gives the scanned in string to `scan` as the `text` arg and separates it by whitespace.
    * The second argument in `scan` can be any string so if you have created one, you can recycle it to save a byte.
2. If you need to turn an input string into a **vector of characters**:

* `x=el(strsplit(s,""))` is the shortest *general* solution. The `split` argument works on anything of length zero including `c()`, `{}` etc so if you happen to have created a zero length variable, you could use it to save a byte.
    * If you can work with the ASCII character codes, consider `utf8ToInt`, since `utf8ToInt(x)` is shorter than the `strsplit` call. To paste them back together, `intToutf8(utf8ToInt(x))` is shorter than `Reduce(paste0,el(strsplit(x,"")))`.
    * If you need to split arbitrary strings of numbers like `"31415926535"` as input, you can use `utf8ToInt(s)-48` to save 3 bytes on `el(strsplit(s,""))`, provided you can use the integer digits instead of the characters, as is often the case. This is also shorter than the usual recipe for splitting numbers into decimal digits.

b. Where you need a **fixed vector** of either words or characters in advance.

* If you need a vector of single characters that have some regular pattern or are in alphabetic order, look at using `intToUtf8` or `chartr` applied to a sequence via `a:b` or on the built in letters sets `letters` or `LETTERS`. The pattern language built into `chartr` is especially powerful.
* For **1 to 3 characters or words**, `c("a","b","c")` is the only general shortest solution.
* If you need a fixed vector of **between 4 and 10 non whitespace characters or words**, use `scan` with `stdin` as the `file` arg:

```
f(x=scan(,""))
q
w
e
r
t
y
u

```
* If `scan` from `stdin` isn't possible, for **6 or more non whitespace characters or words**, use `scan` with the `text` argument `scan(,"",t="a b c d e f")`.
* If you need a vector of (a) **6 or more characters of any type** or (b) **10 or more non-whitespace characters** , `strsplit` via `x=el(strsplit("qwertyuiop",""))` is probably the way to go.
* You *may* be able to get away with the following **quote trick**: `quote(Q(W,E,R,T,Y))`, which creates that expression. Some functions like `strrep`, and `grep` will coerce this to a vector of strings! If you do, this is good for any length of word or character vector from 3 to 11.
* There's no good reason to use `strsplit` on words via `x=el(strsplit("q w e r t y"," "))`. It always loses to `scan(,"",t="q w e r t y"))` by a fixed overhead of 5 bytes.

Here's a table of the byte counts used by each approach to read in a vector of single characters of length `n`. The relative ordering within each row is valid for characters or words, except for `strsplit` on `""` which only works on characters.

```
| n  | c(...) | scan | scan | strsplit | quote |
|    |        |+stdin|+text | on ""    | hack  |
|    |        |      |      | CHAR ONLY|       |
|----|--------|------|------|----------|-------|
| 1  | 3      | 11   | 15   | 20       | 8     |
| 2  | 10     | 13   | 17   | 21       | 11    |
| 3  | 14     | 15   | 19   | 22       | 13    |
| 4  | 18     | 17   | 21   | 23       | 15    |
| 5  | 22     | 19   | 23   | 24       | 17    |
| 6  | 26     | 21   | 25   | 25       | 19    |
| 7  | 30     | 23   | 27   | 26       | 21    |
| 8  | 34     | 25   | 29   | 27       | 23    |
| 9  | 38     | 27   | 31   | 28       | 25    |
| 10 | 42     | 29   | 33   | 29       | 27    |
| 11 | 46     | 31   | 35   | 30       | 29    |
| 12 | 50     | 33   | 37   | 31       | 31    |

```

c. If you need to input **text as a character matrix**, a few recipes that seem short are

```
s="hello\nworld\n foo"

# 43 bytes, returns "" padded data frame
# If lines > 5 are longer than lines <= 5, wraps around and causes error
read.csv(t=gsub("(?<=.)(?=.)",",",s,,T),,F)

# 54 bytes with readLines(), "" padded matrix
sapply(p<-readLines(),substring,p<-1:max(nchar(p)),p))

# plyr not available on TIO
# 58 bytes, returns NA padded matrix, all words split by whitespace
plyr::rbind.fill.matrix(Map(t,strsplit(scan(,"",t=s),"")))
# 61 bytes, returns NA padded matrix
plyr::rbind.fill.matrix(Map(t,(a=strsplit)(el(a(s,"\n")),"")))

```
> 9 votes

# Answer
Some basic concepts but should be somewhat useful:

1. In control flow statements you can abuse that any number not equal to zero will be evaluated as `TRUE`, e.g.: `if(x)` is equivalent to `if(x!=0)`. Conversely, `if(!x)` is equivalent to `if(x==0)`.
2. When generating sequences using `:` (e.g. `1:5`) one can abuse the fact that the exponentiation operator `^` is the only operator that has precedence over the `:`-operator (as opposed to `+-*/`).

```
1:2^2 => 1 2 3 4

```

which saves you two bytes on the parentheses that you would normally have to use in case you wanted to e.g. loop over the elements of an `n x n` matrix (`1:n^2`) or any other integer that can be expressed in a shorter manner using exponential notation (`1:10^6`).
3. A related trick can of course be used on the vectorized operations as well `+-*/`, although most commonly applicaple to `+-`:

```
for(i in 1:(n+1)) can instead be written as for(i in 0:n+1)

```

This works because `+1`is vectorized and adds `1` to each element of `0:n` resulting in the vector `1 2 ... n+1`. Similarly `0:(n+1) == -1:n+1` saves you one byte as well.
4. When writing short functions (that can be expressed on one line), one can abuse variable assignment to save two bytes on the enclosing curly brackets `{...}`:

```
f=function(n,l=length(n))for(i in 1:l)cat(i*l,"\n")
f=function(n){l=length(n);for(i in 1:l)cat(i*l,"\n")}

```

Note that this might not always comply to rules of certain challenges.
> 8 votes

# Answer
# Alternatives to `rep()`

Sometimes `rep()` can be avoided with the colon operator `:` and R's vector recycling.

* For repeating `n` zeroes, where `n>0`, `0*1:n` is 3 bytes shorter than `rep(0,n)` and `!1:n`, an array of `FALSE`, is 4 bytes shorter, if the use case allows it.
* To repeat `x` `n` times, `x+!1:n` is 2 bytes shorter than `rep(x,n)`. For `n` ones, use `!!1:n` if you can use an array of `TRUE`.
* To repeat `x` `2n+1` times, where `n>=0`, `x+0*-n:n` is 4 bytes shorter than `rep(x,2*n+1)`.
* The statement `!-n:n` will give a `TRUE` flanked on both sides by `n` `FALSE`. This can be used to generate *even* numbers of characters in calls to `intToUtf8()` if you remember that a zero is ignored.

Modular arithmetic can be useful. `rep` statements with the `each` argument can sometimes be avoided using integer division.

* To generate the vector `c(-1,-1,-1,0,0,0,1,1,1)`, `-3:5%/%3` is 5 bytes shorter than `rep(-1:1,e=3)`.
* To generate the vector `c(0,1,2,0,1,2,0,1,2)`, `0:8%%3` saves 4 bytes on `rep(0:2,3)`.
* Sometimes nonlinear transformations can shorten sequence arithmetic. To map `i in 1:15` to `c(1,1,3,1,1,3,1,1,3,1,1,3,1,1,3)` inside a compound statement, the obvious golfy answer is `1+2*(!i%%3)` for 11 bytes. However, `3/(i%%3+1)` is 10 bytes, and will floor to the same sequence, so it can be used if you need the sequence for array indexing.
> 6 votes

# Answer
When you do need to use a function, use `pryr::f()` instead of `function()`.

Example:

```
function(x,y){x+y}

```

is equivalent to

```
pryr::f(x,y,x+y)

```

or, even better,

```
pryr::f(x+y)

```

Since If there is only one argument, the formals are guessed from the code.
> 5 votes

# Answer
# Surviving challenges involving strings

As mentioned in another answer, `unlist(strsplit(x,split="")` and `paste(...,collapse="")` can be depressing. But don't just walk away from these, there are workarounds!

* `utf8ToInt` converts a string to a vector, `intToUtf8` does the reverse operation. You're getting a vector of `int`, not a vector of `char` but sometimes this is what you're looking for. For instance to generate a list of `-`, better use`intToUtf8(rep(45,34))` than `paste(rep("-",34),collapse="")`
* `gsub` is more useful than other function of the `grep` family when operating on a single string. The two approaches above can be combined as in this answer which benefited from the advice of ovs, Giuseppe and ngm.
* Choose a convenient I/O format as in this answer taking input as lines of text (without quotes) or this one taking a vector of chars. Check with the OP when in doubt.
* As pointed out in the comments, `<` compares strings lexicographically as one would expect.
> 5 votes

# Answer
# R 4.1.0: new shorthand function syntax

I just found out the very new release R 4.1.0 comes with some new syntax. https://www.r-bloggers.com/2021/05/new-features-in-r-4-1-0/

The new shorthand syntax `\(arglist) expr` performs exactly as `function(arglist) expr` and makes writing R functions 7 bytes shorter:

```
\(x,y)x+y

```

instead of

```
function(x,y)x+y

```

There's also the new native pipe `|>`, but this isn't shorter than just using parentheses (and the pipe has to be used with parentheses, unlike magrittr.)
> 5 votes

# Answer
Some ways to find the first non-zero element of an array.

If it has a name `x`:

```
x[!!x][1]

```

Returns `NA` if no non-zero elements (including when `x` is empty, but not `NULL` which errors.)

Anonymously:

```
Find(c, c(0,0,0,1:3))

```

Returns `NULL` if no non-zero elements, or empty or `NULL`.
> 4 votes

# Answer
# Tips for restricted source challenges :

1. Characters in R literals constants can be replaced by hex codes, octal codes and unicodes.

e.g. the string `"abcd"` can be written :

```
    # in octal codes
    "\141\142\143\144"

    # in hex codes
    "\x61\x62\x63\x64"

    # in unicodes
     "\u61\u62\u63\u64"
    # or
    "\U61\U62\U63\U64"

```

We can also mix characters with octal/hex/unicode and use some oct codes and some hex codes together, as long as unicode characters are not mixed with octal/hex e.g. :

```
    # Valid
    "a\142\x63\x64"

    # Valid
    "ab\u63\U64"

    # Error: mixing Unicode and octal/hex escapes in a string is not allowed
    "\141\142\x63\u64"

```

See the end of this section for further details.
2. Since functions can be written using string literals, e.g. `cat()` can be written alternatively :

```
'cat'()
"cat"()
`cat`()

```

we can use octal codes, hex codes and unicode for function names as well :

```
# all equal to cat()
"\143\141\164"()
`\x63\x61\x74`()
'\u63\u61\u74'()
"ca\u74"()

```

with the only exception that unicode sequences are not supported inside backticks \`\`
3. Round brackets can be avoided abusing operators e.g. :

```
cat('hello')

# can be written as
`+`=cat;+'hello'

```

An application of all the three tricks can be found in this answer
> 3 votes

# Answer
# Searching datasets

R's builtin datasets can be a trove, in particular for challenges, but searching through them is not easy.

For instance, for this answer, creating the value `100` thanks to a dataset was useful. It could be that the value was there as is, or as the sum of a column, or as the size of the dataset.

Here is the code I used; credit goes to Giuseppe in the chat:

```
x = data(package = "datasets")
res = x$results
for(dataset_name in paste0(res[,1],"::",res[,3])){
  curr = try(eval(parse(t=dataset_name)), T)
  if(length(curr) == 100) print(c("Length found in", dataset_name))
  if(100 %in% unlist(curr)) print(c("Value found in", dataset_name))
  try(if(try(sum(curr),T) == 100) print("Sum found in", dataset_name), T)
}

```

This searches all the datasets which are included by default; you can search datasets in other packages by changing the first line to `x <- data(package = .packages(all.available = TRUE))`.

You will need to make lavish use of `try` to avoid issues with different types of data. Remember that some datasets are vectors and not matrices or data frames. Other functions to try instead of `sum` include `min`, `max`, `mean`, `prod`, `sd` and `var`.
> 3 votes

# Answer
## `all` and `any` on lists

Apparently, `all` and `any` both accept lists of depth 1 and work just as well as on vectors (with a warning).

So, if you used `all(sapply(list,function))` in your code, in most places you may replace it with `all(Map(function,list))` for -3 bytes.

*I didn't know that before the answer (linked above) by @Dominic van Essen.*
> 2 votes

# Answer
## Know your `apply` functions

1. As already mentioned, use `Map` instead of `mapply` (and possibly `lapply`, depending on whether you want vectorisation also on further arguments to the function).
2. Use `sapply` when you want the result simplified when possible.
3. Use `apply` on matrices to apply a function rowwise or columnwise. But remember of functions like `colSums` and `colMeans`.
4. Use `tapply(x,y,f)` instead of `sapply(split(x,y),f)` or `Map(f,split(x,y))` \- but you may want to use `simplify=FALSE` in the second case sometimes.

Remember that sometimes the function you're using can apply another function to the results (through the `FUN` argument), e.g. `combn`.
> 2 votes

# Answer
# Numeric Tricks

Ignoring precision error:

* `x%/%1` instead of `floor(x)` (integer part for positive x)
* `x%%1` instead of `x-floor(x)` (fractional part for positive x)
* `!x%%1`, `x%%1` to check if integer or not
* `x^.5` instead of `sqrt(x)`
* `gamma(x+1)` instead of `factorial(x)`

Constants: \\$\pi\\$ `pi`, \\$e\\$ `exp(1)`, \\$1/e\\$ `exp(-1)`

(if you need these for some reason) \\$1 / \sqrt{2\pi}\\$ `dnorm(0)`, \\$\gamma\\$ `-digamma(1)`
> 2 votes

---
Tags: code-golf, tips, r
---