2

Is there a quick and dirty way to generate a list of numbers from 1 to some arbitrary large number in order such that the digits of each number are only 0's, 1's, and 2's?

I tried doing

n = {0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2};
v = 
  Sort @ Rest @
    DeleteDuplicates[
      FromDigits /@ (Cases[
         Permutations /@ 
           Rest @ DeleteDuplicates @
             Subsets[n], {x__?(Head[#] =!= List &)} :> {x}, -1])];

but it slows down pretty fast, so I don't think I can add any more entries to n.

(Also, still not sure how to copy-paste Mathematica code in here so it looks exactly like it does in Mathematica)

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
Raksha
  • 633
  • 1
  • 6
  • 19

2 Answers2

7

A possibly more general function to be aware of is Tuples:

FromDigits /@ Tuples[{0, 1, 2}, 4]

{0, 1, 2, 10, 11, 12, 20, 21, 22, 100, 101, 102, 110, 111, 112, 120, 121, 122, 200, 201, 202, 210, 211, 212, 220, 221, 222, 1000, 1001, 1002, 1010, 1011, 1012, 1020, 1021, 1022, 1100, 1101, 1102, 1110, 1111, 1112, 1120, 1121, 1122, 1200, 1201, 1202, 1210, 1211, 1212, 1220, 1221, 1222, 2000, 2001, 2002, 2010, 2011, 2012, 2020, 2021, 2022, 2100, 2101, 2102, 2110, 2111, 2112, 2120, 2121, 2122, 2200, 2201, 2202, 2210, 2211, 2212, 2220, 2221, 2222}

This is a bit faster than using IntegerDigits:

FromDigits /@ Tuples[{0, 1, 2}, 12]              // Length // Timing
FromDigits /@ IntegerDigits[Range[0, 531440], 3] // Length // Timing
{0.312002, 531441}

{0.530403, 531441}

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
  • ouch ... "FromDigits /@ Tuples[{0, 1, 2}, 12] " just definitely froze my laptop .... had to force restart again for the billionth time :( for some reason MemoryConstrained[ , (1524^3)] does nothing :( – Raksha Mar 21 '15 at 03:00
  • @Solarmew That's strange. What version of Mathematica are you running? For me the MaxMemoryUsed[] after this command is 98783656 which should be within the limits of almost any device today. – Mr.Wizard Mar 21 '15 at 03:49
4

I think you'll find this faster than either of the above:

f=FromDigits@Transpose@IntegerDigits[Range[0, #], 3, IntegerLength[#, 3]] &;

Use e.g.: f@12345 is equalvlent to FromDigits /@ IntegerDigits[Range[0, 12345], 3] above.

Even faster:

FromDigits@Transpose@PadLeft@Tuples[{0, 1, 2}, 11];
ciao
  • 25,774
  • 2
  • 58
  • 139
  • clever! +1 ---- – Mr.Wizard Mar 21 '15 at 07:38
  • @Mr.Wizard well thank you sir! Not sure of clever, I do find it a strange omission from the docs seeing as it's a useful form that's much faster than mapping... I use it often with bitmaps. – ciao Mar 21 '15 at 08:36