Do n and n^3 have the same set of digits?

52

3

Given a number n (0 <= n <= 2642245), check if n and n3 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

Oliver Ni

Posted 2016-11-14T19:02:08.850

Reputation: 9 650

28Proposed test case: 106239 – Dennis – 2016-11-14T22:41:55.730

8Test case: 2103869 -> True. This (or a larger one) is necessary to test a language with a long datatype. – mbomb007 – 2016-11-14T22:43:53.613

5Too bad the max is too big for language without a 64 bit integer type. – edc65 – 2016-11-15T07:32:17.067

17I think you should be explicit about the base... in binary it's kinda half the fun :-D – The Vee – 2016-11-15T13:06:17.340

2@TheVee Decimal is the default base for challenges involving digits in numbers. – Mego – 2016-11-16T19:11:12.460

@Dennis why so many "upvotes"? I may have missed the point, but I'm interested. – Zoltán Schmidt – 2016-11-17T23:22:37.147

7@ZoltánSchmidt 106239 is the smallest positive integer n such that 1199090390129919 – does not contain all digits of n. Some answers were only checking if n contained all digits of and thus got the wrong result for 106239. – Dennis – 2016-11-17T23:28:07.227

@Dennis ooooh, clever! Thanks! – Zoltán Schmidt – 2016-11-17T23:43:09.837

@edc65 - Too bad the max is so small that 64-bit integers are sufficient. – Toby Speight – 2016-11-18T09:48:43.787

Answers

28

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.

0WJYxW9FMN

Posted 2016-11-14T19:02:08.850

Reputation: 2 663

@Emigna No, you wouldn't be able to add a string and an integer. – 0WJYxW9FMN – 2016-11-14T19:09:33.380

@daHugLenny You can't use the set(...) function, though. – 0WJYxW9FMN – 2016-11-14T19:12:15.213

8In python 2 you can use backtics as a shortcut for repr(), saving 6 bytes. set(\x`)` – DenDenDo – 2016-11-14T19:49:46.587

9

@DenDenDo Any input larger than 2097152 (sys.maxint**(1/3.)) and less than sys.maxint+1 will return False if you use repr(). https://repl.it/EXs2/1. Longs have an L at the end.

– mbomb007 – 2016-11-14T21:03:51.087

9Untested, but you can probably do lambda x:{*str(x)}=={*str(x**3)} in Python 3.5+. – Copper – 2016-11-14T22:23:29.280

@Copper You can do that? I never realised! Thanks! – 0WJYxW9FMN – 2016-11-15T17:27:20.313

The {*...} trick is cool! But why does the code need to be prefixed with lambda x:? Is making it a function part of the question? – Ben Hoyt – 2016-11-15T17:41:47.153

1@BenHoyt It's more concise than using print(...) and input(). Making it a function is shorter than making a full program. – 0WJYxW9FMN – 2016-11-15T19:03:29.640

1Because the question says returning a truthy or falsy value is enough, you can replace == by ^. Two equal sets lead to {} which is falsy. – RemcoGerlich – 2016-11-17T08:03:56.910

1@RemcoGerlich Wouldn't I then have to switch truthy and falsy around? – 0WJYxW9FMN – 2016-11-17T16:55:09.407

@J843136028: yes, of course, sigh. Never mind. – RemcoGerlich – 2016-11-17T17:49:27.240

I suppose you could bitflip the falsy to make it truthy and vice versa... but then it would be the same number of characters. – 0WJYxW9FMN – 2016-11-17T17:57:23.720

I would specify that this works in python 3. 5 and after... – Bakuriu – 2016-11-18T13:44:15.513

@Bakuriu I never realised. Thanks! – 0WJYxW9FMN – 2016-11-18T17:16:21.283

19

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

Emigna

Posted 2016-11-14T19:02:08.850

Reputation: 50 798

1

@PuzomorCroatia: 05AB1E uses the CP-1252 encoding, so all these characters are 1 byte each. It is quite common for golfing languages to either use code pages with more printable characters than UTF-8 or alternatively create their own code page.

– Emigna – 2016-11-16T09:06:35.647

7Thanks for the answer. Unfortunately, while trying to edit my comment, I deleted it. Just to make things clear to everyone, I asked about encoding of characters in code golfing languages – Puzomor Croatia – 2016-11-16T09:09:43.477

14

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);
}

Karl Napf

Posted 2016-11-14T19:02:08.850

Reputation: 4 131

The ungolfed code is missing 1 << when setting the bits with k |= 1 << i % 10. Great solution! – 1Darco1 – 2016-11-15T10:54:24.907

1

I used this bitmap idea to make a 39 byte x86-64 machine code function :)

– Peter Cordes – 2016-11-17T00:33:41.500

Are we allowed to consider 0 as truthy? I guess strcmp works that way, so it seems reasonable in C. – Peter Cordes – 2016-11-17T00:55:31.993

1This only works for the entire range of inputs required by the question if int larger than 64-bit. (Even signed 64-bit is not enough, but unsigned 64-bit is). So there are no real implementations of C that I know of where this satisfies the question's requirements. (It does work correctly with unsigned long long, or just unsigned long in implementations where that's a 64-bit type). GNU C defines __int128_t on 64-bit machines (without any headers)... – Peter Cordes – 2016-11-17T00:59:17.043

8

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.

Denis Ibaev

Posted 2016-11-14T19:02:08.850

Reputation: 876

1Nice answer! You can still save a few (3) bytes : perl -pe '$_=$_**3!~/[^$_]/' – Dada – 2016-11-14T22:39:17.583

@Zaid Thanx. Fixed. – Denis Ibaev – 2016-11-15T13:00:32.210

Now it outputs false for 10 :( – Zaid – 2016-11-15T13:19:45.257

@Zaid Yep. -l flag needed. – Denis Ibaev – 2016-11-15T14:11:30.177

2Change the && to a * to save a byte – Gabriel Benamy – 2016-11-15T17:38:51.260

7

Mathematica, 34 bytes

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

Direct implementation (unnamed function of one integer argument).

Greg Martin

Posted 2016-11-14T19:02:08.850

Reputation: 13 940

7

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.

Dennis

Posted 2016-11-14T19:02:08.850

Reputation: 196 637

6

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.

Peter Cordes

Posted 2016-11-14T19:02:08.850

Reputation: 2 810

Code golf in machine code? That's true mastery! – chx – 2016-11-18T06:50:53.953

@chx: It's really in assembly language, optimizing for code size. I don't write the hex bytes directly, I just know (or check on) what size each instruction is. (What I posted is from assembling with yasm and then running objdump -drwC -Mintel on the object file, and copying comments). It's a language where optimizing for code size is actually useful in real life. (But even then, only in rare cases like bootloaders or demos. Usually it's only worth saving code size when it doesn't hurt performance in the already-cached case, but then it is useful avoid decode bottlenecks + cache misses) – Peter Cordes – 2016-11-18T06:58:23.763

@chx: but yes, golfing in asm does make me feel like a badass, thanks for noticing :) See my other answers, here and on SO :) – Peter Cordes – 2016-11-18T07:01:22.863

I am a very old hat in assembly (1987, Z80 was the first) but I would've never thought to enter into code golf with that. I would've thought impossible. – chx – 2016-11-18T07:11:11.813

@chx: I only golf occasionally, usually only when I see one in Hot Network Questions that looks reasonable for asm. Usually stuff with numbers, not strings. A few other people do golf in asm, though. I hadn't thought of doing so myself until I saw someone else's machine-code golf answer. Might have been this one that clued me in to the fact that you can count machine code bytes instead of asm source characters for asm answers. anatolyg has posted some, including on this question.

– Peter Cordes – 2016-11-18T07:20:58.977

Nice work, that BTS instruction really saves the day! – Karl Napf – 2016-11-23T13:35:27.137

