# Question
Title: Death By Shock Probe: That's a lot of dice
In the webcomic Darths & Droids, Pete, who plays R2-D2 in the fictional roleplaying campaign around which the comic is based, once claims (warning: potential spoilers in the linked comic) that, with the Lost Orb of Phanastacoria rigged up to his shock probe, he can now dish out a whopping 1048576d4 of damage. (The GM has neither confirmed nor denied this.) Since it should be reasonably obvious that almost no one will actually have the patience to roll that many dice, write a computer program to do it for him, outputting the total value rolled in some reasonable format. Entries will be ranked by program size (shortest program, by byte count, wins), both overall and per-language, with run time breaking ties. Answer may be either a full program or a function definition.

# Scores Per-Language

**Pyth**

Maltysen - 8 bytes\*

Jakube - 10 bytes

**APL**

Alex A - 10 bytes

**CJam**

Optimizer - 11 bytes

**J**

ɐɔıʇǝɥʇuʎs - 12 bytes \**

**Clip10**

Ypnypn - 12 bytes \**

**K**

JohnE - 13 bytes

**Ti-84 BASIC**

SuperJedi224 - 17 bytes\*

**R**

MickyT - 23 bytes

**OCTAVE/MATLAB**

Oebele - 24 bytes

**PARI/GP**

Charles - 25 bytes \**

**Wolfram/Mathematica**

LegionMammal978 - 27 bytes

**Perl**

Nutki - 29 bytes

AsciiThenAnsii - 34 bytes

**Ruby**

Haegin - 32 bytes \**

ConfusedMr\_C - 51 bytes \**

**Commodore Basic**

Mark - 37 bytes \**

**PHP**

Ismael Miguel - 38 bytes

**VBA**

Sean Cheshire - 40 bytes \**

**PowerShell**

Nacht - 41 bytes \**

**Javascript**

Ralph Marshall - 41 bytes

edc65 - 54 bytes (Requires ES6 functionality not available in all browsers.)

**Lua**

cryptych - 51 bytes

**Java**

RobAu - 52 bytes \**

Geobits - 65 bytes

**C**

Functino - 57 bytes

**Python**

CarpetPython - 58 bytes

**Postgre/SQL**

Andrew - 59 bytes \**

**Swift**

Skrundz - 69 bytes

GoatInTheMachine - 81 bytes

**Haskell**

Zeta - 73 bytes \**

**ActionScript**

Brian - 75 bytes \**

**\>\<\>**

ConfusedMr\_C - 76 bytes

**GO**

Kristoffer Sall-Storgaard - 78 bytes

**C#**

Brandon - 91 bytes \**

Andrew - 105 bytes

Ewan - 148 bytes

**Scratch**

SuperJedi224 - 102 bytes

**C++**

Michelfrancis Bustillos - 154 bytes

**Polyglots**

Ismael Miguel (Javascript/ActionScript2) - 67 bytes

---

# Top 10 Overall

```
Maltysen
Alex A
Jakube
Optimizer
ɐɔıʇǝɥʇuʎs/Ypnypn (order uncertain)
JohnE
SuperJedi224
MickyT
Oebele

```

---

Warning- entries marked with a * are VERY SLOW.

Programmed marked \** I have not yet been able to properly test

# Answer
> 10 votes
# Pyth - 9 8 bytes

Uses obvious simple method of summation of randint. Took me minute to realize `1048576` was `2^20`, now I feel really stupid. Thanks to @Jakube for saving me a byte by pointing out `2^20 = 4^10`.

```
smhO4^4T

```

The runtime is horrible, it has yet to finish on my computer, so there is no point running it online so here is the `2^10` one: Try it online here.

```
s        Summation
 m       Map
  h      Incr (accounts for 0-indexed randint)
   O4    Randint 4
  ^4T    Four raised to ten

```

# Answer
> 9 votes
# Perl - ~~48~~ ~~44~~ ~~37~~ ~~39~~ 34 bytes

```
$-+=rand(4)+1for(1..2**20);print$-

```

Prints the sum without a trailing newline.
Saved 4 bytes by substituting for `2**20` (thanks Maltysen) and removing quotes around print.
Saved another 7 bytes by rearranging the code (thanks Thaylon!)
Lost 2 bytes because my old code generated 0-4 (it should be 1-4).
Once again, saved 5 bytes thanks to Caek and nutki.

Ungolfed, properly written code:

```
my $s = 0
$s += int( rand(4) + 1 ) for (1 .. 2**20);
print "$s";

```

# Answer
> 7 votes
# R, ~~32~~ ~~24~~ ~~23~~ 21 bytes

Edit: Got rid of the `as.integer` and used integer division `%/%`. Speed it up slightly.

Thanks to Alex A for the sample tip ... and Giuseppe for removing the `r=`

```
sum(sample(4,2^20,T))

```

Tested with

```
i = s = 0
repeat {
i = i + 1
print(sum(sample(4,2^20,r=T)))
s = s + system.time(sum(sample(4,2^20,r=T)))[3]
if (i == 10) break
}
print (s/10)

```

Outputs

```
[1] 2621936
[1] 2620047
[1] 2621004
[1] 2621783
[1] 2621149
[1] 2619777
[1] 2620428
[1] 2621840
[1] 2621458
[1] 2620680
elapsed
   0.029

```

For pure speed the following completes in microseconds. However I'm not sure I've got my logic correct for it. The results appear consistent with the random method. Shame it's a longer length.

```
sum(rmultinom(1,2^20,rep(1,4))*1:4)

```

Here's a timing run I did on my machine

```
system.time(for(i in 1:1000000)sum(rmultinom(1,2^20,rep(1,4))*1:4))
                   user                  system                 elapsed
7.330000000000040927262 0.000000000000000000000 7.370000000000345607987

```

# Answer
> 7 votes
# APL, ~~11~~ 10 bytes

```
+/?4⍴⍨2*20

```

This just takes the sum of an array of 220 = 1048576 random integers between 1 and 4.

```
+/           ⍝ Reduce by summing a
  ?          ⍝ random integer
   4⍴⍨       ⍝ array with values between 1 and 4
      2*20   ⍝ of length 2^20

```

You can benchmark this on TryAPL by printing the timestamp before and after. It takes about 0.02 seconds.

Saved a byte thanks to marinus and FUZxxl!

# Answer
> 7 votes
# Ti-84 Basic, 17 bytes

Total footprint - Size of program header = 17 bytes

Run Time: Unknown, estimated at 5-6 *hours* based on performance for smaller numbers of rolls (so, basically, not very good)

```
Σ(randInt(1,4),A,1,2^20
```

# Answer
> 6 votes
# Python 2, 58 bytes

We get 1048576 random characters from the operating system, take 2 bits of each, and add them up. Using the `os` library seems to save a few characters over using the `random` library.

```
import os
print sum(1+ord(c)%4 for c in os.urandom(1<<20))

```

This takes about 0.2 seconds on my PC.

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

```
YK#_{4mr+}*

```

This is pretty straight foward:

```
YK                  e# Y is 2, K is 20
  #                 e# 2 to the power 20
   _                e# Copy this 2 to the power 20. The first one acts as a base value
    {    }*         e# Run this code block 2 to the power 20 times
     4mr            e# Get a random int from 0 to 3. 0 to 3 works because we already have
                    e# 2 to the power 20 as base value for summation.
        +           e# Add it to the current sum (initially 2 to the power 20)

```

But the beauty of this is that its really fast too! On my machine (and using the Java compiler) it takes on an average of 70 milliseconds.

The online version takes around 1.7 seconds on my machine.

*Update*: 1 byte saved thanks to DocMax

# Answer
> 6 votes
# JavaScript (ES6), 54 bytes

Average time \< 100 msec. Run snippet to test (in Firefox)

```
// This is the answer
f=t=>(i=>{for(t=i;i--;)t+=Math.random()*4|0})(1<<20)|t

// This is the test
test();

function test(){
  var time = ~new Date;
  var tot = f();
  time -= ~new Date;

  Out.innerHTML = "Tot: " + tot + " in msec: " + time + "\n" + Out.innerHTML;
}
```

```
<button onclick="test()">Repeat test</button><br>
<pre id=Out></pre>
```

**Explanation**

With no statistical package built-in, in Javascript the shortest way to obtain the sum of 1 million random number is to call random() for a million times. So simply

```
f=()=>{
   var t = 0, r, i
   for (i=1<<20; i--; )
   {
      r = Math.random()*4 // random number between 0 and 3.9999999
      r = r + 1 // range 1 ... 4.999999
      r = r | 0 // truncate to int, so range 1 ... 4
      t = t+r
   }
   return t
}

```

Now, adding 1 for a million times is exactly the same than adding 1 million, or even better, start the sum with 1 million and then add the rest:

```
f=()=>{
   var t, r, i
   for (t = i = 1<<20; i--; )
   {
      r = Math.random()*4 // random number between 0 and 3.9999999
      r = r | 0 // truncate to int, so range 0 ... 3
      t = t+r
   }
   return t
}

```

Then golf, drop the temp variable r and drop the declaration of local variables. `t` is a parameter, as one is needed to shorten the declaration of `f`. `i` is global (bad thing)

```
f=t=>{
   for(t=i=1<<20;i--;)
      t+=Math.random()*4|0
   return t
}

```

Then find a way to avoid 'return' using a nameless inner function. As a side effect, we gain another parameter so no globals used

```
f=t=>(
  (i=>{ // start inner function body
     for(t=i;i--;)t=t+Math.random()*4|0 // assign t without returning it
   })(1<<20) // value assigned to parameter i
  | t // the inner function returns 'undefined', binary ored with t gives t again
) // and these open/close bracket can be removed too

```

# Answer
> 5 votes
# (12 bytes, about 9.8 milliseconds)

```
+/>:?4$~2^20

```

I suspect this is mostly memory bandwith-limited: I can't even get it to max out a single core...

You can test this with the following code:

```
   timeit =: 13 : '(1000 * >./ ($/x) 6!:2"0 1 y)'
   4 20 timeit '+/>:?4$~2^20'
9.90059

```

This runs it in 4 groups of 20 trails, and returns the number of milliseconds of the avarage time in the quickest group. An interpreter can be found here.

# Answer
> 5 votes
# Perl, 29

Generates a table of the required length.

```
print~~map{0..rand 4}1..2**20

```

# Answer
> 4 votes
# Pyth, 10 bytes

```
u+GhO4^4TZ

```

This has slightly more bytes than @Maltysen's Pyth solution. But it runs in 8.5 seconds on my laptop, while @Maltysen's solution produced no solution in 20 minutes running time.

But still a little bit too slow for the online compiler.

### Explanation

```
u     ^4TZ   start with G = 0, for H in 0, ... 4^10-1:
                G =
 +GhO4              G + (rand_int(4) + 1)
             result is printed implicitly

```

# Answer
> 4 votes
# Java, 65

Since we have scores listed by language, why not throw Java into the mix? There's not much to golf here, just a simple loop, but I was able to squeeze a couple out of my initial attempt:

```
int f(){int i=1<<20,s=i;while(i-->0)s+=Math.random()*4;return s;}

```

# Answer
> 4 votes
# Matlab, 24

First submission ever!

```
sum(randi([1,4],1,2^20))

```

I had hoped to make use of randi(\[1,4\],1024), which gives a matrix of 1048576 elements, but then I needed a double sum, which takes more characters than this.

Regarding the running speed mentioned in the question, `timeit` tells me the runtime is about 0.031 seconds. So, pretty much instant.

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

This uses a very simple idea: sum them all!

Also, I've noticed that `1048576` is `10000000000000000000` in binary, equivalent to `1<<20`.

Here's the code:

```
while($i++<1<<20)$v+=rand(1,4);echo$v

```

---

Test in your browser (with **VERY LITTLE** changes):

```
$i=$v=0;while($i++<1<<20)$v+=rand(1,4);printf($v);

```

```
//'patch' to make a TRUE polyglot, to work in JS

if('\0'=="\0")//this will be false in PHP, true in JS
{
  //rand function, takes 2 parameters
  function rand($m,$n){
    return ((Math.random()*($n-$m+1))+$m)>>0;

    /*
     *returns an integer number between $m and $n
     *example run, with rand(4,9):
     *(Math.random()*(9-4+1))+4
     *
     *if you run Math.random()*(9-4+1),
     *it will returns numbers between 0 and 5 (9-4+1=6, but Math.random() never returns 1)
     *but the minimum is 4, so, we add it in the end
     *this results in numbers between 0+4 and 4+5
     *
     */

  }

  //for this purpose, this is enough
  function printf($s){
    document.write($s);
  }
}

/*
 *Changes:
 *
 *- instead of echo, use printf
 *    printf outputs a formatted string in php
 *    if I used echo instead, PHP would complain
 *- set an initial value on $i and $v
 *    this avoids errors in Javascript
 *
 */

$i=$v=0;while($i++<1<<20)$v+=rand(1,4);printf($v);
```

All the changes in the code are explained in comments.

# Answer
> 4 votes
## Haskell, 73 bytes

```
import System.Random
f=fmap sum.(sequence.replicate(2^20))$randomRIO(1,4)

```

Usage:

```
$ ghci sourcefile.hs
ghci> f
2622130

```

# Answer
> 4 votes
**C#: 105 bytes**

```
using System.Linq;class C{int D(){var a=new System.Random();return new int[1<<20].Sum(i=>a.Next(1,5));}}

```

# Answer
> 4 votes
# Mathematica, ~~30~~ 27 bytes

```
Tr[RandomInteger[3,2^20]+1]

```

Mathematica has quite long function names...

# Answer
> 3 votes
# Ruby, 32 bytes

```
(1..2**20).inject{|x|x-~rand(4)}

```

In a more readable form:

```
(1..2**20).inject(0) do |x|
  x + rand(4) + 1
end

```

It creates a range from 1 to 1048576 and then iterates over the block that many times. Each time the block is executed the value from the previous iteration is passed in as `x` (initially 0, the default for `inject`). Each iteration it calculates a random number between 0 and 3 (inclusive), adds one so it simulates rolling a d4 and adds that to the total.

On my machine it's pretty fast to run (`0.25 real, 0.22 user, 0.02 sys`).

If you've got Ruby installed you can run it with `ruby -e 'p (1..2**20).inject{|x|x+rand(4)+1}'` (the `p` is necessary to see the output when run in this manner, omit it if you don't care for that or just run it inside IRB where the result is printed to the screen for you). I've tested it on Ruby 2.1.6.

Thanks to histocrat for the bit twiddling hack that replaces `x + rand(4) + 1` with `x-~rand(4)`.

# Answer
> 3 votes
# C, 57 bytes

```
main(a,b){for(b=a=1<<20;a--;b+=rand()%4);printf("%d",b);}

```

This code works... once. If you ever need to roll those dice again, you'll need to put `srand(time(0))` in there, adding 14 bytes.

# Answer
> 3 votes
## PARI/GP, 25 bytes

Really, no need for golfing here -- this is the straightforward way of doing the calculation in GP. It runs in 90 milliseconds on my machine. Hoisting the `+1` saves about 20 milliseconds.

```
sum(i=1,2^20,random(4)+1)

```

Just for fun: if one were optimizing for *performance* in PARI,

```
inline long sum32d4(void) {
  long n = rand64();
  // Note: __builtin_popcountll could replace hamming_word if using gcc
  return hamming_word(n) + hamming_word(n & 0xAAAAAAAAAAAAAAAALL);
}

long sum1048576d4(void) {
  long total = 0;
  int i;
  for(i=0; i<32768; i++) total += sum32d4();
  return total;
}

```

has a very small total operation count -- if xorgens needs ~27 cycles per 64-bit word (can anyone verify this?), then a processor with POPCNT should take only about 0.5 cycle/bit, or a few hundred microseconds for the final number.

This should have close-to-optimal worst-case performance among methods using random numbers of similar or higher quality. It should be possible to greatly increase average speed by combining cases -- maybe a million rolls at a time -- and selecting with (essentially) arithmetic coding.

# Answer
> 3 votes
# PostgreSQL, 59 bytes

```
select sum(ceil(random()*4)) from generate_series(1,1<<20);

```

I'll admit to the slight problem that `random()` could, in theory, produce exactly zero, in which case the die roll would be zero.

# Answer
> 3 votes
# Javascript, ~~55~~ ~~53~~ ~~50~~ ~~47~~ 41 bytes

```
for(a=i=1<<20;i--;)a+=(Math.random()*4)|0

```

I didn't realize that non-random numbers were a known irritant, so I figure that I ought to post a real solution. Meant no disrespect.

Commentary: as noted by others above you can skip the +1 to each roll by starting off with the number of rolls in your answer, and by not having to write a=0,i=1\<\<20 you save two bytes, and another 2 because you don't add +1 to each roll. The parseInt function does the same thing as Math.floor but is 2 characters shorter.

# Answer
> 2 votes
## Clip 10, 12 bytes

```
r+`m[)r4}#WT

         #4T    .- 4^10 = 1048576             -.
   m[   }       .- that many...               -.
     )r4        .-          ...random numbers -.
r+`             .- sum                        -.

```

It takes approximately 0.6 seconds to run on my machine.

# Answer
> 2 votes
# Go, 87 bytes

## Naive solution

```
import"math/rand";func r(){o,n:=0,2<<19;for i:=0;i<n;i++{o+=rand.Intn(4)};println(o+n)}

```

Run online here: http://play.golang.org/p/gwP5Os7\_Sq

Due to the way the Go playground works you have to manually change the seed (time is always the same)

# Answer
> 2 votes
# Go, 78 bytes

## Golfed

```
import."math/rand";func r()(o int){for i:=2<<19;i>=0;i--{o+=Intn(4)+1};return}

```

Still working on it

Run online here http://play.golang.org/p/pCliUpu9Eq

# Answer
> 2 votes
# Swift, 64 bytes

Nothing clever, golfing in Swift is hard...

```
func r()->Int{var x=0;for _ in 0..<(2<<19) {x+=Int(arc4random()%4)+1;};return x;}

```

Version 2 (too late)

```
var x=0;for _ in 0..<(2<<19){x+=Int(arc4random()%4)+1;};print(x)

```

# Answer
> 2 votes
# VBA, 40 Bytes

```
for i=1 to 2^20:q=q+int(rnd*4)+1:next:?q

```

# Answer
> 2 votes
## Commodore Basic, 37 bytes

```
1F┌I=1TO2↑20:C=C+INT(R/(1)*4+1):N─:?C

```

PETSCII substitutions:  = `SHIFT+E`, `/` = `SHIFT+N`,  = `SHIFT+O`

Estimated runtime based on runs with lower dice counts: 4.25 hours.

It's tempting to try to golf off two bytes by making `C` an integer, getting implicit rounding of the random numbers. However, the range on integers in Commodore Basic is -32678 to 32767 -- not enough, when the median answer is 2621440.

# Answer
> 2 votes
## PowerShell, 41 37 bytes

```
1..1mb|%{(get-random)%4+1}|measure -s

```

Took my machine 2 minutes 40 seconds

# Answer
> 2 votes
## Ruby, ~~51~~ 47 chars

```
x=[];(2**20).times{x<<rand(4)+1};p x.inject(:+)

```

I looked at all of the answers before I did this, and the `sum(2**20 times {randInt(4)})` strategy really stuck out, so I used that.

## \>\<\>, 76 chars

```
012a*&>2*&1v
|.!33&^?&:-<
3.v < >-:v >
   vxv1v^<;3
  1234    n+
  >>>> >?!^^

```

I'm not sure if this one works, because my browser crashed when I tried to test it, but here's the online interpreter.

# Answer
> 2 votes
# Java (Java 8) - 52

```
int f(){return new Random().ints(1<<20,1,5).sum();}

```

# Answer
> 1 votes
**C#, 148** (console app)

```
using R=System.Random;using C=System.Console;class P{static void Main(){int o=0;R r=new R();for(int i=0;i<1048576;i++){o+=r.Next(1,4);}C.Write(o);}}

```

# Answer
> 1 votes
# Lua 5.1, 51 bytes :)

`a=0 for _=1,2^20 do a=a+math.random(4) end print(a)`

`math.random(n)` already returns a number between 1 and `n`, so I didn't use @edc65's optimization (clever though it is). Another 26 bytes is required to properly seed the RNG, however....

# Answer
> 1 votes
# K, 13 bytes

```
+/1+(_2^20)?4

```

Take the sum (`+/`) of one plus a vector of 2^20 (`_2^20`) numbers from \[0,4) (`?4`).

The floor `_` is necessary because `^` returns a float, which is slightly inconvenient for this problem.

Tested with Kona. On my machine, this runs in roughly 24 milliseconds.

## edit:

To test timing, you can prefix the program with `\t` and get the runtime in milliseconds.

```
  \t +/1+(_2^20)?4
25

```

# Answer
> 1 votes
# Microscript, 7 bytes

First, a disclaimer: This is not actually a competing entry for this challenge, as this language is significantly too new.

Now, here's the program: `20ec1r4`

# Answer
> 1 votes
# Scratch, 102 bytes

The consensus seems to be to convert it to the plaintext form used by the scratchblocks code on the scratch forums, so here we go.

```
when green flag clicked
set [a v] to [0]
repeat (1048576)
change [a v] by (pick random (1) to (4))
end

```

Result will be stored in the variable `a`.

# Answer
> 1 votes
## Swift, 69 bytes

```
var b={return[UInt32](0..<8<<17).reduce(0){$1*0+$0+arc4random()%4+1}}

```

`$1*0` is required for the compiler to infer the type of the closure.

# Answer
> 1 votes
# Perl 6, ~~26~~ 22 bytes

~~{sum (1..4).pick xx 1+\<20}~~

```
{sum roll 1..4: 1+<20}

```

~~It's not fast...takes about nine seconds on my system.~~

Try it online!

Six years ago, I apparently didn't know about the `roll` method.

# Answer
> 1 votes
# Thunno 2 `S`, 6 bytes

```
T4@ı4ɼ

```

Try it online!

#### Explanation

```
T4@ı4ɼ  # Implicit input
T4@     # Push 4 ** 10
   ı    # Map over the range:
    4ɼ  #  Random number from [1..4]
        # Implicit output of sum

```

# Answer
> 0 votes
## Actionscript 3, ~~81~~ ~~77~~ 75 bytes:

```
function r(){var a=0,i=1<<20;while(i--){a+=int(Math.random()*4+1)}return a}

```

# Answer
> 0 votes
# Javascript + ActionScript2, 67 bytes

According to the ActionScript3 documentation, it is only required to use the keyword `var` when setting a type.

Other than that, it pretty much looks like Javascript.
Since I'm a fan of polyglots, I did this one.

The code:

```
function r(){i=a=0;while(i++<1<<20)a+=1+Math.random()*4&7;return a}

```

The `&7` has a function to convert the number to an integer value. I could use other methods, but the gain in size would be null.

Test it here:

```
function r(){i=a=0;while(i++<1<<20)a+=1+Math.random()*4&7;return a}

document.write(r());
```

This answer is based on Brian's answer in ActionScript3, based in a comment I left with a solution for him.

# Answer
> 0 votes
# C# - 91

I went the function route for this

```
Func<int,int>G=s=>{int e=s=0;var r=new Random();for(;s<1<<20;s++)e+=r.Next(1,5);return e;};

```

# Answer
> 0 votes
## C++, 154 bytes

### Golfed:

```
#include<iostream>
#include <stdlib.h>
#include <time.h>
int main(){int c=0;srand(time(NULL));for(int x=0;x<=1048576;x++){c=c+(rand()%4+1);}std::cout<<c;}

```

### Ungolfed:

```
#include<iostream>
#include <stdlib.h>
#include <time.h>

int main(){
    int c = 0;
    srand (time(NULL));
    for(int x = 0; x <= 1048576; x++){
        c = c + (rand() % 4 + 1);
    }

    std::cout<<c;
}

```

# Answer
> 0 votes
## Python 2, ~~69~~ 67 Bytes

```
import random
print sum([random.randint(1,4)for _ in range(4**10)])

```

~~11~~ 9 bytes more that the existing Python 2 answer :( I'm sure I can find some places to shave off a few bytes though.

# Answer
> 0 votes
# Vyxal `s`, 38 bitsv2, 4.75 bytes

```
k₂ƛ4℅

```

Try it Online!

## Explained

```
k₂ƛ4℅
k₂ƛ    # For each number in the range [1, 2**20]:
   4℅  #   Choose a random number between 1 and 4
# s flag sums

```

Created with the help of Luminespire.

---
Tags: code-golf, random
---


# Question
Title: Do n and n^3 have the same set of digits?
Given a number *n* (0 \<= *n* \<= 2642245), check if *n* and *n*3 have the same set of digits, and output a truthy or falsey value accordingly.

For example, let's check the number 100.

1003 is 1000000.

The set of digits in 100 is {0, 1}.

The set of digits in 1000000 is {0, 1}.

Therefore, 100 should give a truthy value.

### Test cases

```
0 -> True
1 -> True
10 -> True
107624 -> True
251894 -> True
251895 -> False
102343 -> False

```

Remember, this is , so the code with the fewest bytes wins.

OEIS A029795

# Answer
> 29 votes
# Python 3, ~~36~~ 32 bytes

```
lambda x:{*str(x)}=={*str(x**3)}

```

I think this only works in Python 3.5 and later. Four bytes have gone, thanks to Copper.

# Answer
> 19 votes
# 05AB1E, 6 bytes

05AB1E uses CP-1252 encoding.

```
3mê¹êQ

```

Try it online!

**Explanation**

```
3m       # input^3
  ê      # sorted with duplicates removed
     Q   # is equal to
   ¹ê    # input sorted with duplicates removed

```

# Answer
> 14 votes
# C, 73 bytes

```
k;b(i){k=0;while(i)k|=1<<i%10,i/=10;return k;}f(n){return b(n)-b(n*n*n);}

```

Creates the set via bits. Returns `0` for same set, anything else for different sets.

Ungolfed:

```
k;
b(i){
  k=0;
  while(i)
    k|=1<<i%10,
    i/=10;
  return k;
}

f(n){
  return b(n)-b(n*n*n);
}

```

# Answer
> 8 votes
# Perl, 31 + 2 (`-pl` flag) = ~~25~~ ~~21~~ ~~18~~ ~~34~~ 33 bytes

```
$_=($==$_**3)!~/[^$_]/*!/[^$=]/

```

Using:

```
perl -ple '$_=($==$_**3)!~/[^$_]/*!/[^$=]/' <<< 251894

```

Output: `1\n` or `0\n`.

Thanx to @Dada for 3 bytes, Gabriel Benamy for 1 byte, & @Zaid for bug reports.

# Answer
> 7 votes
# Mathematica, 34 bytes

```
f=Union@*IntegerDigits;f@#==f[#^3]&

```

Direct implementation (unnamed function of one integer argument).

# Answer
> 7 votes
# Jelly, 8 bytes

```
,3*\D‘ṬE

```

Try it online! or verify all test cases.

### How it works

```
,3*\D‘ṬE  Main link. Argument: n

,3        Pair; yield [n, 3].
  *\      Cumulative reduce by exponentation. Yields [n, n³].
    D     Decimal; yield the digit arrays of n and n³.
     ‘    Increment, mapping 0 ... 9 to 1 ... 10.
      Ṭ   Untruth (vectorizes); map digit array [a, b, c, ...] to the smallest
          of zeroes with ones at indices a, b, c, ...
       E  Test the results for equality.

```

# Answer
> 6 votes
# JavaScript ES6, ~~55~~ 51 bytes

Thanks to Downgoat for 3 bytes! You can save a byte by converting to ES7 and using `n**3` instead of `n*n*n`.

```
n=>(f=s=>[...new Set(s+[])].sort()+[])(n)==f(n*n*n)

```

Simple enough.

# Answer
> 6 votes
## CJam, 8 bytes

```
l_~3#s^!

```

Test suite.

### Explanation

```
l   e# Read input.
_~  e# Duplicate and evaluate.
3#  e# Raise to third power.
s   e# Convert back to string.
^   e# Symmetric set difference. Gives an empty list iff the two sets
    e# are equal.
!   e# Logical NOT.

```

# Answer
> 6 votes
# C#, ~~241~~ ~~208~~ ~~205~~ ~~201~~ ~~193~~ ~~233~~ ~~222~~ ~~220~~ ~~212~~ ~~203~~ ~~177~~ 159 bytes (109 alternate)

```
I=>{x=s=>{var a=new int[10];foreach(var h in s+"")a[h-'0']++;return a;};var i=x(I);var j=x(I*I*I);for(var k=0;k<10;)if(i[k]>0^j[k++]>0)return 0>1;return 1>0;};

```

The lambda's must specifically use the `ulong` type:

```
System.Func<ulong, bool> b; // = I=>{...};
System.Func<ulong, int[]> x; // inner lambda

```

Thanks to @Corak and @Dennis\_E for saving some bytes, and @TimmyD for finding a problem with my original solution. Thanks to @SaxxonPike for pointing out the ulong/long/decimal/etc problem (which actually also saved me some bytes).

---

There is also a **109 byte** solution using HashSets, similar to the Java answers here, but I'm going to stick to my original solution for my score.

```
using System.Collections.Generic;I=>{return new HashSet<char>(I+"").SetEquals(new HashSet<char>(I*I*I+""));};

```

# Answer
> 6 votes
# Java 8, 154 characters

```
a->java.util.Arrays.equals((a+"").chars().distinct().sorted().toArray(),(new java.math.BigInteger(a+"").pow(3)+"").chars().distinct().sorted().toArray());

```

Called like this:

```
interface Y {
    boolean n(int x);
}

static Y y = a->java.util.Arrays.equals((a+"").chars().distinct().sorted().toArray(),(new java.math.BigInteger(a+"").pow(3)+"").chars().distinct().sorted().toArray());

public static void main(String[] args) {
    System.out.println(y.n(0));
    System.out.println(y.n(1));
    System.out.println(y.n(10));
    System.out.println(y.n(107624));
    System.out.println(y.n(251894));
    System.out.println(y.n(251895));
    System.out.println(y.n(102343));
}

```

Outputs:

```
true
true
true
true
true
false
false

```

A very Java 8-y answer, using a lambda as well as streams including some fancy number-to-string conversions.

Unfortunately we need to use `BigInteger.pow(3)` instead of `Math.pow(a,3)` due to Math.pow using non-precise doubles, which return incorrect values with large numbers (starting with `2103869`).

# Answer
> 6 votes
## Haskell, 47 bytes

```
n%p=[c|c<-['0'..],elem c$show$n^p]
f n=n%1==n%3

```

Very slow. Test with `c<-['0'..'9']`.

Tests every character for inclusion in the string representation of `n`, and makes a list of those included. Does likewise for `n^3` and checks if the lists are equal.

# Answer
> 6 votes
# BASH, ~~69~~, 59 bytes

*UPDATE*

Another nice way to do this in bash is to use *tr* (62 bytes, but can probably be squeezed a bit more)

```
T() { m=`bc<<<$1^3`;[ -z "`tr -d $m <<<$1;tr -d $1 <<<$m`" ];}

```

*EDIT:* Some more optimizations (Thx ! @manatwork)

**Golfed**

```
T() { S(){ fold -1|sort -u;};bc<<<$1^3|S|diff - <(S<<<$1);}

```

**Test**

```
TEST() {
 T $1 >/dev/null; echo $?
}

TEST 0
0
TEST 1
0
TEST 11
1
TEST 10
0
TEST 107624
0
TEST 251894
0
TEST 251895
1
TEST 102343
1
TEST 106239
1

```

0 - for success (exit code) 1 - for failure (exit code)

# Answer
> 6 votes
# x86-64 machine code function, 40 bytes.

# Or 37 bytes if 0 vs. non-zero is allowed as "truthy", like strcmp.

Thanks to Karl Napf's C answer for the bitmap idea, which x86 can do very efficiently with BTS.

Function signature: `_Bool cube_digits_same(uint64_t n);`, using the x86-64 System V ABI. (`n` in RDI, boolean return value (0 or 1) in AL).

`_Bool` is defined by ISO C11, and is typically used by `#include <stdbool.h>` to define `bool` with the same semantics as C++ `bool`.

Potential savings:

* 3 bytes: Returning the inverse condition (non-zero if there's a difference). Or from inline asm: returning a flag condition (which is possible with gcc6)
* 1 byte: If we could clobber EBX (doing so would give this function a non-standard calling convention). (could do that from inline asm)
* 1 byte: the RET instruction (from inline asm)

All of these are possible if this was an inline-asm fragment instead of a function, which would make it **35 bytes for inline-asm**.

```
0000000000000000 <cube_digits_same>:
   0:   89 f8           mov    eax,edi
   2:   48 f7 e7        mul    rdi          # can't avoid a REX prefix: 2642245^2 doesn't fit in 32 bits
   5:   48 f7 e7        mul    rdi          # rax = n^3, rdx=0
   8:   44 8d 52 0a     lea    r10d,[rdx+0xa]  # EBX would save a REX prefix, but it's call-preserved in this ABI.
   c:   8d 4a 02        lea    ecx,[rdx+0x2]

000000000000000f <cube_digits_same.repeat>:
   f:   31 f6           xor    esi,esi

0000000000000011 <cube_digits_same.cube_digits>:
  11:   31 d2           xor    edx,edx
  13:   49 f7 f2        div    r10         ; rax = quotient.  rdx=LSB digit
  16:   0f ab d6        bts    esi,edx     ; esi |= 1<<edx
  19:   48 85 c0        test   rax,rax     ; Can't skip the REX: (2^16 * 10)^3 / 10 has all-zero in the low 32.
  1c:   75 f3           jne    11 <cube_digits_same.cube_digits>

                                         ; 1st iter:                 2nd iter:                both:
  1e:   96              xchg   esi,eax   ; eax=n^3 bitmap            eax=n bitmap             esi=0
  1f:   97              xchg   edi,eax   ; edi=n^3 bitmap, eax=n     edi=n bmp, eax=n^3 bmp
  20:   e2 ed           loop   f <cube_digits_same.repeat>

  22:   39 f8           cmp    eax,edi
  24:   0f 94 d0        sete   al
                  ;; The ABI says it's legal to leave garbage in the high bytes of RAX for narrow return values
                  ;; so leaving the high 2 bits of the bitmap in AH is fine.
  27:   c3              ret
0x28: end of function.

```

LOOP seems like the smallest way to repeat once. I also looked at just repeating the loop (without REX prefixes, and a different bitmap register), but that's slightly larger. I also tried using PUSH RSI, and using `test spl, 0xf` / `jz` to loop once (since the ABI requires that RSP is 16B aligned before CALL, so one push aligns it, and another misaligns it again). There's no `test r32, imm8` encoding, so the smallest way was with a 4B TEST instruction (including a REX prefix) to test just the low byte of RSP against an imm8. Same size as LEA + LOOP, but with extra PUSH/POP instructions required.

Tested for all n in the test range, vs. steadybox's C implementation (since it uses a different algorithm). In the two cases of different results that I looked at, my code was correct and steadybox's was wrong. I think my code is correct for all n.

```
_Bool cube_digits_same(unsigned long long n);

#include <stdio.h>
#include <stdbool.h>
int main()
{
    for(unsigned n=0 ; n<= 2642245 ; n++) {
        bool c = f(n);
        bool asm_result = cube_digits_same(n);
        if (c!=asm_result)
            printf("%u problem: c=%d asm=%d\n", n, (int)c, (int)asm_result);
    }
}

```

The only lines printed have c=1 asm=0: false-positives for the C algorithm.

Also tested against a `uint64_t` version of Karl's C implementation of the same algorithm, and the results match for all inputs.

# Answer
> 5 votes
# Haskell, ~~54~~ 52 bytes

Thanks @Laikoni for saving two bytes.

```
(%)=all.flip elem
k n|[a,b]<-show<$>[n,n^3]=b%a&&a%b

```

# Answer
> 5 votes
# Dyalog APL, 10 bytes

```
⍕≡⍕∪(⍕*∘3)

```

`⍕≡` is the argument's text representation identical to

`⍕∪` the union of the argument's text representation and

`(⍕*∘3)` the text representation of the cubed argument?

TryAPL online!

**Note:** For large numbers, set `⎕PP←34 ⋄ ⎕FR←1287` (34 significant digits, 128 bit floats)

# Answer
> 5 votes
# Clojure, 35 bytes

```
#(=(set(str %))(set(str(* % % %))))

```

# Answer
> 5 votes
# Java 7, ~~185~~ 178 characters

```
import java.util.*;
boolean a(int n){return new HashSet(Arrays.asList((n+"").split(""))).equals(new HashSet(Arrays.asList((new java.math.BigInteger(n+"").pow(3)+"").split(""))));}

```

Call as:

```
public static void main(String [] args) {
    System.out.println(0 + " -> " + a(0));
    System.out.println(1 + " -> " + a(1));
    System.out.println(10 + " -> " + a(10));
    System.out.println(107624 + " -> " + a(107624));
    System.out.println(2103869 + " -> " + a(2103869));
    System.out.println(251894 + " -> " + a(251894));
    System.out.println(251895 + " -> " + a(251895));
    System.out.println(102343 + " -> " + a(102343));
    System.out.println(106239 + " -> " + a(106239));
}

```

Output:

```
0 -> true
1 -> true
10 -> true
107624 -> true
2103869 -> true
251894 -> true
251895 -> false
102343 -> false
106239 -> false

```

*(I'm never sure if I have to count imports and method definitions as well... I've seen either way. The code itself would be only 141 bytes long though.)*

# Answer
> 5 votes
# R, ~~65~~ ~~79~~ 70 bytes

Takes `n` from stdin, splits `n` and `n^3` into single digits, and compares the two sets. Uses the `gmp` package to handle large integers (thanks to Billywob for pointing out that shortcoming). Now uses `substring` to cut up `n` and `n^3`, thanks to @MickyT for the suggestion. (Previous versions used `scan` and `gsub` in a hacky way.)

```
s=substring
setequal(s(n<-gmp::as.bigz(scan()),p<-1:1e2,p),s(n^3,p,p))

```

# Answer
> 4 votes
# Jelly, 8 bytes

```
*3ṢQ⁼ṢQ$

```

Try it online!

Explanation:

```
       $    # As a monadic (single argument) link:
    ⁼       # Return true if the following are equal
     ṢQ     # The unique sorted elements of 'n'
  ṢQ        # and The unique sorted elements
*3          # of 'n^3'

```

# Answer
> 4 votes
# C++, 82 bytes

```
t(int a){int b=a*a*a,c,d;while(a|b)c|=1<<a%10,a/=10,d|=1<<b%10,b/=10;return c==d;}

```

The function t(a) returns the answer. Uses an int as a set. Printed nicely:

```
t(int a)
{
    int b = a*a*a, c, d;
    while(a|b) c|=1 << a%10, a/=10, d|=1 << b%10, b/=10;
    return c==d;
}

```

# Answer
> 4 votes
# C++14, 93 bytes

```
int b(auto i){int k=0;while(i)k|=1<<i%10,i/=10;return k;}int f(auto n){return b(n)-b(n*n*n);}

```

Port of my C answer, works for big numbers (call with `L` suffix).

# Answer
> 4 votes
# Pyth, 10 bytes

Because we don't have enough variety with Pyth answers, let's add not one, but two more! Both are 10 bytes, and have been tested with `106239` as a sample input (which some other answers failed).

```
!s.++Q,`**

```

Explanation:

```
!s.++Q,`**QQQQ   Implicit input filling
        **QQQ    Q ^ 3
       `         repr(Q^3)
      ,      Q   [repr(Q^3),Q]
    +Q           [Q,repr(Q^3),Q]
  .+             Deltas ([Digits in Q but not in Q^3, digits in Q^3 but not in Q])
!s               Are both empty?

```

Try the first answer using an online test suite.

Second answer:

```
qFmS{`d,**

```

Explanation:

```
qFmS{`d,**QQQQ   Implicit input filling
        **QQQ    Q ^ 3
       ,     Q   [Q^3, Q]
  m              map over each element d of [Q^3, Q]:
     `d           the element's string representation
    {             with duplicates removed
   S              and sorted
qF               Fold over equality (are the two the same?)

```

Try the second answer using an online test suite.

# Answer
> 4 votes
# Kotlin: 46/88/96 bytes

The question doesn't specify from where the input comes from, so here's the usual 3 input sources.

---

### Function: 46 bytes

```
fun f(i:Long)="$i".toSet()=="${i*i*i}".toSet()

```

---

### main() using first program argument: 88 bytes

`fun main(a:Array<String>){val i=a[0].toLong();println("$i".toSet()=="${i*i*i}".toSet())}`

---

### main() using standard input: 96 bytes

`fun main(a:Array<String>){val i=readLine()!!.toLong();println("$i".toSet()=="${i*i*i}".toSet())}`

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

```
g=n=>n<1?0:g(n/10)|1<<n%10
n=>g(n)==g(n*n*n)

```

Port of @KarlNapf's excellent C answer. ES7 saves a byte via `n**3`. Only works up to 208063 due to JavaScript's limited numeric precision; if you only need it to work up to 1290, you can save another byte.

# Answer
> 4 votes
# Perl 6, 22 bytes

```
{!(.comb⊖$_³.comb)}

```

## Expanded:

```
{ # bare block lambda with implicit parameter ｢$_｣
  !(
    .comb # get a list of the graphemes ( digits )

    ⊖ # Symmetric Set difference

    $_³.comb # cube and get a list of the graphemes
  )
}

```

The Symmetric Set difference ｢⊖｣ operator returns an empty Set if both sides are equivalent Sets (automatically turns a list into a Set). At that point the only thing left to do is invert it logically.

# Answer
> 3 votes
# Ruby, 48 bytes

```
->n{(f=->x{x.to_s.chars.uniq.sort})[n]==f[n**3]}

```

# Answer
> 3 votes
## PowerShell v2+, ~~94~~ 93 bytes

```
filter f($n){-join("$n"[0..99]|sort|select -u)}
(f($x=$args[0]))-eq(f("[bigint]$x*$x*$x"|iex))

```

*(Newline for clarity, not included in bytecount)*

The first line defines `f` as a `filter` (similar-ish enough to a function for our purposes here to not go into specifics) that takes input `$n` and does the following:

```
filter f($n){-join("$n"[0..99]|sort|select -u)}
       f($n)                                    # Input
                   "$n"                         # Cast as string
                       [0..99]                  # Index as char-array
                              |sort             # Sorted alphabetically
                                   |select -u   # Only select the -Unique elements
             -join(                          )  # Join those back together into a string
                                                 # Implicit return

```

The second line takes the input `$args`, performs `f` on it, and checks whether it's `-eq`ual to `f` performed on `$x` cubed. Note the explicit `[bigint]` cast, required else we'll get the result back in scientific notation, which will obviously not work.

The Boolean result is left on the pipeline, and output is implicit.

```
PS C:\Tools\Scripts\golfing> 0,1,10,107624,251894,251895,102343,106239,2103869|%{"$_ --> "+(.\do-n-n3-same-digits.ps1 $_)}
0 --> True
1 --> True
10 --> True
107624 --> True
251894 --> True
251895 --> False
102343 --> False
106239 --> False
2103869 --> True

```

*Saved a byte thanks to @ConnorLSW*

# Answer
> 3 votes
## Haskell, 47 bytes

```
import Data.Set
s=fromList.show
f n=s n==s(n^3)

```

Usage example: `f 102343` -\> `False`.

Uses sets from the `Data.Set` module. The helper function `s` turns a number into its string representation and than makes a set out of the characters.

# Answer
> 3 votes
# Brachylog, 11 bytes

```
doI,?:3^doI

```

Try it online!

Thanks to @DestructibleWatermelon for pointing out a problem with my original answer.

### Explanation

```
(?)doI,           I is the Input sorted with no duplicates
       ?:3^       Compute Input^3
           doI    Input^3 sorted with no duplicates is I

```

# Answer
> 3 votes
# Groovy, 35 ~~51~~ chars/bytes

I was sad not to see Groovy included, so here's my original 51-byte attempt:

`def x(def n){"$n".toSet()=="${n.power(3)}".toSet()}`

Rewritten as a 35-byte anonymous closure and with `**` for exponentiation, thanks to manatwork:

`{"$it".toSet()=="${it**3}".toSet()}`

Some test cases for the original function:

```
println x(0)
println x(1)
println x(10)
println x(107624)
println x(251894)
println x(251895)
println x(102343)

```

A named closure `c` could be called like this: `println c.call(107624)`. The anonymous 35-byte closure could be called like this: `println ({"$it".toSet()=="${it**3}".toSet()}(107624))`

Outputs:

```
true
true
true
true
true
false
false

```

Please note: I learned that something like code golf exists just now, so hopefully I got this right!

# Answer
> 2 votes
# Lua, 55 bytes

Takes input on the command line. Makes n into a character class and tests the string n ^ 3 against it.

```
a=arg[1]print(not("%u"):format(a^3):find("[^"..a.."]"))

```

# Answer
> 2 votes
# Factor, 37 bytes

```
[ dup 3 ^ [ 10 >base unique ] bi@ = ]

```

(passing) Tests:

```
: func ( x -- ? ) dup 3 ^ [ number>string unique ] bi@ = ;
{ t } [ 0 func ] unit-test
{ t } [ 1 func ] unit-test
{ t } [ 10 func ] unit-test
{ t } [ 107624 func ] unit-test
{ t } [ 251894 func ] unit-test
{ f } [ 251895 func ] unit-test
{ f } [ 102343 func ] unit-test

```

# Answer
> 2 votes
# C#, 86 characters

```
using System.Linq;i=>(i*i*i+"").All((i+"").Contains)&&(i+"").All((i*i*i+"").Contains);

```

Because it is a lambda, in practical use, you will need to assign it to type `Func<decimal, bool>`. This should, according to MSDN, be useful until you go beyond 28 digits on the `i*i*i` calculation. If you use the BigInteger package, you can theoretically go to however many digits you have memory for. Just substitute `BigInteger` for `decimal`. The function itself does not change.

nUnit Test:

```
using System;
using System.Linq;
using NUnit.Framework;

namespace CodeGolf
{
    [TestFixture]
    public class CodeGolfTestFixture
    {
        [TestCase(0, true)]
        [TestCase(1, true)]
        [TestCase(10, true)]
        [TestCase(107624, true)]
        [TestCase(251894, true)]
        [TestCase(251895, false)]
        [TestCase(102343, false)]
        [TestCase(106239, false)]
        [TestCase(2103869, true)]
        public void Test(int inp, bool expectedResult)
        {
            Func<decimal, bool> subject = i =>
                (i*i*i + "").All((i + "").Contains) &&
                (i + "").All((i*i*i + "").Contains);
            var observedResult = subject(inp);
            Assert.AreEqual(expectedResult, observedResult);
        }
    }
}

```

# Answer
> 2 votes
# Factor, 32 bytes

```
[ dup 3 ^ [ present ] bi@ set= ]

```

Try it online!

* `dup` Make a copy of the input.

**Stack (e.g.):** `100 100`
* `3 ^` Cube.

**Stack:** `100 1000000`
* `[ present ] bi@` Convert them both to strings.

**Stack:** `"100" "1000000"`
* `set=` Are they equal when viewed as sets?

**Stack:** `t`

# Answer
> 2 votes
# Vyxal, 3 bytes

```
3e⊍

```

Try it Online!

An empty set is truthy and a set with items is falsey. If that ain't an acceptable format for output:

## 4 bytes

```
3e⊍¬

```

Try it Online!

## Explained

```
3e⊍
3e  # input ^ 3
  ⊍ # symmetric set difference between the above and input
    # ¬ will negate that result, making it either `0` or `1`

```

# Answer
> 1 votes
## Pyke, 10 bytes

```
3^`}SR`}Sq

```

Try it here!

# Answer
> 1 votes
# Pyth, ~~11~~ 10 bytes

It was difficult for me to find a function to convert to a string while searching the online tutorial. I just guessed ``` and was right. I suppose this site is better for searching.

```
q.{`^Q3.{`

```

**Try it online**

**Explanation**

```
     Q          evaluated input (implicit Q at the end as well)
    ^  3        cubed
   `      `     str() - it's actually repr, but doesn't have an 'L' at the end of longs
 .{     .{      convert each string to set()
q               check if equal
                implicit print

```

# Answer
> 1 votes
## Batch, 202

```
@set/an=%1,c=n*n*n,e=1
@for /l %%a in (0,1,9)do @call:l %%a
@exit/b%e%
:l
@set f=1
@call set s=%%n:%1=%%
@if "%s%"=="%n%" set/af=1-f
@call set s=%%c:%1=%%
@if "%s%"=="%c%" set/af=1-f
@set/ae*=f

```

Note: Only works up to 1290 due to the limited range of Batch's data type. Takes input on the command line and returns an error level of 1 if the cube uses the same set of digits, 0 otherwise. Works by looping through each digit, checking to see whether an even number of the two strings contains the digit.

# Answer
> 1 votes
# DASH, 33 bytes

```
@=(f\ss[sort I;unq;str])#0f ^#0 3

```

Usage:

```
(@=(f\ss[sort I;unq;str])#0f ^#0 3)500

```

# Explanation

```
@
  =                       #. check if the following are equal
    (f\                   #. store the following to f:
      ss[sort I;unq;str]  #. composition of to string, unique, sort
    )
      #0                  #. apply f to the arg
    f ^ #0 3              #. apply f to arg cubed

```

# Answer
> 1 votes
# ES6 (Javascript), ~~32~~, 58 bytes

**Golfed**

```
n=>(x=(a,b)=>!RegExp(`[^${a}]`).test(b))(m=n*n*n,n)&x(n,m)

```

**Test**

```
N=n=>(x=(a,b)=>!RegExp(`[^${a}]`).test(b))(m=n*n*n,n)&x(n,m)

N(0)
1 (true)

N(1)
1 (true)

N(10)
1 (true)

N(107624)
1 (true)

N(251894)
1 (true)

N(251895)
0 (false)

N(102343)
0 (false)

N(106239)
0 (false)

```

# Answer
> 1 votes
# Scala, 57 chars

```
def n(x:BigInt)=x.toString.toSet==(x*x*x).toString.toSet

```

# Answer
> 1 votes
# dc, 69 bytes

This takes input from top of stack, and leaves a result on top of stack. The result is the count of symmetric difference between the digit sets, so zero indicates true, and other numbers indicate false.

```
d[O~1r:ad0<f]dsfx+3^[O~1r:bd0<f]dsfxsaO[1-ddd;ar;b-d*la+sad0<m]dsmxla

```

## Explanation

Expanded version as commented full program with I/O to standard streams:

```
#!/usr/bin/dc

# read input
?

# store 1 in a[i] for each digit i
d[O~
  1r:a
  d0<f]dsfx
# cube the original number
+3^
# record its digits in b[]
[O~
 1r:b
 d0<f]dsfx

# 0 left on stack used to initialize accumulator
sa
# for i in 9..0, add (b[i]-a[i])^2
# accumulate in register 'a'
O[1-d
  dd;ar;b-d*
  la+sa
  d0<m]dsmx

# load result from accumulator
la

# print output
p

```

I hoped I could re-use the first function to store to both `a[]` and `b[]` but I couldn't find an easy way to do it. Arrays can't be pushed or popped, and it was too hard to add an indirection to the function.

## Test results

Here's the test cases from the question, plus those suggested in comments:

```
0 -> 0
1 -> 0
10 -> 0
107624 -> 0
251894 -> 0
251895 -> 4
102343 -> 6
106239 -> 1
2103869 -> 0

```

And here's the first 50 terms of A029795, of 536 that I identified with this program by testing the numbers up to ten million:

```
0
1
10
100
1000
10000
100000
107624
109573
132485
138624
159406
165640
192574
205738
215806
251894
281536
318725
419375
427863
568314
642510
713960
953867
954086
963218
965760
1000000
1008529
1023479
1023674
1026258
1028537
1028565
1028756
1032284
1035743
1037689
1039725
1045573
1046783
1062851
1062854
1063279
1063724
1066254
1072399
1073824
1076240

```

# Answer
> 1 votes
# C#, 87 bytes

Inspired by @Yodle, but I can't put a comment on his answer because I lack the reputation, I just parsed the string in a separate variable, this saves 5 characters:

```
var n=long.Parse(i);return new HashSet<char>(i).SetEquals(new HashSet<char>(n*n*n+""));

```

# Answer
> 1 votes
# CJam, 15 bytes

I know it's not the best answer, but it is my first one:

```
l:Fi3#s$L|FL|$=

```

Explanation:

```
l            Read input
 :F          Put it in the var F
  i          Convert to int
   3#        Raise to the 3rd power
    s        Back to a string
     $       Sort
      L|     Remove dupes
       FL|   Remove dupes from the original input
        $    Sort
         =   Check if they are equal

```

# Answer
> 1 votes
# MKSH (BASH) ,3̶9̶ 4̶1̶ 3̶6̶ 5̶2̶ 46 bytes

## (38 bytes without printing return value)

3g.sh:

```
c=`bc<<<$1^3`;[ ${c//[$1]}${1//[$c]} ];echo $?

```

Usage from file:

```
$ mksh 3g.sh 100
1
$ mksh 3g.sh 11
0
$ mksh 3g.sh 251894
1

```

Or from command line displaying return value outside (**38 bytes**):

```
$ mksh -c 'c=`bc<<<$0^3`;[ ${c//[$0]}${0//[$c]} ]' 2103869;echo $?
1
$ mksh -c 'c=`bc<<<$0^3`;[ ${c//[$0]}${0//[$c]} ]' 102343;echo $?
0
$ mksh -c 'c=`bc<<<$0^3`;[ ${c//[$0]}${0//[$c]} ]' 106239;echo $?
0

```

My question: is my 2nd oneliner a valid solution? The result should be printed on terminal or is it enough in an invisible return value? ( I'm new to codegolf. )

# Answer
> 1 votes
# Convex, 6 bytes

```
3#sê^!

```

Try it online!

Well, I guess major bugs in some operators can help in golfing sometimes...

# Answer
> 1 votes
# Python 2, ~~36~~ 33 bytes

```
lambda x:set(`x`)==set(str(x**3))

```

Can't use backticks (`repr`) on large numbers because it includes the `'L'`.

# Answer
> 1 votes
# Python 3, 61 Bytes

```
n=input()
print([i for i in str(int(n)**3)if i not in n]==[])

```

Or in python 2 (60 Bytes):

```
n=input()
print[i for i in str(n**3) if i not in str(n)]==[]

```

# Answer
> 1 votes
# Pushy, ~~13~~ 10 bytes

```
V3esuFsux#

```

**Try it online!**

Like most other answers here, it just generates sets for both numbers and checks for equality:

```
     \ Implicit: Input on stack 1
V    \ Copy into stack 2
3e   \ Cube (stack 1)
su   \ Split into digits and create sorted set
Fsu  \ ^ Do the same to the second stack (not cubed)
x#   \ Check cross-stack equality and output (0 or 1)

```

# Answer
> 1 votes
# PowerShell 3+, 72

```
filter f{"$("$_"[0..99]|sort -u)"}(($a=[long]$args[0])|f)-eq($a*$a*$a|f)

```

Pretty much the same solution idea as TimmyD had, just a lot shorter (and arrived at independently). I also think there aren't that many more *obvious* PowerShell solutions to this.

# Answer
> 1 votes
## Mathematica 31 Bytes

```
(f=Sign@*DigitCount)@#==f[#^3]&

```

because `Sign<Union` and `DigitCount<IntegerDigits`

# Answer
> 1 votes
# Pyt, 8 bytes

```
Đ³ąỤ⇹ąỤ\

```

Try it online!

Outputs an empty list if true

```
Đ³ąỤ⇹ąỤ\
            Implicit input
Đ           Duplicate input
 ³          Cube
  ą         Make array of digits
   Ụ        Filter so you have no duplicates
    ⇹       swap
     ąỤ     make array of digits and filter duplicates
       \    set difference

```

# Answer
> 1 votes
# Brachylog, ~~9~~ 7 bytes

```
d.&^₃dp

```

Try it online!

-2 bytes thanks to Fatalize for fixing the interaction between zero and `p`.

The predicate succeeds if the input has the same set of digits as its cube, and fails otherwise. If run as a standalone program, success prints `true.` and failure prints `false.`

```
d          The input with duplicates removed
 .         is the output variable
  &^₃      and the input cubed
     d     with duplicates removed
      p    is a permutation of the output variable.

```

# Answer
> 1 votes
# Pari/GP, 35 bytes

```
n->(d=i->Set(digits(i)))(n)==d(n^3)

```

Try it online!

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

```
ⁿαÉ▒▀z=

```

Try it online!

-2 bytes thanks to KevinCruijssen. By changing the map to a for loop, we save one byte from not having to do a map (`m`), and another byte from not having to dump the array onto the stack (`~`).

## Explanation

```
ⁿ         pop a : push(a*a*a)
 α        wrap last two elements in array
  É       start block of length 3
   ▒      split to list of chars/digits
    ▀     unique elements of string/list
     z    reverse sort(array)
      =   pop(a, b), push(a==b)

```

# Answer
> 1 votes
# Husk, 9 bytes

```
¤=ȯOud¹^3

```

Try it online!

# Answer
> 1 votes
# Japt `-!`, 4 bytes

```
³skU

```

Try it here

```
³skU     :Implicit input of integer U
³        :Cubed
 s       :Convert to string
  kU     :Remove all digits that appear in U
         :Convert to integer, resulting in NaN if all digits were removed
         :Implicit output of negation of result

```

# Answer
> 1 votes
# GolfScript, 6 bytes

```
.~3?^!

```

Try it online!

```
.        # Copy the input                "102343" "102343"
 ~       # Parse it to an integer        "102343" 102343
  3?     # Cube it                       "102343" 1071949756947607
    ^    # Get the different digits      "237956"
     !   # Is it an empty string?        0

```

# Answer
> 1 votes
# Thunno 2, 2 bytes

```
³ḍ

```

Try it online!

Output with inverted booleans - add the `!` flag to take the logical NOT of the result.

#### Explanation

```
    # Implicit input
³   # Cube it
 ḍ  # Symmetric set difference
    # Implicit output

```

# Answer
> 0 votes
# Pyth - 9 bytes

Hopefully can take another char off.

```
@I.{`^Q3`

```

Test Suite.

```
!          Negation, tells if set is empty
 -         Setwise subtraction
  `^Q3     String repr of input^3
  `        String repr of implicit input

```

# Answer
> 0 votes
## C#6, ~~117~~ ~~118~~ 115 bytes

```
using System.Linq;bool A(ulong n){string s=n+"",t=n*n*n+"";return s.All(x=>t.Contains(x))&t.All(x=>s.Contains(x));}

```

Praise `System.Linq.Enumerable`

+1 byte due to `long` range problem
-3 bytes by storing strings to variable

Ungolfed + explanations

```
bool A(ulong n)
{
    // Convert n and n^3 to strings
    string s=n+"",t=n*n*n+"";
    // Two sets are equal iff:
    // Foreach element in one set, it is also present in another set
    return s.All(x=>t.Contains(x))&t.All(x=>s.Contains(x));
}

```

# Answer
> 0 votes
# PHP, 48 bytes

```
<?=($f=count_chars)($a=$argv[1],3)==$f($a**3,3);

```

It's the first time I've assigned a function to a variable like this and I'm honestly quite surprised that it works.

# Answer
> 0 votes
# Actually, 12 bytes

```
3ßⁿk`$╔S`Mi=

```

Try it online!

Explanation:

```
3ßⁿk`$╔S`Mi=
3ßⁿ           copy of input, cubed
   k          [input, input**3]
    `$╔S`M    for each:
     $          stringify
      ╔         remove duplicate elements
       S        sort
          i=  flatten and compare equality

```

# Answer
> 0 votes
# J, 18 bytes

```
-:&(/:~)&~.&":^&3x

```

I think this is the most`&`s I've used in an answer to date. This is a fork:

```
-:&(/:~)&~.&": ^&3x

```

The verb on the right, `^&3x`, raises the argument to the `3`rd power, converting to an e`x`tended number if necessary. Then, the verb on the left takes right arg (cubed arg) and left arg (arg). `&` applies the verb following to each argument, then passes each argument to the preceding function. So, this is:

```
-:&(/:~)&~.&":
            ":  string representation
         ~.     unique elements
   (/:~)        sorted
-:              are the same

```

## Test cases

```
   f=:-:&(/:~)&~.&":^&3x
   (,. f"0) 0 1 10 107624 251894 251895 102343
     0 1
     1 1
    10 1
107624 1
251894 1
251895 0
102343 0
   f 251894
1
   f 251895
0

```

# Answer
> 0 votes
# Julia 40 bytes

```
 h(x)= ==(Set.(digits.([x,big(x)^3]))...)

```

Test:

```
h.([0,1,10,107624,251894,251895,102343,106239,2103869])
9-element Array{Bool,1}:
  true
  true
  true
  true
  true
 false
 false
 false
  true

```

# Answer
> 0 votes
# Julia, 34 bytes

```
!n=symdiff("$n",dec(big(n)^3))==[]

```

How does it work? Well, strings act like arrays in many ways, so we can apply the `symdiff` (symmetric difference) function to a pair of strings to get an array of all characters found in only one of the two strings. If that is an empty array (`[]`), then the set of digits is the same.

`big` is used to make sure it handles larger values of `n^3` (anything that would overflow in 64 bit), although it will still be limited in terms of `n` itself (but easily covers the range required).

# Answer
> 0 votes
**C#**

Without any 32 or 64 bit limits...

```
Func<BigInteger,bool> x = n => !(n * n * n + "").Except(n + "").Any();

```

# Answer
> 0 votes
# Actually, 10 bytes

This answer uses the direct approach, using `str(), sort(), uniq()` on `n` then `n**3` directly. Golfing suggestions welcome! Try it online!

```
$S╔3ßⁿ$S╔=

```

**Ungolfing**

```
      Implicit input n.
$S╔   str(), sort(), uniq() on n.
3ßⁿ   Push n**3.
$S╔   str(), sort(), uniq() on n**3.
=     Check if the results are equal.
      Implicit return.

```

# Answer
> 0 votes
# bash, 42

```
[[ $1 = +([$((a=$1**3))])&&$a = +([$1]) ]]

```

# Answer
> 0 votes
# Scala, 34 bytes

```
i=>s"$i".toSet==(""+(i*i*i)).toSet

```

Usage:

```
val f:(BigInt=>Boolean)=...
print(f(2103869))

```

Explanation:

```
i=>            //define an anonymous function with a parameter i
    s"$i"        //use string interpolation to convert i to a string
    .toSet       //convert the string to a set of chars
  ==           //is it equal to...
    (
    ""+(i*i*i)   //i*i*i as a string
    ).toSet      //as a set of chars

```

# Answer
> 0 votes
## Matlab/Octave, 39 bytes

```
a=@(x)(unique(num2str(x)));min(a(x)==a(x^3))

```

# Answer
> 0 votes
# Swift 3, 75 bytes

```
func a(n:UInt64){print(Set("\(n)".characters)==Set("\(n*n*n)".characters))}

```

# Answer
> 0 votes
# Axiom, ~~92~~ 76 bytes

```
g(y:String):String==removeDuplicates(sort(y));f(x)==(g(x)=g((x^3)))::Boolean

```

results

```
->[i,f(i)] for i in [0,1,10,107624,251894,251895,102343,106239]

  [[0,true], [1,true], [10,true], [107624,true], [251894,true],
   [251895,false], [102343,false], [106239,false]]

```

# Answer
> 0 votes
# Python, 88 bytes

```
lambda n:reduce(lambda x,y:x*y,map(lambda x:x[0]in str(x[1]),[(i,n)for i in str(n**3)]))

```

Worked in version 2.7.9.

This lambda `lambda x:x[0]in str(x[1])` receives a tuple, which first element is an char and the second element is a integer. This function checks if the char is in the string correspondent to the integer.

This `[(i,n)for i in str(n**3)]` creates a set of arguments, for each character of the string of n³, and function `map` evaluates the lambda function for each argument of the set. Then, the result is a list of booleans that tell if each character of the string of n³ is in the string of n. The reduce and the lambda `reduce(lambda x,y:x*y,...)` multiplies all the elements of the list, returning 1 if all the characters of the string of n³ are in the string of n and 0 otherwise.

A 89 bytes solution with a similar idea but with different implementation is:

```
lambda n:len(filter(lambda x:x[0]in str(x[1]),[(i,n)for i in str(n**3)]))==len(str(n**3))

```

Here, `filter` literally filter the elements of the set of arguments that leads the internal lambda function to returns True. The resulting list has its length compared to the length of the string of n³ to check if all the characters of the string of n³ are in the string of n.

# Answer
> 0 votes
# Clojure, 109 bytes

```
(use '[clojure.string :only(split)])#(if(= (into #{}(split(str %)#""))(into #{}(split(str(* % % %))#"")))1 0)

```

Use the function like this:

```
...(#(...) 106239)

```

Yikes, that is a long one-liner.

Ungolfed:

```
(use '[clojure.string :only (split)])
(defn cube [n]
  (if (= (into #{} (split (str n) #""))
         (into #{} (split (str(* n n n)) #"")))
    1 0))

```

# Answer
> 0 votes
# APL NARS 29 chars

```
{(⍵>2e6)∨⍵<0:¯1⋄''≡(⍕⍵)§⍕⍵*3}

```

f has meaningful result only if 0\<=arg\<=2000000 else if arg\>=2098567 (so i wrote 2000000 for round) it miss digits as float with result can not be meaningful...So if arg of f is out 0\<=arg\<=2000000 it return the error number ¯1

```
  f←{(⍵>2e6)∨⍵<0:¯1⋄''≡(⍕⍵)§⍕⍵*3}
  f¨ 0 1 10 107624 251894 251895 102343
1 1 1 1 1 0 0
  f 2000000
0
  f 2000001
¯1
  f ¯9
¯1

```

# Answer
> 0 votes
## Clojure 35 bytes

```
#(every?(set(str %))(str(* % % %)))

```

Same byte count as an earlier answer, but slightly different approach.

More obscure but unfortunately longer:

```
#(apply =(map(comp set str)[%(* % % %)]))

```

# Answer
> 0 votes
## Alice, 15 bytes

```
/D.n~@
\iXDo/3E

```

Try it online!

Prints `Jabberwocky` as a truthy result and nothing as a falsy result (Alice's canonical truthy and falsy values in Ordinal mode).

### Explanation

```
/   Switch to Ordinal mode.
i   Read all input as a string.
.D  Duplicate the string and then deduplicate the characters of the copy,
    turning it into the set of digits.
~   Swap with the other copy.
/   Switch to Cardinal mode.
3E  Implicitly convert the string to the represented integer value N and raise
    it to the third power.
\   Switch to Ordinal mode.
D   Implicitly convert N^3 to a string and deduplicate its characters as well.
X   Symmetric multiset difference. Gives an empty string iff both strings
    are permutations of each other. The fact that Alice only has multiset
    oprations is the reason why we needed to use D on both strings.
n   Logical NOT. Turns the empty string into the (truthy) "Jabberwocky"
    and everything else into the (falsy) empty string.
o   Output the result.
@   Terminate the program.

```

# Answer
> 0 votes
# Add++, 12 bytes

```
L,d3^BD€q=

```

Try it online!

## How it works

```
L,		; Define a lambda function
		; Example argument:         [106239]
	d3^	; Push n³;          STACK = [106239 1199090390129919]
	BD	; Get the digits;   STACK = [[1 0 6 2 3 9] [1 1 9 9 0 9 0 3 9 0 1 2 9 9 1 9]]
	€q	; Deduplicate €ach; STACK = [{0 1 2 3 6 9} {0 1 2 3 9}]
	=	; Equal?	    STACK = [0]

```

# Answer
> 0 votes
# Stax, 9 bytes

```
à±▒!⌂▼▒RÜ

```

Run and debug online!

## Explanation

Uses the unpacked version to explain.

```
cJ*EuxEu|n!
cJ*            Raise to 3rd power (can also be `3|*`)
   Eu          Discrete digits
     xEu       Discrete digits of input
        |n!    Array xnor

```

# Answer
> 0 votes
# JavaScript ES7, 48 bytes from Downgoat 's

```
F=
n=>(f=s=>[...new Set(s+f)].sort()+f)(n)==f(n**3)

console.log([0,1,10,107624,251894,251895,102343].map(F))
```

---
Tags: code-golf, number, decision-problem
---


# Question
Title: (Robbers) Fast and Golfiest Season 1: The Lord of the Strings
## Fast and Golfiest Robbers Thread

Welcome to the first season of **Fast and Golfiest**, a cops-and-robbers challenge! I designed this challenge to encourage competitive coding for efficiency (fastest algorithm) to become more popular on the site.

The rules are simple. The cops choose problems from LeetCode, a competitive coding platform, and solve them with code as efficient and short as possible. Now you, as the robber, will try to golf up their code, **without** sacrificing code efficiency. That is, the time complexity of your code must be smaller or equal to the cop code's complexity. You must also use the same language as the cop. Here's the link to the Cops Thread. Note that for the robbers, **golfiness matters most**! However, if your time complexity is lower than the cop code **and** shorter than theirs, your score will be 2.718 times the original!

Your answer post should include the following:

1. A link to the cop post you cracked.
2. Your code, its length in bytes.
3. The UTC time of your post.
4. The time complexity of your code (must be smaller or equal to the cop code's complexity).

You should also edit the cop post to say "Cracked" and add a link to your post.

Your score is the percentage reduction of the code length in bytes compared to the cop code (with the 2.718 times efficiency bonus if you got it), rounded to the nearest integer! **Edit**: Sorry, it seems unbalanced now so I have to nerf the robbers. The robbers' score will be divided by 4.

If you have any advices please let me know in the comments so that this challenge series could be improved. Thanks in advance!

Leaderboard (Periodically updated. Please note that I rank individual answers instead of answerers to encourage quality over quantity.):

1. 9 points: ATOI String to Integer by The Thonnu
2. 5 points: Concatenated Words by CursorCoercer
3. 4 Points: Longest Substring Without Repeating Characters by CursorCoercer

# Answer
# Python, 84 bytes (35.4% reduction), cracks ATOI string to integer

```
lambda s:min(max(L:=-2**31,int([*re.findall("^ *([+-]?\d+)",s),0][0])),~L)
import re

```

Attempt This Online!

* UTC: 09:28 (updated 09:38)
* Same time complexity as the cops' answer I think.
> 3 votes

# Answer
# C (GCC), 44 bytes (6.4% reduction), cracks Removing Stars From a String

```
i;f(char*s){for(i=0;s[i-=*s++-42?0:2]=*s;);}

```

Attempt This Online!

-2 bytes thanks to c-- (original cop).

I think this involves undefined behavior. I'm not exactly sure. But it works in the exact compiler version.

It doesn't work for empty strings, but the specification says 1 \<= s.length \<= 105.

* UTC: 2023-07-20 18:38:43Z; 2023-07-21 03:55:34Z
* Time complexity \\$O(n)\\$ (same as cops' answer)
> 3 votes

# Answer
# Python, 44 bytes (6.4% reduction), cracks Reverse words in a string

```
lambda g:print(*filter(str,g.split()[::-1]))

```

Attempt This Online!

* UTC: 14:04 (updated 14:18)
* Time complexity \\$O(n)\\$ (same as cops' answer)
> 2 votes

# Answer
# Python, 145 bytes (18% reduction), cracks Concatenated Words

```
lambda z:[i for i in z if any(q&z==q for q in g(i,0))]
def g(a,b=1):
 if b:yield{a}
 for i in range(1,len(a)):
  for j in g(a[i:]):yield{a[:i]}|j

```

Attempt This Online!

* UTC: 14:39
* Time complexity \\$O(n)\\$ (same as the cops')
> 2 votes

# Answer
# Python 3, 112 bytes (5% reduction), cracks Simplify Path, 2023-07-20 18:02 UTC

Just some minor golfs like realizing `elif` isn't needed and tweaking the string used to construct the final output. -1 by The Thonnu

```
def f(p):
 s=[]
 for x in p.split('/'):
  if x=='..'and s:s.pop()
  if x not in'..':s+=x,
 return'/'+'/'.join(s)

```

Try it online!
> 2 votes

# Answer
# Python 3, 125 bytes (13% reduction), cracks Longest Substring Without Repeating Characters

```
def f(s):
 m=x=0;c=set()
 for y in s:
  if y in c:
   while s[x]!=y:c-={s[x]};x+=1
   x+=1
  c|={y};m=max(m,len(c))
 return m

```

Try it online!

* UTC: 18:40
* Time complexity \\$O(n)\\$ (same as cops')
> 2 votes

# Answer
# Go, 168 bytes (2.9% reduction), cracks Count and Say

```
import."fmt"
func g(n int)string{s:="1"
for;n>1;n--{c,o,f,k:=1,"",rune(s[0]),s[1:]+"_"
for _,r:=range k{if r==f{c++}else{o+=Sprintf("%d%c",c,f);f,c=r,1}}
s=o}
return s}

```

Attempt This Online!

* Time: 2023-07-20 21:46:57Z
* Time complexity (same as cops' answer)
> 2 votes

# Answer
# Python, 122 bytes (1.6% reduction), cracks Edit Distance

```
lambda a,b:(d:=range(len(b)+1),[d:=[x:=d[(j:=0)]+1]+[x:=1+min(x,d[(j:=j+1)],d[j-1]-(i==k))for k in b]for i in a])and d[-1]

```

A bit of a cheap crack.

Time: 2023-07-25 02:11:18Z
> 2 votes

# Answer
# \>\<\> (Fish), 171 bytes (3.9% reduction), cracks Generate Parentheses

```

```

Hover over any symbol to see what it does

In plaintext:

```
i>:?v~l2,b2.
10-1<.02}}
:?v~{{l2,06.
v-\&'('o:2*[{1+}]$:
\:?v~$}}&1-b2.
')'/.321o
>:?v;
1+&\&:2*[{1-:}]?v:@&:&l2,-+?!v$
{{&>:?v~}}50ao./~0}]
.61-1&>1-&:2*[{/>1{{69!.|.!7f<

```

Try it

* Time: 2023-07-26 14:58:41Z (updated 15:42:38)
* Time complexity \\$O(n!)\\$ (same as cops' answer)
> 2 votes

# Answer
# Rust, 184 bytes (4.6% reduction), cracks Generate Parentheses

```
fn f(z:i32)->Vec<String>{if z<1{vec!["".into()]}else{(0..z).flat_map(|i|->Vec<_>{let b=f(z-i-1);f(i).iter().flat_map(|c|b.iter().map(move|d|format!("({c})")+d)).collect()}).collect()}}

```

Attempt This Online!

* Time: 2023-07-21 05:06:39Z
* Time complexity \\$O(n!)\\$ (same as cops' answer)
> 1 votes

# Answer
# C (GCC), 66 bytes (7.04% reduction), cracks Sum of Scores for buit strings

```
f(s,l,i)char*s;{for(i=0;s[i]&&s[l+i]==s[i];++i);s=l?i+f(s,l-1):i;}

```

Attempt This Online!

Based on This C tip from G B
> 1 votes

---
Tags: code-golf, string, cops-and-robbers, fastest-algorithm
---


# Question
Title: Find the digit occurring the most in a range of prime numbers
Find the digit which occurs the most in a range of prime numbers.

### Input:

Two numbers, `p` and `q`, specifying the range; the range includes both `p` and `q`.

### Output:

The digit that occurs most frequently in that range of prime numbers. If two or more digits are tied, all of them should be outputted.

### Winning Criteria:

Fastest code to complete *(insert 1+ specific test cases here)* wins.

## Example

**Input:** `21 40`

**Output:** `3`

## Explanation

The prime numbers in the range `21 40` are `23`, `29`, `31`, and `37`. Within these numbers, `2` occurs 2 times, `3` occurs 3 times, and `1`, `7` and `9` occur 1 time each. Thus, as `3` appears the most, the correct output is `3`.

# Answer
> 2 votes
# Python 3

```
import collections
p=lambda n:n>1 and all(n%i for i in range(int(n**0.5),1,-1))
print(collections.Counter(''.join(map(str,filter(p,range(*map(int,raw_input().split(' '))))))).most_common(1)[0][0])

```

Probably not the best way it can be done, but a start. (**196 bytes**)

## Time Specs

Using Python's builtin code timer module, `timeit`, I got these times for each listed range.

```
(1,       11):      0.000084381103520
(1,      101):      0.000338881015778
(1,     1001):      0.003911740779880
(1,    10001):      0.071979818344100
(1,   100001):      1.785329985620000
(1,  1000001):     54.977741956700000
(1, 10000001):   1700.231099130000000

```

It can go over a range of a million numbers in under a minute.

## Usage

```
$ python test.py
21 41
3
$ python test.py
51 89
7
$ python test.py
201 501
3

```

## Ungolfed

```
import collections

def is_it_prime(n):
    if n > 1:
        if all(n % i for i in range(int(n ** 0.5), 1, -1)):
            return True
    return False

start, stop = raw_input.split(' ', 1)

primes = ""
for p in range(int(start), int(stop)):
    if is_it_prime(p):
        primes += str(p)

counter = collections.Counter(primes).most_common(1)
print(counter[0][0])

```

# Answer
> 1 votes
# Mathematica

```
 Print[""<>IntegerString[MaximalBy[Tally[Join@@IntegerDigits[Prime[Range[PrimePi[#1]+1,PrimePi[#2]]]]],Last][[;;,1]]&@@FromDigits/@StringSplit@InputString[]]]

```

## Time Specs

Using Mathematica's builtin timer, `AbsoluteTiming`, I got these times for each listed range.

```
f=MaximalBy[Tally[Join@@IntegerDigits[Prime[Range[PrimePi[#1]+1,PrimePi[#2]]]]],Last][[;;,1]]&
Grid[Table[{1,10^x+1,AbsoluteTiming[f[1,10^x+1]][[1]]},{x,1,7}]]

```

Returns:

```
1        11   0.0003388
1       101   0.0003645
1      1001   0.0016222
1     10001   0.0040902
1    100001   0.0267737
1   1000001   0.211297
1  10000001   4.55387
1 100000001  43.9889

```

It can go over a range of a hundred million numbers in under a minute.

## Usage

```
wolframscript -f primedigitcount.wls
? 21 41
3
wolframscript -f primedigitcount.wls
? 51 89
7
wolframscript -f primedigitcount.wls
? 201 501
3

```

## Ungolfed

Takes the space-seperated input and converts it to two integers

```
a = FromDigits/@StringSplit@InputString[]

```

PrimePi is the inverse function of Prime, so this gets all the primes between the two a's. The `+1` is that if the operand is not prime, it gets the first prime below it, but we want a prime above the smaller number.

```
b = Prime[Range[PrimePi[#1]+1,PrimePi[#2]]&@@a

```

Turns every number in the list into a list of it's digits, and then concatenates all the lists into one list of all the digits

```
c = Join@@IntegerDigits[b]

```

Mathematica has a nice built-in for turning a list into unique items and their counts.

```
d = Tally[c]

```

Takes a list of the item (or items) who has the largest count, and strips off the tally.

```
e = MaximalBy[d,Last][[;;,1]]

```

Converts every number in the list to a string, concatenates them, and prints it.

```
Print[""<>IntegerString[e]]

```

## Conjecture:

In hope that somebody more mathematically inclined could find this to be an O(n) problem, I leave you this conjecture:

If the first number is kept as 1, and the 2nd number tends to be large (n\>100), the result will be no more than two of 1, 3, or 7.

---
Tags: math, fastest-algorithm
---


title: Tic Tac Toe encoder/decoder

text:
# Question
Title: Tic Tac Toe encoder/decoder
James Bond is about to start a new mission and you are his computer scientist friend. As Tic Tac Toe is becoming more and more popular you decide that nothing would be more underhanded than a **Tic Tac Toe encoder/decoder™**.

For each line the decoder will follow the following steps:

* Convert from 'O','X' and ' ' \[space\] to trinary

+ ' ' -\> 0
    + 'O' -\> 1
    + 'X' -\> 2
* Convert from trinary to decimal
* Convert from decimal to letter

Example: **"XO "**

* 210
* 21
* v

The encoder will do the reverse.

As code is much more precise than words, see the reference answer below in which I give an example (very long) implementation of the problem in Python:

Your decoder should be able to decode all the messages encoded with my encoder correctly and my decoder should be able to decode all the messages encoded with your encoder.

This is code-golf, the shortest wins.

## Additional informations

* 0 must be converted to a, the alphabet ends with a whitespace, so 26-\> ' ' \[whitespace\]
* "XXX" is the max, it translates to "222" that translates to 26.
* As in Tic Tac Toe the max line lenght is 3.
* `X -> 2` means X should be replaced by 2
* Encoder/Decoder

+ The encoder goes from plaintext to code.
    + The decoder goes from code to plaintext.

# Answer
## BRAINFUCK, 393 bytes (encoder only)

Guys, we're making something for James Bond. Languages like javascript and C are way too readable! If you want something that the russians will never understand, brainfuck is the only option. It's surly not the shortest or fastest option, but no-one will understand it (and, let's be honest, everyone loves brainfuck)

The code has a couple of limitations though, It only encodes and only one character at a time. Also it doesn't manually stop, you have the stop it after it spits out the output. But hey, it works. This is the code:

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

```

If you want to try it: just run the code with one capital letter as input.

If you want it commented just ask me nicely. A lot of things can be done better but I don't feel like optimizing it now (because brainfuck). Maybe I'll make a decoder too as reversing the process probably isn't that difficult.
> 5 votes

# Answer
# C++, 168 + 135 = 303 bytes

EDIT: saved one byte by requiring uppercase input

I like doing these in C++ because I get to do all sorts of fun nastiness I would never ever do in C++ code.

**Encoder (168):**

Takes a string of uppercase letters and spaces as an argument.

```
#include<cstdio>
int main(int h,char**c){c[0][3]=0;for(c++;h=**c;c[0]++){h=h&32?26:h-65;for(int d=2,e;d+1;d--){h=(h-(e=h%3))/3;c[-1][d]=e&2?88:e*47+32;}printf(c[-1]);}}

```

Readable:

```
#include<cstdio>
int main(int h,char**c)
{
    c[0][3]=0;
    for(c++;h=**c;c[0]++)
    {
        h=h&32?26:h-65;
        for(int d=2,e;d+1;d--)
        {
            h=(h-(e=h%3))/3;
            c[-1][d]=e&2?88:e*47+32;
        }
        printf(c[-1]);
    }
}

```

**Decoder (135):**

Takes a string of X, O, and space as an argument.

```
#include<cstdio>
int b=9,v;int main(int h,char**c){for(c++;h=**c;c[0]++){v+=(h&16?2:h&1)*b;b/=3;if(!b)putchar(v==26?32:v+97),v=0,b=9;}}

```

Readable:

```
#include<cstdio>
int b=9,v;
int main(int h,char**c)
{
    for(c++;h=**c;c[0]++)
    {
        v+=(h&16?2:h&1)*b;
        b/=3;
        if(!b)putchar(v==26?32:v+97),v=0,b=9;
    }
}

```
> 4 votes

# Answer
# CJam, 24 + 25 = 49 bytes

**Encoder**

```
qN/{:i40f/3b'a+_'{=S@?}%

```

**Decoder**

```
q{_Sc=26@'a-?Zb" OX"f=N}%

```

Try it online here
> 3 votes

# Answer
## Javascript, ES6, 157 chars

### Only encoder, 83

```
f=s=>s=="XXX"?" ":(parseInt(s.replace(/./g,x=>" OX".indexOf(x)),3)+10).toString(36)

```

### Only decoder, 77

```
g=s=>(parseInt(10+s,36)-10).toString(3).substr(-3).replace(/./g,x=>" OX"[x])

```

### Both, 157

```
p=parseInt;f=s=>s=="XXX"?" ":(p(s.replace(/./g,x=>" OX".indexOf(x)),3)+10).toString(36);g=s=>(p(10+s,36)-10).toString(3).substr(-3).replace(/./g,x=>" OX"[x])

```

### Test

```
console.log(x=["   ", "XO ", "XXX"], x=x.map(f), x.map(g))

```

PS: Tried to perform some optimization, but failed: resulting code was longer then just concatenation. I don't publish it as it also contains a bug, which had already been fixed.
> 3 votes

# Answer
## R, 121 + 115 = 236

I think I got the spec correct

**Decoder Function 121**

```
d=function(s){i=rev(as.integer(unlist(strsplit(chartr('XO ','210',s),''))));c(letters,' ')[sum(3^(0:(length(i)-1))*i)+1]}

```

**Encoder Function 115**

```
e=function(s){i=which(c(letters,' ')==s)-1;paste(chartr("210","XO ",c(i%/%9%%3,i%/%3%%3,i%%3)),sep='',collapse='')}

```

This only works on lower case characters. Is that a requirement?

Quick Test

```
> mapply(d,c("OO "," OO"," OO","X O","XXX"))
OO   OO  OO X O XXX
"m" "e" "e" "t" " "
> mapply(e,unlist(strsplit('meet ','')))
    m     e     e     t
"OO " " OO" " OO" "X O" "XXX"

```
> 2 votes

# Answer
# Go, 372 bytes \\$= 29 + 171 + 170\\$

* Imports = 29 bytes
* Decoder = 171 bytes
* Encoder = 170 bytes

```
import(."strings";."strconv")
func d(s string)(k string){for _,l:=range Split(s,"\n"){i,_:=ParseInt(NewReplacer(" ","0","O","1","X","2").Replace(l),3,64)
k+=string('A'+i)}
return ReplaceAll(k,"["," ")}
func e(s string)(k string){q:=ReplaceAll(s," ","[")
for _,r:=range q{k+=NewReplacer("0"," ","1","O","2","X").Replace(FormatInt(int64(r-'A'),3))+"\n"}
return Trim(k,"\n")}

```

Attempt This Online!

### Explanation

#### Decoder

```
import(."strings";."strconv")
func d(s string)(k string){
for _,l:=range Split(s,"\n"){            // for each line...
i,_:=ParseInt(                           // turn the string into an int
    NewReplacer(" ","0","O","1","X","2") // define the replacements
    .Replace(l),                         // replace the chars
    3,64)                                // turn it into trinary
k+=string('A'+i)}                        // append to the output string
return ReplaceAll(k,"["," ")}            // replace `[` with spaces

```

#### Encoder

```
import(."strings";."strconv")
func e(s string)(k string){
q:=ReplaceAll(s," ","[")                // replace `[` with spaces
for _,r:=range q{                       // for each character...
k+=NewReplacer("0"," ","1","O","2","X") // define the replacements...
    .Replace(                           // and apply onto...
    FormatInt(int64(r-'A'),3))          // the character, turned into trinary
    +"\n"}                              // and add a newline
return Trim(k,"\n")}                    // trim the final newline

```
> 2 votes

# Answer
# Excel, 81 + 87 = 168 bytes

**Encoder**:

```
=CONCAT(SWITCH(0+MID(BASE(TEXT(CODE(A1)-97,"[=63]26"),3,3),{1,2,3},1),2,"X",1,"O"," "))

```

**Decoder**:

```
=CHAR(97+TEXT(MMULT(SWITCH(MID(A1,{1,2,3},1),"X",2,"O",1,),3^{2;1;0}),"[=26]63"))

```

Input in cell `A1` in both cases.
> 1 votes

# Answer
# Nibbles, 12 + 14 = 26 bytes

## Encoder, 12 bytes

```
.@.`@3%-$6 91=$"OX "

```

Attempt This Online!

*-1 byte thanks to Dominic van Essen*

```
.@.`@3%-%$32~27=$"OX "
.                      For each character c in
 @                      the input as a string
  .                     for each digit d in
   `@3                   convert to base 3
        %$32              ord(c) mod 32
       -    ~             minus 1
      %      27           mod 27
               =$        take the d-th character (1-indexed, wrapping)
                 "OX "    from "OX "

```

## Decoder, 14 bytes

```
*" "`%.;@+`@3.$%/$10 3'a'"{"

```

Attempt This Online!

```
*" "`%.;@+`@3.$%/$10 3'a'"{"
*" "                         Join by spaces
    `%                   "{"  split on '{' characters
      .                        for each line l in
       ;@                       the input as a list of lines
         +            'a'        add the character code of 'a' to
          `@3                     convert from base 3
             .                     for each character c in
              $                     l
                /$10                ord(c) divided by 10
               %     3              modulo 3

```

I realized later that I could've simply used `?"OX"$` instead of `%/$10 3`. The byte count is equal.
> 1 votes

# Answer
Reference answer, completely ungolfed:

```
# Tic-Tac-Toe code encoder

def from_letter_to_decimal(letter):
    alphabet = "abcdefghijklmnopqrstuvwxyz "
    return alphabet.index(letter)

def from_decimal_to_trinary(decimal):
    digits = []
    while decimal:
        digits.append(str(decimal % 3))
        decimal //= 3
    return ''.join(list(reversed((digits))))

def from_trinary_to_line(trinary):
    replace_dict = {"0": " ",
                  "1": "O",
                  "2": "X"}
    for char in replace_dict:
        trinary = trinary.replace(char,replace_dict[char])
    return trinary

def encode_letter(letter):
    decimal = from_letter_to_decimal(letter)
    trinary = from_decimal_to_trinary(decimal)
    line = from_trinary_to_line(trinary)
    return line

def encode_text(text):
    return '\n'.join([encode_letter(letter) for letter in text])

print(encode_text("meet me under the red bridge"))

```

---

```
# Tic-Tac-Toe code decoder

boards = """
OO
OO
OO
X O
XXX
OO
OO
XXX
X X
OOO
O
OO
OXX
XXX
X O
XO
OO
XXX
OXX
OO
O
XXX
O
OXX
XX
O
X
OO

"""

def from_line_to_trinary(line):
    replace_dict = {" ": "0",
                  "O": "1",
                  "X": "2"}
    for char in replace_dict:
        line = line.replace(char,replace_dict[char])
    return line

def from_trinary_to_decimal(n):
    result = 0
    for position,i in enumerate(reversed(n)):
        result += int(i) * 3**position
    return result

def from_decimal_to_letter(n):
    alphabet = "abcdefghijklmnopqrstuvwxyz "
    return alphabet[n]

def decode_line(line):
    trinary = from_line_to_trinary(line)
    decimal = from_trinary_to_decimal(trinary)
    letter = from_decimal_to_letter(decimal)
    return letter

def decode_boards(boards):
    return ''.join([decode_line(line) for line in boards.splitlines() if not line==""])

print(decode_boards(boards))

```
> 0 votes

# Answer
# Ruby, 44 + 54 = 98 bytes

## Encoder

```
->s{[*?A..?Z," "][s.tr(" OX","012").to_i 3]}

```

Attempt This Online!

## Decoder

```
->c{((c<?A??[:c).ord-65).digits(3).join.tr"012"," OX"}

```

Attempt This Online!
> 0 votes

# Answer
# Japt v1.4.5, 12 + 17 = 29 bytes

**Encoder**

```
;C+S gUn" OX

```

Try it

**Decoder**

```
;C+S aU s" OX" ù3

```

Try it

I tried some options that worked with codepoints rather than indexing into `C+S`, but they always ended up being longer in order to handle the space.

#### Explanations:

```
;C+S gUn" OX
;            # C = "abcdefghijklmnopqrstuvwxyz"
 C+S         # Add a space to the end of C
     g       # Get the character at index:
      U      #  Input string
       n" OX #  Converted to base 10 from base " OX"

```

---

```
;C+S aU s" OX" ù3
;                 # C = "abcdefghijklmnopqrstuvwxyz"
 C+S              # Add a space to the end of C
     aU           # Find the index of the input string
        s" OX"    # Convert to base " OX"
               ù3 # Left pad with spaces to length 3

```
> 0 votes

# Answer
# Scala, 90+107=197 bytes

Port of @Jordan's Ruby answer in Scala.

---

### Encoder

Golfed version. Attempt This Online!

```
s=>(('A'to'Z')++Seq(' '))(Integer.parseInt(s.map{case'O'=>'1'case'X'=>'2'case' '=>'0'},3))

```

Ungolfed version. Attempt This Online!

```
object Main {
  def main(args: Array[String]): Unit = {
    def f(s: String): Char = {
      val alphabet = ('A' to 'Z') ++ Seq(' ')
      val mapped = s.map {
        case 'O' => '1'
        case 'X' => '2'
        case ' ' => '0'
      }
      val idx = Integer.parseInt(mapped, 3)
      alphabet(idx)
    }

    println("["++f("XO ").toString++"]")
    println("["++f("XXX").toString++"]")
  }
}

```

### Decoder

Golfed version. Attempt This Online!

```
c=>{val n=if(c<'A')26 else c-'A';Integer.toString(n,3).map{case'0'=>' ';case'1'=>'O';case'2'=>'X'}.reverse}

```

Ungolfed version. Attempt This Online!

```
object Main {
  def F(c: Char): String = {
    val n = if (c < 'A') 26 else (c - 'A').toInt
    val base3 = Integer.toString(n, 3)
    base3.map {
      case '0' => ' '
      case '1' => 'O'
      case '2' => 'X'
    }.reverse
  }

  def main(args: Array[String]): Unit = {
    println(F('V'))
    println(F(' '))
  }
}

```
> 0 votes

# Answer
# APL (Dyalog Unicode), 18 + 18 = 36 bytes

Decoder:

```
(⊂3⊥⍉' O'⍳⎕)⌷27↑⎕A

```

Encoder:

```
' OX'[⍉3 3 3⊤⎕A⍳⎕]

```

Try it online!
> 0 votes

---
Tags: code-golf, tic-tac-toe, base-conversion
---