52
\$\begingroup\$

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

\$\endgroup\$
  • 28
    \$\begingroup\$ Proposed test case: 106239 \$\endgroup\$ – Dennis Nov 14 '16 at 22:41
  • 8
    \$\begingroup\$ Test case: 2103869 -> True. This (or a larger one) is necessary to test a language with a long datatype. \$\endgroup\$ – mbomb007 Nov 14 '16 at 22:43
  • 5
    \$\begingroup\$ Too bad the max is too big for language without a 64 bit integer type. \$\endgroup\$ – edc65 Nov 15 '16 at 7:32
  • 17
    \$\begingroup\$ I think you should be explicit about the base... in binary it's kinda half the fun :-D \$\endgroup\$ – The Vee Nov 15 '16 at 13:06
  • 7
    \$\begingroup\$ @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. \$\endgroup\$ – Dennis Nov 17 '16 at 23:28

75 Answers 75

28
\$\begingroup\$

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.

\$\endgroup\$
  • 8
    \$\begingroup\$ In python 2 you can use backtics as a shortcut for repr(), saving 6 bytes. set(`x`) \$\endgroup\$ – DenDenDo Nov 14 '16 at 19:49
  • 9
    \$\begingroup\$ @DenDenDo Any input larger than 2097152 (sys.maxint**(1/3.)) and less than sys.maxint+1 will return False if you use repr(). repl.it/EXs2/1. Longs have an L at the end. \$\endgroup\$ – mbomb007 Nov 14 '16 at 21:03
  • 9
    \$\begingroup\$ Untested, but you can probably do lambda x:{*str(x)}=={*str(x**3)} in Python 3.5+. \$\endgroup\$ – Copper Nov 14 '16 at 22:23
  • 1
    \$\begingroup\$ @BenHoyt It's more concise than using print(...) and input(). Making it a function is shorter than making a full program. \$\endgroup\$ – 0WJYxW9FMN Nov 15 '16 at 19:03
  • 1
    \$\begingroup\$ Because the question says returning a truthy or falsy value is enough, you can replace == by ^. Two equal sets lead to {} which is falsy. \$\endgroup\$ – RemcoGerlich Nov 17 '16 at 8:03
19
\$\begingroup\$

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
\$\endgroup\$
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ – Emigna Nov 16 '16 at 9:06
  • 7
    \$\begingroup\$ Thanks 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 \$\endgroup\$ – Puzomor Croatia Nov 16 '16 at 9:09
14
\$\begingroup\$

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);
}
\$\endgroup\$
  • \$\begingroup\$ The ungolfed code is missing 1 << when setting the bits with k |= 1 << i % 10. Great solution! \$\endgroup\$ – 1Darco1 Nov 15 '16 at 10:54
  • 1
    \$\begingroup\$ I used this bitmap idea to make a 39 byte x86-64 machine code function :) \$\endgroup\$ – Peter Cordes Nov 17 '16 at 0:33
  • \$\begingroup\$ Are we allowed to consider 0 as truthy? I guess strcmp works that way, so it seems reasonable in C. \$\endgroup\$ – Peter Cordes Nov 17 '16 at 0:55
  • 1
    \$\begingroup\$ This 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)... \$\endgroup\$ – Peter Cordes Nov 17 '16 at 0:59
8
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ Nice answer! You can still save a few (3) bytes : perl -pe '$_=$_**3!~/[^$_]/' \$\endgroup\$ – Dada Nov 14 '16 at 22:39
  • \$\begingroup\$ @Zaid Thanx. Fixed. \$\endgroup\$ – Denis Ibaev Nov 15 '16 at 13:00
  • \$\begingroup\$ Now it outputs false for 10 :( \$\endgroup\$ – Zaid Nov 15 '16 at 13:19
  • \$\begingroup\$ @Zaid Yep. -l flag needed. \$\endgroup\$ – Denis Ibaev Nov 15 '16 at 14:11
  • 2
    \$\begingroup\$ Change the && to a * to save a byte \$\endgroup\$ – Gabriel Benamy Nov 15 '16 at 17:38
7
\$\begingroup\$

Mathematica, 34 bytes

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

Direct implementation (unnamed function of one integer argument).

\$\endgroup\$
7
\$\begingroup\$

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.
\$\endgroup\$
6
\$\begingroup\$

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.
\$\endgroup\$
6
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ it's terrible that there isn't a nicer way to compare sets for equivalence \$\endgroup\$ – njzk2 Nov 14 '16 at 22:39
  • 1
    \$\begingroup\$ @njzk2 Well, I'd say the greater tragedy is that == doesn't work even on arrays. \$\endgroup\$ – Conor O'Brien Nov 14 '16 at 22:42
  • \$\begingroup\$ You can save a byte by changing n*n*n to n**3, but I guess that might be ES7 and not ES6. \$\endgroup\$ – Robert Hickman Nov 14 '16 at 23:06
  • 1
    \$\begingroup\$ @Downgoat Thanks, that inspired me to save some more bytes! \$\endgroup\$ – Conor O'Brien Nov 14 '16 at 23:49
  • 3
    \$\begingroup\$ This fails for 2103869, and the problem explicitly requires solutions to work up to 2642245. \$\endgroup\$ – user5090812 Nov 16 '16 at 14:12
6
\$\begingroup\$

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+""));};
\$\endgroup\$
  • \$\begingroup\$ Can you check p<0 instead of p==1? \$\endgroup\$ – TuukkaX Nov 14 '16 at 21:00
  • \$\begingroup\$ @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. \$\endgroup\$ – Yodle Nov 14 '16 at 21:09
  • \$\begingroup\$ 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;}; \$\endgroup\$ – Corak Nov 15 '16 at 11:40
  • \$\begingroup\$ You can replace int.Parse(c+"") with c-'0' \$\endgroup\$ – Dennis_E Nov 15 '16 at 15:53
  • \$\begingroup\$ 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.) \$\endgroup\$ – SaxxonPike Nov 15 '16 at 21:08
