4
$\begingroup$

Using the following commands (which may be inefficient) I can generate all words of length $j$ on the alphabet $\{0,1\}$:

sd[st_]:=StringDelete[st, " "]

name[j_]:=Map[sd,Map[StringRiffle,Tuples[{0, 1}, j] ]]

Suppose I want to find all words on length 6 which contain as a substring 101, how do I do this? I have tried using StringCases but this seems to only give me strings that start or end with 101. Is there a way to do this?

$\endgroup$
4
$\begingroup$

Two additional methods (both faster than Select[strings, StringContainsQ["101"]]):

strings = Map[StringJoin, Tuples[{"0", "1"}, 6]];

Pick[strings, StringContainsQ["101"] @ strings]
{"000101", "001010", "001011", "001101", "010100", "010101", 
"010110", "010111", "011010", "011011", "011101", "100101", "101000", 
"101001", "101010", "101011", "101100", "101101", "101110", "101111", 
"110100", "110101", "110110", "110111", "111010", "111011", "111101"}

A slower alternative:

Pick[strings, StringMatchQ["*101*"]@strings]

same result

| improve this answer | |
$\endgroup$
3
$\begingroup$

Two different methods:

strings = Map[StringJoin, Tuples[{"0", "1"}, 6]];
Flatten @ StringCases[
  strings,
  StartOfString ~~ ___ ~~ "101" ~~ ___ ~~ EndOfString
]
Select[strings, StringContainsQ["101"]]

The Select variant is slightly faster for large datasets.

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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