Message Boards Message Boards

0
|
6701 Views
|
3 Replies
|
7 Total Likes
View groups...
Share
Share this post:

Can we select from a list by position and value?

Posted 9 years ago

Hi everyone

Does anyone know of a way to select by position and value, lets say I have a list of all 6 digit numbers and I want to select all those that have say 3, 5, 6 in position 2, 4, 5, so 138569 would be one of those that meet the criteria. The positions and numbers are stored as lists and can be 1, or 2 or 3 digits or more in length.

So we could have

a=Range[100000,999999];b={2,4,5};c={5,2,1}. 

where list b is the position's and list c are the values. I have solved it but not very efficiently, where I have converted to strings and used stringtake and stringposition within a do loop, the loop being equal to the length of the list {b}. where each iteration is a smaller list etc.

Paul.

POSTED BY: Paul Cleary
3 Replies

One can use IntegerDigits to get the digits separately:

a = Range[100000, 999999];
b = {2, 4, 5};
c = {5, 2, 1};
Select[a, IntegerDigits[#][[b]] === c &]
POSTED BY: Sander Huisman
Posted 9 years ago

You may also work the problem the other way around: build the numbers with this pattern.

FromDigits[{#[[1]], 5, #[[2]], 2, 1, #[[3]]}] & /@ Select[Tuples[Range[0, 9], 3], #[[1]] != 0 &]

This performs a bit faster.


Or, if you want it even faster:

Flatten@Table[FromDigits[{a, 5, b, 2, 1, c}], {a, 1, 9}, {b, 0, 9}, {c, 0, 9}]
POSTED BY: Sandu Ursu
Posted 9 years ago

Thank you both for your replies, both are excellent methods, in the end I adopted Sander's method even though slower it was more generic and adaptable, however I can see where I can utilise the faster method of Sandu's in other applications. Thanks again.

Paul.

POSTED BY: Paul Cleary
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