6
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ That static Y y thing is a weird initialisation syntax, does it autoassign to y.n because the interface has exactly one member? \$\endgroup\$ – cat Nov 15 '16 at 0:39
  • \$\begingroup\$ 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. \$\endgroup\$ – Hypino Nov 15 '16 at 3:09
  • \$\begingroup\$ 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. \$\endgroup\$ – 1Darco1 Nov 15 '16 at 10:44
  • \$\begingroup\$ 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. \$\endgroup\$ – 1Darco1 Nov 15 '16 at 10:51
  • 1
    \$\begingroup\$ Nevermind, just read the meta post about this and it seems the community agrees. I suppose I can see why. I will update. \$\endgroup\$ – Hypino Nov 16 '16 at 15:56
6
\$\begingroup\$

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)

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – manatwork Nov 15 '16 at 11:45
  • \$\begingroup\$ Yep, you are correct, fixed ! Thank you ! \$\endgroup\$ – zeppelin Nov 15 '16 at 12:30
  • \$\begingroup\$ 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. \$\endgroup\$ – manatwork Nov 15 '16 at 13:00
  • \$\begingroup\$ @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 ! \$\endgroup\$ – zeppelin Nov 15 '16 at 13:16
  • 1
    \$\begingroup\$ @zeppelin: you can use cmp instead of diff and save 1 byte. \$\endgroup\$ – Ipor Sircer Nov 17 '16 at 0:28
6
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Code golf in machine code? That's true mastery! \$\endgroup\$ – chx Nov 18 '16 at 6:50
  • \$\begingroup\$ @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) \$\endgroup\$ – Peter Cordes Nov 18 '16 at 6:58
  • \$\begingroup\$ @chx: but yes, golfing in asm does make me feel like a badass, thanks for noticing :) See my other answers, here and on SO :) \$\endgroup\$ – Peter Cordes Nov 18 '16 at 7:01
  • \$\begingroup\$ 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. \$\endgroup\$ – chx Nov 18 '16 at 7:11
  • \$\begingroup\$ @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. \$\endgroup\$ – Peter Cordes Nov 18 '16 at 7:20
5
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Does Haskell not have set literals, or a function which returns the unique elements from a list? \$\endgroup\$ – cat Nov 15 '16 at 0:27
  • 2
    \$\begingroup\$ @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). \$\endgroup\$ – xnor Nov 15 '16 at 0:32
  • \$\begingroup\$ Why the need to sort...? \$\endgroup\$ – cat Nov 15 '16 at 0:33
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ – xnor Nov 15 '16 at 0:35
  • \$\begingroup\$ Oh, I never realised Haskell doesn't have a primitive unordered collection type, that makes sense \$\endgroup\$ – cat Nov 15 '16 at 0:38
5
\$\begingroup\$

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)

\$\endgroup\$
  • 1
    \$\begingroup\$ You're assuming that the unique digits in n^3 can't be fewer than those in n? \$\endgroup\$ – ngn Nov 18 '16 at 3:31
  • \$\begingroup\$ Can you prove the existence of a counter-example? \$\endgroup\$ – Adám Nov 19 '16 at 20:04
  • 1
    \$\begingroup\$ 106239, see comments at the top \$\endgroup\$ – ngn Nov 19 '16 at 20:19
5
\$\begingroup\$

Clojure, 35 bytes

#(=(set(str %))(set(str(* % % %))))
\$\endgroup\$
5
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ Imports/usings are indeed part of the byte-count. You can remove the static though. \$\endgroup\$ – Kevin Cruijssen Nov 16 '16 at 14:50
  • \$\begingroup\$ Okay thanks. Removed static. \$\endgroup\$ – QBrute Nov 16 '16 at 15:13
