Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All possible sequences of given sets of characters

I have the following string:

'[ABC][abcd][XYZ]'

I want to generate all possible strings where the first character is A, B, or C, the second character is a, b, c, or d, and the third character is X, Y, or Z.

Example: AcX, BaZ, etc.

How to do this, preferably within Tidyverse?

like image 209
Ian Avatar asked Sep 01 '25 10:09

Ian


2 Answers

First splitstr the string appropriately to get a list, then using expand.grid and paste0 with do.call .

el(strsplit('[ABC][abcd][XYZ]', '[\\[|\\]]', perl=TRUE)) |>
  {\(x) x[x != '']}() |>
  sapply(strsplit, '') |>
  do.call(what=expand.grid) |>
  do.call(what=paste0)
# [1] "AaX" "BaX" "CaX" "AbX" "BbX" "CbX" "AcX" "BcX" "CcX" "AdX" "BdX" "CdX" "AaY" "BaY" "CaY" "AbY" "BbY" "CbY" "AcY" "BcY"
# [21] "CcY" "AdY" "BdY" "CdY" "AaZ" "BaZ" "CaZ" "AbZ" "BbZ" "CbZ" "AcZ" "BcZ" "CcZ" "AdZ" "BdZ" "CdZ"
like image 85
jay.sf Avatar answered Sep 04 '25 00:09

jay.sf


A stringr solution:

library(stringr)
str_extract_all(x,"(?<=\\[).+?(?=\\])", simplify = TRUE) |>
  str_split("") |>
  expand.grid() |>
  do.call(what = paste0)

# [1] "AaX" "BaX" "CaX" "AbX" "BbX" "CbX" "AcX" "BcX" "CcX" "AdX" "BdX" "CdX" "AaY" "BaY" "CaY" "AbY" "BbY" "CbY" "AcY" "BcY"
#[21] "CcY" "AdY" "BdY" "CdY" "AaZ" "BaZ" "CaZ" "AbZ" "BbZ" "CbZ" "AcZ" "BcZ" "CcZ" "AdZ" "BdZ" "CdZ"

This also works, using interaction:

library(stringr)
str_extract_all(x,"(?<=\\[).+?(?=\\])", simplify = TRUE) |>
  str_split("") |>
  interaction(sep = "") |> levels()

# [1] "AaX" "BaX" "CaX" "AbX" "BbX" "CbX" "AcX" "BcX" "CcX" "AdX" "BdX" "CdX" "AaY" "BaY" "CaY" "AbY" "BbY" "CbY" "AcY" "BcY"
#[21] "CcY" "AdY" "BdY" "CdY" "AaZ" "BaZ" "CaZ" "AbZ" "BbZ" "CbZ" "AcZ" "BcZ" "CcZ" "AdZ" "BdZ" "CdZ"
like image 39
Maël Avatar answered Sep 03 '25 23:09

Maël