2
$\begingroup$

The link Convert string of tuple of numbers to complex number is perhaps a bit too advanced for me to understand, but I wonder if there is some easy way to convert tuples to integers, e.g.

lst = Tuples[{1, 2, 3, 4}, 4];

would become

{ 1111, 1112, 1113, ... }

A most basic (and naive) method is

For[i = 1, i <= Length[lst], i++,
 s = 1000 lst[[i, 1]] + 100 lst[[i, 2]] + 10 lst[[i, 3]] + lst[[i, 4]];
 Print[s]
 ]

but I'm sure there is a much smarter way. TIA.

$\endgroup$
4
  • 7
    $\begingroup$ Something like FromDigits /@ Tuples[{1, 2, 3, 4}, 4]? $\endgroup$ May 31, 2022 at 15:39
  • $\begingroup$ Many thanks. So short and elegant. $\endgroup$
    – mf67
    May 31, 2022 at 15:41
  • 3
    $\begingroup$ Just a note: the choice of base in FromDigits can matter here if this is meant to be a reversible transformation, particularly if your tuples contain numbers bigger than 9 or less than 1. $\endgroup$
    – eyorble
    May 31, 2022 at 16:22
  • 3
    $\begingroup$ Another possibility is: lst . {1000, 100, 10, 1}, which ought to be pretty fast. $\endgroup$
    – Carl Woll
    May 31, 2022 at 18:49

1 Answer 1

4
$\begingroup$

(a) NumberCompose

lst = Tuples[{1, 2, 3, 4}, 4];

NumberCompose[#,{1000, 100, 10, 1}]&/@lst//Short

(* {1111, 1112, 1113, 1114, 1121, 1122, 1123, <<246>>, 4442, 4443, 4444} *)

(According to the documentation, "the basic operation of NumberDecompose is Dot")

(b) Dot

(Contributed by Carl Woll, in a comment)

lst.{1000, 100, 10, 1}//Short

(*{1111, 1112, 1113, 1114, 1121, 1122, 1123, <<246>>, 4442, 4443, 4444}*)

(c) FromDigits

(Contributed by J. M.'s slightly less busy in a comment)

FromDigits/@lst//Short

(* {1111, 1112, 1113, 1114, 1121, 1122, 1123, <<246>>, 4442, 4443, 4444} *)

eyorble has noted (in a comment) that "the choice of base in FromDigits can matter here if this is meant to be a reversible transformation, particularly if your tuples contain numbers bigger than 9 or less than 1"

Community Wiki

I think this question deserves a 'fully-fledged' answer, judging by the highly voted comments: it may benefit future visitors, for example. I have marked this answer "Community Wiki". Feel free to edit.

$\endgroup$

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