| Author |
Comment/Response |
Forum Moderator
email me
 |
09/29/98 1:44pm
> > Given a list of integers, e.g., 110, 124, etc., how can I get Mathematica to extract those integers that do not contain two or more identical digits?
>
> I use V. 3.0.1.1x for Windows 95.
>
> Thanks,
> Pedro
>
========
Here is one approach (I am sure there are many and this may not be the best):
There is a Built-in function called IntegerDigits.
In[1]:= ?IntegerDigits
''IntegerDigits[n] gives a list of the decimal digits in the integer n. \
IntegerDigits[n, b] gives a list of the base-b digits in the integer n. \
IntegerDigits[n, b, len] pads the list on the left with zeros to give a list \
of length len.''
Here it is in action:
In[2]:= IntegerDigits[114]
Out[2]= {1,1,4}
One could then compare each of the digits to all the others. Here is a way to do that using the built in function, Union.
In[3]:= ?Union
''Union[list1, list2, ... ] gives a sorted list of all the distinct elements \
that appear in any of the listi. Union[list] gives a sorted version of a \
list, in which all duplicated elements have been dropped.''
The key point here is that duplicates are dropped.
In[4]:= Union[IntegerDigits[114]]
Out[4]= {1,4}
The resulting List has a length:
In[3]:= Length[Union[IntegerDigits[114]]]
Out[3]= 2
That can be compared to the length of the non-Union-ized digit list:
In[6]:= Length[IntegerDigits[114]] == Length[Union[IntegerDigits[114]]]
Out[6]= False
Another Built-in function, Select, can help us use that comparison:
In[7]:= ?Select
''Select[list, crit] picks out all elements ei of list for which crit[ei] is \
True. Select[list, crit, n] picks out the first n elements for which crit[ei] \
is True.''
Note that crit has a function-like form in the description above. Here is a function that will make the comparision in In[6] for any Integer.
In[8]:= NoDups[x_]:= Length[IntegerDigits[x]] == Length[Union[IntegerDigits[x]]]
This function will return True if there are no duplicate digits, False if there are.
Now here are some numbers in a list:
In[10]:= nums = Table[Random[Integer, {100, 999}], {20}]
Out[10]={607,945,462,428,584,176,316,604,586,401,522,571,978,800,368,300,746,804,394,
687}
Select will can use NoDups to pick out the ones with no duplicate digits.
In[11]:= Select[nums,NoDups]
Out[11]= {607,945,462,428,584,176,316,604,586,401,571,978,368,746,804,394,687}
I suggest that you investigate the functions mentioned in the Help Browser and
look through the on line Mathematica book.
Tom Zeller
Forum Moderator
URL: , |
|