@KarlNapf: yeah, IDK why compilers don't use it more often. It's fast on Intel CPUs with a register destination. (1 uop, 1c latency, can run on multiple ALU execution ports on Intel SnB-family (source). It's 2 m-ops on AMD Bulldozer-family, but that's still cheap. The funny thing about it is how slow it is with a memory destination: cheaper to load / bts / store separately, because of its crazy-CISC bitstring behaviour with a memory operand: the address read/written depends on the source operand!

– Peter Cordes – 2016-11-23T13:52:48.840

6

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.

Conor O'Brien

Posted 2016-11-14T19:02:08.850

Reputation: 36 228

it's terrible that there isn't a nicer way to compare sets for equivalence – njzk2 – 2016-11-14T22:39:43.340

1@njzk2 Well, I'd say the greater tragedy is that == doesn't work even on arrays. – Conor O'Brien – 2016-11-14T22:42:01.430

You can save a byte by changing n*n*n to n**3, but I guess that might be ES7 and not ES6. – Robert Hickman – 2016-11-14T23:06:19.683

Perhaps use \${[...new Set( ... ).sort()}`` if that saves bytes – Downgoat – 2016-11-14T23:43:58.410

1@Downgoat Thanks, that inspired me to save some more bytes! – Conor O'Brien – 2016-11-14T23:49:50.763

The last parenthesis is too many, isn't it? – Huntro – 2016-11-15T08:18:14.437

@Huntro Indeed it is. I copied that from my testing environment, which surrounds the expression in parens. – Conor O'Brien – 2016-11-15T12:04:13.190

3This fails for 2103869, and the problem explicitly requires solutions to work up to 2642245. – user5090812 – 2016-11-16T14:12:24.647

@user5090812 Shouldn't this because of the precision in JS cannot handle number of that size? Say 2103869**3 = 9.30E+18 > 2**53 – Shieru Asakoto – 2018-03-04T23:39:39.553

Does n=>(f=s=>[...new Set(s+[])].sort()+9)(n)==f(n*n*n) work as we don't require the compared string be pure? – l4m2 – 2018-03-05T03:50:50.723

6

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.

Martin Ender

Posted 2016-11-14T19:02:08.850

Reputation: 184 808

6

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+""));};

Yodle

Posted 2016-11-14T19:02:08.850

Reputation: 2 378

Can you check p<0 instead of p==1? – Yytsi – 2016-11-14T21:00:41.377

@TuukkaX Would've done that, but the way I'm determining the sets now is using the same array of integers, incrementing the appropriate index for both strings, so a value of 0 or 2 is okay, but if any are 1, it should return false. – Yodle – 2016-11-14T21:09:35.290

Save very little by extracting the creation and filling of the arrays into a separate lambda: n=>{Func<string,int[]>x=s=>{var a=new int[10];foreach(var c in s)a[int.Parse(c+"")]++;return a;};var i=x(n);var j=x((long)Math.Pow(int.Parse(n),3)+"");for(var k=0;k<10;)if(i[k]>0^j[k++]>0)return 0>1;return 1>0;}; – Corak – 2016-11-15T11:40:41.083

You can replace int.Parse(c+"") with c-'0' – Dennis_E – 2016-11-15T15:53:32.960

Fails test case 2103869. I ran into the same issue. (Nevermind, I found out why. I'd used a long instead of ulong and this test case uses the MSB.) – SaxxonPike – 2016-11-15T21:08:04.983

@SaxxonPike So it turns out if I take the input as a ulong instead of a string, it works. The problem is with Math.Pow() returning a double, so if I just do I*I*I it works as long as I is a ulong. It actually saves bytes doing it this way too because no more Math.Pow() call ^.^ – Yodle – 2016-11-15T21:46:28.627

6

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).

Hypino

Posted 2016-11-14T19:02:08.850

Reputation: 221

That static Y y thing is a weird initialisation syntax, does it autoassign to y.n because the interface has exactly one member? – cat – 2016-11-15T00:39:50.590

I believe so, yes. To be honest I'm newish to Java 8 since my workplace is still on 7, but that's how I perceive it to work. – Hypino – 2016-11-15T03:09:56.173

The compiler automatically adds the @FunctionalInterface annotation (interface with only one method, see javadoc) which makes lambdas work instead of the usual anonymous type instantiation. – 1Darco1 – 2016-11-15T10:44:06.807

This is essentially equal to Y y = new Y() { @Override public boolean n(int x) { return Arrays.equals((a+"").chars().distinct().sorted().toArray(),(new BigInteger(a+"").pow(3)+"").chars().distinct().sorted().toArray()); } } and the staticmodifier is only there to allow calling y.n(int) from the static main method. – 1Darco1 – 2016-11-15T10:51:54.063

Why not a*a*a instead of .pow()? – JollyJoker – 2016-11-15T11:36:35.743

Oh, just realized signed 64-bit isn't enough :( – JollyJoker – 2016-11-15T12:13:01.830

Nice answer! +1 Btw, imports/usings are unfortunately also part of the byte-count, so it should be a->java.util.Arrays.equals((a+"").chars().distinct().sorted().toArray(),(new java.math.BigInteger(a+"").pow(3)+"").chars().distinct().sorted().toArray()); – Kevin Cruijssen – 2016-11-16T14:46:51.513

@KevinCruijssen I was under the impression that that would only be necessary for full programs? – Hypino – 2016-11-16T15:54:14.630

1Nevermind, just read the meta post about this and it seems the community agrees. I suppose I can see why. I will update. – Hypino – 2016-11-16T15:56:53.973

Nice solution! You can use Try it online! to share your answer. It even counts your answer as 1 Byte shorter.

– Bernat – 2017-12-11T14:00:33.783

6

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)

zeppelin

Posted 2016-11-14T19:02:08.850

Reputation: 7 884

I'm afraid the base theory is completely wrong here. Try T <<< 11. Will say the digit sets are the same just because 11**3 == 1331 contains the digits not present in the original number twice. – manatwork – 2016-11-15T11:45:46.420

Yep, you are correct, fixed ! Thank you ! – zeppelin – 2016-11-15T12:30:57.490

Ok, but now some extra spaces left in the code. Not sure why you added the -w explicitly to fold. If uniq is used without options, sort -u can replace it. And feed the 2nd S call with here-string. And I think there is no need to quote the formula passed to bc. – manatwork – 2016-11-15T13:00:55.277

@manatwork, thx, I've fixed the fold argument, removed spaces, and made the second diff argument use a here-doc.

I now also pipe the first argument into diff, and have removed the superfluous quotes around the bc expression.

uniq is used without options, sort -u can replace it.

That's just a remnants of previous version (was uniq -u)).

Thank you ! – zeppelin – 2016-11-15T13:16:58.877

1@zeppelin: you can use cmp instead of diff and save 1 byte. – Ipor Sircer – 2016-11-17T00:28:48.813

@Ipor - that's a nice idea, I will look into this, thx ! – zeppelin – 2016-11-17T15:57:01.337

5

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.

xnor

Posted 2016-11-14T19:02:08.850

Reputation: 115 687

Does Haskell not have set literals, or a function which returns the unique elements from a list? – cat – 2016-11-15T00:27:14.350

2@cat No. Haskell has nub (get unique elements) and sort, but both require the lengthy import import Data.List. Even so, it comes very close at 48 bytes: import Data.List;q=sort.nub.show;f n=q n==q(n^3). – xnor – 2016-11-15T00:32:33.853

Why the need to sort...? – cat – 2016-11-15T00:33:50.520

1@cat nub preserves order by first appearance, i.e. nub [3,1,3,2,1,2] == [3,1,2]. It doesn't convert to a set type (there is none), but gives a list. – xnor – 2016-11-15T00:35:25.293

Oh, I never realised Haskell doesn't have a primitive unordered collection type, that makes sense – cat – 2016-11-15T00:38:15.307

5

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)

Adám

Posted 2016-11-14T19:02:08.850

Reputation: 37 779

1You're assuming that the unique digits in n^3 can't be fewer than those in n? – ngn – 2016-11-18T03:31:31.733

Can you prove the existence of a counter-example? – Adám – 2016-11-19T20:04:41.033

1106239, see comments at the top – ngn – 2016-11-19T20:19:31.617

5

Clojure, 35 bytes

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

MattPutnam

Posted 2016-11-14T19:02:08.850

Reputation: 521

5

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.)

QBrute

Posted 2016-11-14T19:02:08.850

Reputation: 271

Imports/usings are indeed part of the byte-count. You can remove the static though. – Kevin Cruijssen – 2016-11-16T14:50:35.403

Okay thanks. Removed static. – QBrute – 2016-11-16T15:13:54.063

4

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))

rturnbull

Posted 2016-11-14T19:02:08.850

Reputation: 3 689

Sadly this wont work (for large n) unless you use some kind of BigInt package. See ?.Machine for details on the biggest integer and float etc. To see this compare e.g. 2600001^3 in R to wolframalpha

– Billywob – 2016-11-16T15:57:28.777

I've never had to use it myself but it seems like the gmp package could solve this problem. – Billywob – 2016-11-16T16:00:18.400

Ah, good catch! I've updated the answer, it now uses gmp::as.bigz() to handle large integers. – rturnbull – 2016-11-16T16:12:34.113

