Message Boards Message Boards

3 Replies
7 Total Likes
View groups...
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


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.


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


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

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
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract