Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i find all possible permutations of the first 1-2 letters of each word?

Tags:

r

I have the following data:

inputs <- c("Master", "Bachelor", "School")

I would like to have all possible permutations of the first 1-2 letters of each word.

first_letter <- sapply(inputs, substr, start = 1, stop = 1)
"M" "B"  "S"

second_letter <- sapply(inputs, substr, start = 1, stop = 2)
"Ma"     "Ba"     "Sc" 

Desired output:

All permutations of the first letters in every order, see the columns of variable "all_order" (see section "What i tried"). Also in both variations, so either take the first value of "first_letter" or first value "second_letter" but not both at the same time.

MBaS, MBS, MBSc, MBaSc MaBaS, MaBS, MaBSc, MaBaSc,

SBM, SBaM, SBaMa, SBaM ScBM, ScBaM, ScBaMa, ScBaM

BSM, BSMa, BScM, BScMa BaSM, BaSMa, BaScM, BaScMa,

.....

(Let me know if it is explained well enough.)

What i tried:

combs <- combn(rep(seq(inputs), 2), 3)
keep <- !colSums(apply(combs, 2, duplicated))
all_order <- combs[, keep]

all_order
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    1    1    1    2    2    3    1
[2,]    2    2    3    2    3    1    1    2
[3,]    3    3    2    3    1    3    2    3
like image 218
Tlatwork Avatar asked Dec 30 '21 20:12

Tlatwork


1 Answers

Maybe we can try the code below

d <- do.call(
  rbind,
  combn(
    c(first_letter, second_letter),
    3,
    pracma::perms,
    simplify = FALSE
  )
)

res <- do.call(
  paste0,
  data.frame(d)
)[apply(
  `dim<-`(match(substr(d, 1, 1), first_letter), dim(d)),
  1, 
  function(x) all(!duplicated(x))
)]

which gives

> res
 [1] "SBM"    "SMB"    "BSM"    "BMS"    "MBS"    "MSB"    "ScBM"   "ScMB"  
 [9] "BScM"   "BMSc"   "MBSc"   "MScB"   "BaSM"   "BaMS"   "SBaM"   "SMBa"
[17] "MSBa"   "MBaS"   "ScBaM"  "ScMBa"  "BaScM"  "BaMSc"  "MBaSc"  "MScBa"
[25] "MaSB"   "MaBS"   "SMaB"   "SBMa"   "BSMa"   "BMaS"   "ScMaB"  "ScBMa"
[33] "MaScB"  "MaBSc"  "BMaSc"  "BScMa"  "BaMaS"  "BaSMa"  "MaBaS"  "MaSBa"
[41] "SMaBa"  "SBaMa"  "ScBaMa" "ScMaBa" "BaScMa" "BaMaSc" "MaBaSc" "MaScBa"
like image 61
ThomasIsCoding Avatar answered Sep 29 '22 16:09

ThomasIsCoding