you could make use of the fact substring converts to a character to split the number, eg s=substring;setequal(s(n<-gmp::as.bigz(scan()),p<-1:1e4,p),s(n^3,p,p)) – MickyT – 2016-11-16T21:31:14.163

@MickyT Fantastic suggestion! I didn't know substring could be used that way (I've only ever used substr). Answer has been edited to incorporate your suggestion now. – rturnbull – 2016-11-16T23:41:48.093

4

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

Angs

Posted 2016-11-14T19:02:08.850

Reputation: 4 825

1Declaring a%b=all(elema)b as a function and then calling with b%a&&a%b should save two bytes. – Laikoni – 2016-11-14T22:32:10.077

4

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'

James

Posted 2016-11-14T19:02:08.850

Reputation: 54 537

This doesn't work with input 100. – Dennis – 2016-11-14T21:10:09.077

I understand why it doesn't, but why doesn't this work?

– James – 2016-11-14T21:12:11.797

1Because Jelly is strictly parsed left to right, without operator precedence. *3ṢQ⁼ṢQ$ works as intended, since the quick $ groups the two atoms to its left into a monadic chain. – Dennis – 2016-11-14T21:14:22.870

4

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;
}

J. Antonio Perez

Posted 2016-11-14T19:02:08.850

Reputation: 1 480

You need to include #include<set> and using namespace std; in the golfed code and byte count – cat – 2016-11-15T00:28:38.557

@cat #include<set> instead of algorithm – Karl Napf – 2016-11-15T00:31:31.357

@KarlNapf oh, I thought all the stdlib containers were acessible through algorithm -- shows what I know about C++ :) – cat – 2016-11-15T00:32:36.003

It seems to me the variable local to the function "c" is not initialized but used c|=1 ... – RosLuP – 2016-12-03T15:43:12.810

4

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).

Karl Napf

Posted 2016-11-14T19:02:08.850

Reputation: 4 131

4

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.

Steven H.

Posted 2016-11-14T19:02:08.850

Reputation: 2 841

4

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())}

F. George

Posted 2016-11-14T19:02:08.850

Reputation: 317

1

Welcome to PPCG! The input/output is implicitly specified because of the [tag:code-golf]. You can see the community-consensus standards here. Your function count should be sufficient.

– AdmBorkBork – 2016-11-15T13:42:51.673

4

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.

Neil

Posted 2016-11-14T19:02:08.850

Reputation: 95 035

4

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.

Brad Gilbert b2gills

Posted 2016-11-14T19:02:08.850

Reputation: 12 713

You can replace the $_ with just . – Jo King – 2019-03-06T01:51:19.050

3

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!

Rado

Posted 2016-11-14T19:02:08.850

Reputation: 161

Hello Rado, and Welcome to PPCG! This is a great first answer, +1! – NoOneIsHere – 2016-11-18T16:41:24.263

I managed to squeeze it even further to 47 chars/bytes by using a closure, but can't edit my previous answer due to being new here, so here it is: def c={"$it".toSet()=="${it.power(3)}".toSet()} – Rado – 2016-11-18T16:43:36.280

1Anonymous functions are acceptable. And use the ** operator for exponentiation. – manatwork – 2016-11-18T16:45:40.207

Thanks @NoOneIsHere! Also, calling the closure for test cases would involve replacing x(107624) with c.call(107624) – Rado – 2016-11-18T16:46:04.207

Thank you @manatwork! Using an anonymous closure and ** brings it down to beautiful 35 chars/bytes: {"$it".toSet()=="${it**3}".toSet()} – Rado – 2016-11-18T16:50:42.140

3

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 -equal 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

AdmBorkBork

Posted 2016-11-14T19:02:08.850

Reputation: 41 581

you can use "$n"[0..99] instead of [char[]]"$n" to save one byte, since the biggest number you'll need to deal with is only about 20 chars in length. – colsw – 2016-11-15T15:29:13.237

@ConnorLSW There's that indexing trick again. I'm going to need to remember that. – AdmBorkBork – 2016-11-15T17:21:06.890

as long as you're guaranteed to be using less than 100 characters it's an easy enough save over the normal char[] conversion, the rest of your code is as good as I could get it, if there was a shorthand way to compare arrays, you could use something like ("$n"[0..99]|group).Name to save loads but compare isn't exactly quick and easy to golf. – colsw – 2016-11-16T10:00:14.173

That's what I get for solving it without looking at the answers ... Pretty much the same answer ;-). But you missed a few very obvious optimizations ;-)

– Joey – 2016-11-18T10:00:37.637

3

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.

nimi

Posted 2016-11-14T19:02:08.850

Reputation: 34 639

Can't you save a byte here using s$n^3? – None – 2016-11-16T04:22:33.753

@ais523: No, because it translates to (s n==s) (n^3) which gives a type error. – nimi – 2016-11-16T08:34:07.007

3

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

Fatalize

Posted 2016-11-14T19:02:08.850

Reputation: 32 976

I like the cat smiley in this :3 – QBrute – 2016-11-15T07:59:17.977

2

Ruby, 48 bytes

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

Lee W

Posted 2016-11-14T19:02:08.850

Reputation: 521

2

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.."]"))

Trebuchette

Posted 2016-11-14T19:02:08.850

Reputation: 1 692

2

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

cat

Posted 2016-11-14T19:02:08.850

Reputation: 4 989

2

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);
        }
    }
}

SaxxonPike

Posted 2016-11-14T19:02:08.850

Reputation: 121

Some other C# golfing exercises do not have using System.Linq. I'd like to discuss its requirement. For example: http://codegolf.stackexchange.com/a/84789/62301

– SaxxonPike – 2016-11-18T17:45:09.990

1

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

kungfushark

Posted 2016-11-14T19:02:08.850

Reputation: 61

Welcome to PPCG! – AdmBorkBork – 2016-11-16T16:04:17.653

1

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. )

Ipor Sircer

Posted 2016-11-14T19:02:08.850

Reputation: 333

1

Welcome to PPCG! You don't get to define what is true and false. Generally, 1 is true, and 0 is false. http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey

– mbomb007 – 2016-11-16T04:43:22.293

So, then i have to add 2 more bytes. :-/ – Ipor Sircer – 2016-11-16T04:53:03.810

1@mbomb007 But this is Bash. Bash defines 0 as truthy and everything else as falsy. And the meta question you link seems to agree with me: truthy and falsy should be understood relative to the language. – Grimmy – 2016-11-16T13:58:40.737

Then perhaps the answer body should be edited to clarify that. – mbomb007 – 2016-11-16T14:53:38.587

1does not work for 106239 – zeppelin – 2016-11-16T16:05:43.590

@zeppelin: corrected – Ipor Sircer – 2016-11-16T21:43:39.270

1@Ipor 106239 still returns 1, 106239^3= 1199090390129919 (note the lack of "6") – zeppelin – 2016-11-16T22:02:02.580

@zeppelin: auch, thx! I misunderstood the task a bit. – Ipor Sircer – 2016-11-16T23:56:09.473

1

Convex, 6 bytes

3#sê^!

Try it online!

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

GamrCorps

Posted 2016-11-14T19:02:08.850

Reputation: 7 058

1

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.

Sherlock9

Posted 2016-11-14T19:02:08.850

Reputation: 11 664

1

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'.

Farhan.K

Posted 2016-11-14T19:02:08.850

Reputation: 111

1

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)]==[]

sonrad10

Posted 2016-11-14T19:02:08.850

Reputation: 535

This would be shorter as a lambda: lambda n:[i for i in str(n**3) if i not in str(n)]==[] – Oliver Ni – 2016-11-17T15:10:54.530

@Oliver I haven't used lambda much before, so I don't know much about how to use it. However, I will bear this in mind if I need it for a future challenge. – sonrad10 – 2016-11-17T20:45:22.157

1

Pushy, 13 10 bytes

V3esuFsux#

Try it online!

(non-competing as the language postdates the challenge)

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)

FlipTack

Posted 2016-11-14T19:02:08.850

Reputation: 13 242

1

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.

Joey

Posted 2016-11-14T19:02:08.850

Reputation: 12 260

You should specify that this is v3+ for the -Unique parameter on the Sort-Object. Otherwise, nice tricks. – AdmBorkBork – 2016-11-19T18:54:43.800

1

Mathematica 31 Bytes

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

because Sign<Union and DigitCount<IntegerDigits

Kelly Lowder

Posted 2016-11-14T19:02:08.850

Reputation: 3 225

1

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

FantaC

Posted 2016-11-14T19:02:08.850

Reputation: 1 425

