| Bytes | Lang | Time | Link |
|---|---|---|---|
| 046 | Python 3.8 | 240924T064014Z | The Empt |
| 060 | Nim | 240924T035232Z | Archar G |
| 011 | Uiua | 240923T233112Z | nyxbird |
| 002 | Thunno 2 | 230726T125237Z | The Thon |
| 1310 | Pushy | 161117T184545Z | FlipTack |
| 003 | Vyxal | 210510T044828Z | lyxal |
| 032 | Factor | 210510T040402Z | chunes |
| 006 | GolfScript | 201027T220205Z | 2014MELO |
| 007 | MathGolf | 190307T100759Z | maxb |
| 004 | Japt ! | 201006T164258Z | Shaggy |
| 009 | Husk | 201006T123532Z | Razetime |
| 035 | Pari/GP | 190306T033828Z | alephalp |
| 007 | Brachylog | 190301T224429Z | Unrelate |
| 048 | JavaScript ES7 | 180305T040053Z | l4m2 |
| 008 | Pyt | 180304T213653Z | qqq |
| 009 | Stax | 180304T210604Z | Weijun Z |
| 012 | Add++ | 180304T202035Z | caird co |
| 015 | Alice | 171211T152531Z | Martin E |
| 029 | APL NARS | 171211T114804Z | user5898 |
| 035 | Clojure | 171211T132927Z | NikoNyrh |
| 031 | Mathematica 31 Bytes | 161230T201103Z | Kelly Lo |
| 076 | Axiom | 161202T213923Z | user5898 |
| 109 | Clojure | 161203T043604Z | clismiqu |
| 088 | Python | 161203T025453Z | rafa1111 |
| 072 | PowerShell 3+ | 161118T095836Z | Joey |
| 075 | Swift 3 | 161118T174347Z | Otá |
| 032 | Python 3 | 161114T190722Z | 0WJYxW9F |
| 035 | Groovy | 161118T163719Z | Rado |
| 093 | C++14 | 161115T005626Z | Karl Nap |
| 069 | dc | 161115T164831Z | Toby Spe |
| 040 | x8664 machine code function | 161117T003132Z | Peter Co |
| 039 | Matlab/Octave | 161117T214832Z | costrom |
| 034 | Scala | 161117T182153Z | corvus_1 |
| 033 | Python 2 | 161117T115053Z | Farhan.K |
| 061 | Python 3 | 161117T120635Z | AvahW |
| nan | MKSH BASH | 161116T040914Z | Ipor Sir |
| 042 | bash | 161117T050129Z | izabera |
| 010 | Actually | 161117T024834Z | Sherlock |
| 040 | Julia | 161116T024448Z | Frames C |
| 070 | R | 161116T152531Z | rturnbul |
| nan | 161116T185258Z | L.B | |
| 059 | BASH | 161115T112058Z | zeppelin |
| 154 | Java 8 | 161114T204551Z | Hypino |
| 178 | Java 7 | 161115T075825Z | QBrute |
| 006 | Convex | 161116T143242Z | GamrCorp |
| 006 | 05AB1E | 161114T190630Z | Emigna |
| 034 | Julia | 161116T062603Z | Glen O |
| 115 | C#6 | 161115T010555Z | Link Ng |
| 015 | CJam | 161116T035010Z | kungfush |
| 086 | C# | 161115T215127Z | A.Konzel |
| nan | C# | 161114T203404Z | Yodle |
| nan | Perl | 161114T194245Z | Denis Ib |
| 087 | C# | 161115T173050Z | Flavius |
| 082 | C++ | 161114T212643Z | Alecto |
| 093 | PowerShell v2+ | 161114T195244Z | AdmBorkB |
| 022 | Perl 6 | 161115T170809Z | Brad Gil |
| 073 | C | 161115T004024Z | Karl Nap |
| 018 | J | 161115T121256Z | Conor O& |
| 051 | JavaScript ES6 | 161114T194502Z | Conor O& |
| 044 | JavaScript ES6 | 161115T114954Z | Neil |
| 057 | Scala | 161115T103054Z | Amir Asa |
| 058 | ES6 Javascript | 161115T091537Z | zeppelin |
| 012 | Actually | 161115T100429Z | user4594 |
| 048 | PHP | 161115T094923Z | user5917 |
| 011 | Brachylog | 161115T073308Z | Fatalize |
| 052 | Haskell | 161114T193807Z | Angs |
| nan | Kotlin 46/88/96 bytes | 161115T040930Z | F. Georg |
| 033 | DASH | 161115T034652Z | Mama Fun |
| 008 | Jelly | 161115T004853Z | Dennis |
| 047 | Haskell | 161115T032749Z | nimi |
| 035 | Clojure | 161115T021452Z | MattPutn |
| 010 | Pyth | 161115T015010Z | Steven H |
| 202 | Batch | 161115T014212Z | Neil |
| 010 | Dyalog APL | 161115T003208Z | Adá |
| 037 | Factor | 161114T230429Z | cat |
| 009 | Pyth | 161114T222620Z | Maltysen |
| 055 | Lua | 161114T224256Z | Trebuche |
| 010 | Pyth | 161114T205115Z | mbomb007 |
| 047 | Haskell | 161114T215608Z | xnor |
| 008 | Jelly | 161114T194813Z | DJMcMayh |
| 010 | Pyke | 161114T201224Z | Blue |
| 008 | CJam | 161114T195253Z | Martin E |
| 034 | Mathematica | 161114T194154Z | Greg Mar |
| 048 | Ruby | 161114T194004Z | Lee W |
Python 3.8, 46 bytes
lambda x:(a:={*f"{x}"})==a.union({*f"{x**3}"})
Anonymous function that checks if the set of digits of \$n\$ is equal to its union with the set of digits of \$n^3\$.
Nim, 60 bytes
import std/setutils,sugar
(n:int)=>toSet($n)==toSet $(n*n*n)
It's an anonymous function that can be called like this:
((n:int)=>toSet($n)==toSet $(n*n*n))(100)
Very basic solution. Notes:
std/prefix is required for some newer standard libraries- lambdas are part of
sugarlibrary - Nim parses
$(toString operator) as infix operator when it's touching an identifier on the left, so we have to use an extra space or parenthesis.
Uiua, 11 bytes
≍∩(⍆◴°⋕)ⁿ3.
≍∩(⍆◴°⋕)ⁿ3.
∩( )ⁿ3. # for both n and n^3,
°⋕ # stringify,
◴ # deduplicate,
⍆ # and sort.
≍ # do they match?
Thunno 2, 2 bytes
³ḍ
Output with inverted booleans - add the ! flag to take the logical NOT of the result.
Explanation
# Implicit input
³ # Cube it
ḍ # Symmetric set difference
# Implicit output
Pushy, 13 10 bytes
V3esuFsux#
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)
Vyxal, 3 bytes
3e⊍
An empty set is truthy and a set with items is falsey. If that ain't an acceptable format for output:
4 bytes
3e⊍¬
Explained
3e⊍
3e # input ^ 3
⊍ # symmetric set difference between the above and input
# ¬ will negate that result, making it either `0` or `1`
Factor, 32 bytes
[ dup 3 ^ [ present ] bi@ set= ]
dupMake a copy of the input.Stack (e.g.):
100 1003 ^Cube.Stack:
100 1000000[ present ] bi@Convert them both to strings.Stack:
"100" "1000000"set=Are they equal when viewed as sets?Stack:
t
GolfScript, 6 bytes
.~3?^!
. # Copy the input "102343" "102343"
~ # Parse it to an integer "102343" 102343
3? # Cube it "102343" 1071949756947607
^ # Get the different digits "237956"
! # Is it an empty string? 0
MathGolf, 9 7 bytes
ⁿαÉ▒▀z=
-2 bytes thanks to KevinCruijssen. By changing the map to a for loop, we save one byte from not having to do a map (m), and another byte from not having to dump the array onto the stack (~).
Explanation
ⁿ pop a : push(a*a*a)
α wrap last two elements in array
É start block of length 3
▒ split to list of chars/digits
▀ unique elements of string/list
z reverse sort(array)
= pop(a, b), push(a==b)
Japt -!, 4 bytes
³skU
³skU :Implicit input of integer U
³ :Cubed
s :Convert to string
kU :Remove all digits that appear in U
:Convert to integer, resulting in NaN if all digits were removed
:Implicit output of negation of result
Brachylog, 9 7 bytes
d.&^₃dp
-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.
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))
Pyt, 8 bytes
Đ³ąỤ⇹ąỤ\
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
Stax, 9 bytes
à±▒!⌂▼▒RÜ
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
Add++, 12 bytes
L,d3^BD€q=
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]
Alice, 15 bytes
/D.n~@
\iXDo/3E
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.
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
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)[%(* % % %)]))
Mathematica 31 Bytes
(f=Sign@*DigitCount)@#==f[#^3]&
because Sign<Union and DigitCount<IntegerDigits
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]]
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))
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.
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.
Swift 3, 75 bytes
func a(n:UInt64){print(Set("\(n)".characters)==Set("\(n*n*n)".characters))}
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.
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!
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).
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
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.
Matlab/Octave, 39 bytes
a=@(x)(unique(num2str(x)));min(a(x)==a(x^3))
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
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'.
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)]==[]
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. )
bash, 42
[[ $1 = +([$((a=$1**3))])&&$a = +([$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.
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
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))
C#
Without any 32 or 64 bit limits...
Func<BigInteger,bool> x = n => !(n * n * n + "").Except(n + "").Any();
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)
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).
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.)
05AB1E, 6 bytes
05AB1E uses CP-1252 encoding.
3mê¹êQ
Explanation
3m # input^3
ê # sorted with duplicates removed
Q # is equal to
¹ê # input sorted with duplicates removed
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).
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));
}
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
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);
}
}
}
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+""));};
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.
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+""));
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;
}
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
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.
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);
}
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
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.
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.
Scala, 57 chars
def n(x:BigInt)=x.toString.toSet==(x*x*x).toString.toSet
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)
Actually, 12 bytes
3ßⁿk`$╔S`Mi=
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
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.
Brachylog, 11 bytes
doI,?:3^doI
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
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
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())}
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
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.
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.
Clojure, 35 bytes
#(=(set(str %))(set(str(* % % %))))
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?)
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.
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?
Note: For large numbers, set ⎕PP←34 ⋄ ⎕FR←1287 (34 significant digits, 128 bit floats)
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
Pyth - 9 bytes
Hopefully can take another char off.
@I.{`^Q3`
! Negation, tells if set is empty
- Setwise subtraction
`^Q3 String repr of input^3
` String repr of implicit input
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.."]"))
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.{`
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
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.
Jelly, 8 bytes
*3ṢQ⁼ṢQ$
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'
CJam, 8 bytes
l_~3#s^!
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.
Mathematica, 34 bytes
f=Union@*IntegerDigits;f@#==f[#^3]&
Direct implementation (unnamed function of one integer argument).
Ruby, 48 bytes
->n{(f=->x{x.to_s.chars.uniq.sort})[n]==f[n**3]}