4
\$\begingroup\$

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'
\$\endgroup\$
  • \$\begingroup\$ This doesn't work with input 100. \$\endgroup\$ – Dennis Nov 14 '16 at 21:10
  • \$\begingroup\$ I understand why it doesn't, but why doesn't this work? \$\endgroup\$ – DJMcMayhem Nov 14 '16 at 21:12
  • 1
    \$\begingroup\$ Because 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. \$\endgroup\$ – Dennis Nov 14 '16 at 21:14
4
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

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

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to PPCG! The input/output is implicitly specified because of the code-golf. You can see the community-consensus standards here. Your function count should be sufficient. \$\endgroup\$ – AdmBorkBork Nov 15 '16 at 13:42
4
\$\begingroup\$

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
\$\endgroup\$
  • 1
    \$\begingroup\$ Declaring a%b=all(elema)b as a function and then calling with b%a&&a%b should save two bytes. \$\endgroup\$ – Laikoni Nov 14 '16 at 22:32
4
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ You can replace the $_ with just . \$\endgroup\$ – Jo King Mar 6 at 1:51
4
\$\begingroup\$

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;
}
\$\endgroup\$
  • \$\begingroup\$ You need to include #include<set> and using namespace std; in the golfed code and byte count \$\endgroup\$ – cat Nov 15 '16 at 0:28
  • \$\begingroup\$ @cat #include<set> instead of algorithm \$\endgroup\$ – Karl Napf Nov 15 '16 at 0:31
  • \$\begingroup\$ @KarlNapf oh, I thought all the stdlib containers were acessible through algorithm -- shows what I know about C++ :) \$\endgroup\$ – cat Nov 15 '16 at 0:32
  • \$\begingroup\$ It seems to me the variable local to the function "c" is not initialized but used c|=1 ... \$\endgroup\$ – RosLuP Dec 3 '16 at 15:43
4
\$\begingroup\$

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))
\$\endgroup\$
  • \$\begingroup\$ 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 \$\endgroup\$ – Billywob Nov 16 '16 at 15:57
  • \$\begingroup\$ I've never had to use it myself but it seems like the gmp package could solve this problem. \$\endgroup\$ – Billywob Nov 16 '16 at 16:00
  • \$\begingroup\$ Ah, good catch! I've updated the answer, it now uses gmp::as.bigz() to handle large integers. \$\endgroup\$ – rturnbull Nov 16 '16 at 16:12
  • \$\begingroup\$ 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)) \$\endgroup\$ – MickyT Nov 16 '16 at 21:31
  • \$\begingroup\$ @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. \$\endgroup\$ – rturnbull Nov 16 '16 at 23:41
4
\$\begingroup\$

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

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Can't you save a byte here using s$n^3? \$\endgroup\$ – user62131 Nov 16 '16 at 4:22
  • \$\begingroup\$ @ais523: No, because it translates to (s n==s) (n^3) which gives a type error. \$\endgroup\$ – nimi Nov 16 '16 at 8:34
3
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ I like the cat smiley in this :3 \$\endgroup\$ – QBrute Nov 15 '16 at 7:59
3
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – colsw Nov 15 '16 at 15:29
  • \$\begingroup\$ @ConnorLSW There's that indexing trick again. I'm going to need to remember that. \$\endgroup\$ – AdmBorkBork Nov 15 '16 at 17:21
  • \$\begingroup\$ 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. \$\endgroup\$ – colsw Nov 16 '16 at 10:00
  • \$\begingroup\$ 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 ;-) \$\endgroup\$ – Joey Nov 18 '16 at 10:00
3
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ Hello Rado, and Welcome to PPCG! This is a great first answer, +1! \$\endgroup\$ – NoOneIsHere Nov 18 '16 at 16:41
  • \$\begingroup\$ 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()} \$\endgroup\$ – Rado Nov 18 '16 at 16:43
  • 1
    \$\begingroup\$ Anonymous functions are acceptable. And use the ** operator for exponentiation. \$\endgroup\$ – manatwork Nov 18 '16 at 16:45
  • \$\begingroup\$ Thanks @NoOneIsHere! Also, calling the closure for test cases would involve replacing x(107624) with c.call(107624) \$\endgroup\$ – Rado Nov 18 '16 at 16:46
  • \$\begingroup\$ Thank you @manatwork! Using an anonymous closure and ** brings it down to beautiful 35 chars/bytes: {"$it".toSet()=="${it**3}".toSet()} \$\endgroup\$ – Rado Nov 18 '16 at 16:50
2
\$\begingroup\$

Ruby, 48 bytes

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.