1This fails for 106239. – mudkip201 – 2018-03-06T17:34:41.780

1

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.

Unrelated String

Posted 2016-11-14T19:02:08.850

Reputation: 5 300

1

The interaction between 0 and p has been fixed in the latest commit. The 7 bytes d.&^₃dp should now work properly (once the commit is pulled on TIO).

– Fatalize – 2019-03-04T07:59:46.927

1

Pyke, 10 bytes

3^`}SR`}Sq

Try it here!

Blue

Posted 2016-11-14T19:02:08.850

Reputation: 26 661

1

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

mbomb007

Posted 2016-11-14T19:02:08.850

Reputation: 21 944

vz is Q and you can remove the last z – Maltysen – 2016-11-14T22:19:03.000

srry you need a ` instead of the z – Maltysen – 2016-11-14T22:20:50.473

still get 10 tho – Maltysen – 2016-11-14T22:20:56.583

also the tutorial is super out of date, I would recommend using the table at https://pyth.herokuapp.com/ which is always current.

– Maltysen – 2016-11-14T22:28:38.230

to the third power, you can overflow the repr – njzk2 – 2016-11-14T22:41:13.403

@Maltysen I already linked that in my answer. – mbomb007 – 2016-11-14T22:41:42.713

@njzk2 This works differently than Python's. There is still no L, even if the result is a long. Try it yourself with input of 2103869. – mbomb007 – 2016-11-14T22:42:04.887

1

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.

Neil

Posted 2016-11-14T19:02:08.850

Reputation: 95 035

1

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

Mama Fun Roll

Posted 2016-11-14T19:02:08.850

Reputation: 7 234

1

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)

zeppelin

Posted 2016-11-14T19:02:08.850

Reputation: 7 884

1You need to check set equality, not just subset - see Dennis' comment on the main post for the test case 106239. – Sp3000 – 2016-11-15T09:30:56.203

That is true, will fix it now, thanks ! – zeppelin – 2016-11-15T10:07:53.180

n*n*n can be written n**3 – hoosierEE – 2016-11-17T21:53:27.513

2@hoosierEE, no, not in ES6, unfortunately – zeppelin – 2016-11-17T22:12:02.557

1

Scala, 57 chars

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

Amir Asaad

Posted 2016-11-14T19:02:08.850

Reputation: 21

I'm not fluent in Scala, but shouldn't it be possible to remove the whitespace around the various =s? – Mego – 2016-11-15T11:08:10.047

yes I'm new to code golf – Amir Asaad – 2016-11-15T11:13:19.257

1

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

Toby Speight

Posted 2016-11-14T19:02:08.850

Reputation: 5 058

1

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+""));

Flavius

Posted 2016-11-14T19:02:08.850

Reputation: 11

Can you strip the spaces around =? – Oliver Ni – 2016-11-15T17:31:41.670

thanks @Oliver, how do I count the bytes? – Flavius – 2016-11-15T17:32:37.173

I used this site.

– Oliver Ni – 2016-11-15T17:33:10.230

Are you missing an using to generic namespace? – Link Ng – 2016-11-16T05:49:25.777

@LinkNg what exactly are the requirements, I tried to find it on the website but couldn't. – Flavius – 2016-11-16T12:10:46.643

From this meta and the links therein, the program/function should be compilable. In C# you need to add using System.Collections.Generic;, or qualify both HashSet<char> to be System.Collections.Generic.HashSet<char>, or put your program/function in this namespace, or use using alias. TBH I found it challenging to golf in C# while considering namespaces.

– Link Ng – 2016-11-16T15:16:50.430

0

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

Lyndon White

Posted 2016-11-14T19:02:08.850

Reputation: 1 021

big(x) requires few bytes than Int128(x) – Glen O – 2016-11-16T06:21:38.563

thanks, i forgot big was availble as a function (rather than just as a string macro) – Lyndon White – 2016-11-17T00:56:19.977

0

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).

Glen O

Posted 2016-11-14T19:02:08.850

Reputation: 2 548

0

C#

Without any 32 or 64 bit limits...

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

L.B

Posted 2016-11-14T19:02:08.850

Reputation: 101

You can drop the function name and type signature - unnamed lambdas are acceptable. Additionally, you have a lot of whitespace that can be removed. Remember, in code golf, you're trying to make your code as short as possible.

– Mego – 2016-11-16T19:16:05.857

Thanks @Mego, I saw this question at Hot Network Questions But I think I have to read some docs before posting next answer... – L.B – 2016-11-16T19:28:05.310

0

bash, 42

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

izabera

Posted 2016-11-14T19:02:08.850

Reputation: 879

test with 2103869 – Ipor Sircer – 2016-11-17T07:13:51.840

@IporSircer plenty of other answers are limited by the language's limits – izabera – 2016-11-17T07:16:12.643

0

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

corvus_192

Posted 2016-11-14T19:02:08.850

Reputation: 1 889

0

Matlab/Octave, 39 bytes

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

costrom

Posted 2016-11-14T19:02:08.850

Reputation: 478

1== will give an error if the numbers of unique digits are different (maybe use isequal). Also, this would require x to be of type uint64 in order to work across the specified input range; you should indicate it in your answer. You can remove the parentheses around unique. In addition, the general rule is that your code should be a full program or a function (i.e. define the second part as an anonymous function or use input()). – Luis Mendo – 2016-11-18T22:02:30.500

0

Swift 3, 75 bytes

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

Otávio

Posted 2016-11-14T19:02:08.850

Reputation: 161

0

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]]

RosLuP

Posted 2016-11-14T19:02:08.850

Reputation: 3 036

This produces a false positive for 106239 (the Dennis test case). – zeppelin – 2016-12-02T22:29:44.453

@zeppelin ok i wrote a new version... thank you – RosLuP – 2016-12-03T09:21:23.877

0

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.

rafa11111

Posted 2016-11-14T19:02:08.850

Reputation: 310

0

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))

clismique

Posted 2016-11-14T19:02:08.850

Reputation: 6 600

0

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

RosLuP

Posted 2016-11-14T19:02:08.850

Reputation: 3 036

0

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)[%(* % % %)]))

NikoNyrh

Posted 2016-11-14T19:02:08.850

Reputation: 2 361

0

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.

Martin Ender

Posted 2016-11-14T19:02:08.850

Reputation: 184 808

0

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]

caird coinheringaahing

Posted 2016-11-14T19:02:08.850

Reputation: 13 702

0

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

Weijun Zhou

Posted 2016-11-14T19:02:08.850

Reputation: 3 396

0

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))

l4m2

Posted 2016-11-14T19:02:08.850

Reputation: 5 985

0

Pari/GP, 35 bytes

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

Try it online!

alephalpha

Posted 2016-11-14T19:02:08.850

Reputation: 23 988

0

MathGolf, 9 bytes

ⁿαmÉ▒▀s~=

Try it online!

Explanation

ⁿ           pop a : push(a*a*a)
 α          wrap last two elements in array (pops the implicit input again)
  m         explicit map
   É        start block of length 3
    ▒       split to list of chars/digits
     ▀      unique elements of string/list
      s     sort(array)
       ~    dump array onto stack
        =   pop(a, b), push(a==b)

maxb

Posted 2016-11-14T19:02:08.850

Reputation: 5 754

0

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

Maltysen

Posted 2016-11-14T19:02:08.850

Reputation: 25 023

1This fails for input 106239. – Dennis – 2016-11-14T22:41:17.803

0

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));
}

Link Ng

Posted 2016-11-14T19:02:08.850

Reputation: 593

0

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.

user59178

Posted 2016-11-14T19:02:08.850

Reputation: 1 007

It works in PHP 7, yes, not in PHP 5. Also, this throws a notice because count_chars should be in apostrophes or double quotes. https://3v4l.org/UsWn4

– chx – 2016-11-18T06:49:05.920

@chx I know, what I was really surprised about was being able to do it in line. As for the notice, ignoring notices is standard practise in PPCG and learning what strings you can use without the quotes is a decent start for golfing PHP. – user59178 – 2016-11-18T09:17:04.973

45 +1 bytes with -F flag and $argn instead of $argv[1] – Titus – 2019-03-06T03:22:54.820

0

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

Mego

Posted 2016-11-14T19:02:08.850

Reputation: 32 998

0

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 3rd power, converting to an extended 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

Conor O'Brien

Posted 2016-11-14T19:02:08.850

Reputation: 36 228

Holy... this was the best I could do: (]([=(~.@,)&.":)[:x:3^~]) (25 bytes, or 23 if you don't count the parens) – hoosierEE – 2016-11-17T21:50:55.620