Message Boards Message Boards

0
|
6206 Views
|
6 Replies
|
1 Total Likes
View groups...
Share
Share this post:
GROUPS:

Combining nested lists of numbers into single numbers

Posted 9 years ago

My program produces this intermediary result: {{97, 98, 99}, {65, 66, 67}, {90, 89}}

I want to combine these lists of numbers into single numbers, like this: {979899, 656667, 9089}

I've tried every possible combination of Join, Flatten, Level, IntegerDigits, FromDigits etc but I can't find a simple solution using these basic functions.

I would also be interested in a solution for the reverse problem: turning list 2 into list 1.

Can anybody help?

POSTED BY: H FR
6 Replies
Posted 9 years ago

Thank you all very much for your solutions. Very inspiring!

POSTED BY: H FR
Posted 9 years ago

Hi. Just another of many alternatives:

JoinNumbers[v_List] := Fold[#1*10^IntegerLength[#2] + #2  &, 0, v]    
JoinNumbers[{1,23,456,7890,12345}]
123456789012345
Example = {{97,98,99},{65,66,67},{90,89}};
JoinNumbers/@Example
{979899,656667,9089}

I've tried every possible combinations of Join, Flatten, Level, IntegerDigits, FromDigits etc

Another possible solution:

fx[v_List] := FromDigits /@ Flatten /@ Map[IntegerDigits, v]
fx[Example]
{979899,656667,9089}

Note: Fold might be a little faster:

Do[fx[Example],{100000}]//Timing
{2.59130999999999,Null}
Do[JoinNumbers/@Example,{100000}]//Timing
{1.86826099999999,Null}

= = = = =

HTH :>)

POSTED BY: Dana DeLouis
Posted 9 years ago

You can also try-

data = {{97, 98, 99}, {65, 66, 67}, {90, 89}};
FromDigits[#] & /@ (Catenate[#] & /@ IntegerDigits[data])
{979899, 656667, 9089}

For the second part-

list ={979899, 656667, 9089};
newlist =Partition[#, 2] & /@ IntegerDigits[list]
{{{9, 7}, {9, 8}, {9, 9}}, {{6, 5}, {6, 6}, {6, 7}}, {{9, 0}, {8, 9}}}
MapAt[FromDigits[#] &, newlist, {{All, All}}]
{{97, 98, 99}, {65, 66, 67}, {90, 89}}
POSTED BY: Girish Arabale

Take care with Partition there Girish, it concatenates to multiples, so you could risk dropping data from an odd length number. Both FromDigits and IntegerDigits take base specification, making them massively versatile!

FromDigits[#, 100] & /@ {{97, 98, 99}, {05, 66, 67}, {90, 89}}
{979899, 56667, 9089}

IntegerDigits[{979899, 56667, 9089}, 100]
{{97, 98, 99}, {5, 66, 67}, {90, 89}}
POSTED BY: David Gathercole
Posted 9 years ago

Yup.. Overlooked the base specification part. This makes it quite simple. Thanks.

POSTED BY: Girish Arabale

Hi,

not elegant but works:

ToExpression[StringJoin[ToString /@ #]] & /@ {{97, 98, 99}, {65, 66, 67}, {90, 89}}

Cheers, Marco

POSTED BY: Marco Thiel
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract