-1

1.I want to generate combinations of characters from a given word with each letter being repeated consecutively utmost 2 times and at least 1.The resultant words are of unequal lengths. For example from

"cat"

to

"cat", "catt", "caat", "caatt", "ccat",  "ccatt", "ccaat", "ccaatt"

Required function takes a word of length n and generates 2^n words of unequal length. It is almost similar to binary digits with n length gives 2^n combinations. For example a 3 digit binary number gives

000 001 010 011 100 101 110 111 

combinations, where 0=t and 1=tt.

2.And also the same function should restrict the resultant sequence maximum upto 2 consecutive repetition of a character even if the given word has repetitions of letters.For example

"catt"

to

"catt"   "ccatt"  "caatt"  "ccaatt"

I tried something like this

pos=expand.grid(l1=c(1,11),l2=c(2,22),l3=c(3,33))
result=chartr('123','cat',paste0(pos[,1],pos[,2],pos[,3]))

#[1] "cat"    "ccat"   "caat"   "ccaat"  "catt"   "ccatt"  "caatt"  "ccaatt" 

It gives correct sequence but I am stuck with generalizing it to any given word with different lengths.

Thank you.

M L
  • 106
  • 6

2 Answers2

1

Use stdout as per normal...

print("Hello, world!")

x="cat"
l=seq(nchar(x))
n=paste(l,collapse="")
m=split(c(l,paste0(l,l)),rep(l,2)) 
chartr(n,x,do.call(paste0,expand.grid(m)))
Onyambu
  • 67,392
  • 3
  • 24
  • 53
  • Thank you very much @Onyambu. It is working fine with the input words which doesn't have repetitions. But when the input words are repeating, the resultant sequence is exceeding beyond 2 repetitions. For example `"caa"` gives `#[1] "caa" "ccaa" "caaa" "ccaaa" "caaa" "ccaaa" "caaaa" "ccaaaa" ` I think I can solve 2nd part. I will edit my question and post the answer as well. Thank you – M L Mar 09 '18 at 04:07
0

1.Just an addition to the answer given by Onyambu to solve the second part of the question i.e. restrict the output to maximum 2 consecutive repetitions of a character given any number of consecutive repetitions of characters in the input word.

x="catt"
l=seq(nchar(x))
n=paste(l,collapse="")
m=split(c(l,paste0(l,l)),rep(l,2))
o <- chartr(n,x,do.call(paste0,expand.grid(m)))

Below line of code removes the words with more than 2 consecutive repetitive characters

unique(gsub('([[:alpha:]])\\1{2,}', '\\1\\1', o))
#[1] "catt"   "ccatt"  "caatt"  "ccaatt"

2.If you want all the combinations starting from "cat" to "ccaattt" given any number of consecutive repetitions of characters in the input word. Code is

x1="catt"

Below line of code restricts the consecutive repetition of characters to 1.

x2= gsub('([[:alpha:]])\\1+', '\\1', x1)
l=seq(nchar(x2))
n=paste(l,collapse="")
m=split(c(l,paste0(l,l)),rep(l,2))
o <- chartr(n,x,do.call(paste0,expand.grid(m)))
unique(gsub('([[:alpha:]])\\1{2,}', '\\1\\1', o))
#[1] "cat"    "ccat"   "caat"   "ccaat"  "catt"   "ccatt"  "caatt"  "ccaatt"
M L
  • 106
  • 6