Home > Enterprise >  Unique string combinations of consecutive integers
Unique string combinations of consecutive integers

Time:07-01

I have a vector of integers from 0-9 and need all unique possible combinations of these consecutive vector elements, including the original elements.

> vec <- 0:9
> vec
 [1] 0 1 2 3 4 5 6 7 8 9

The task is similar to this question. The major (and tricky) difference is that I only need consecutive combinations (e.g "0", "01", "012", ... "0123456789", ... "1", ... "123456789") and not non-consecutive combinations (such as "013").

How would I go about creating this subset of combinations?

CodePudding user response:

Here is a nested sapply approach

unlist(
  sapply(
    seq_along(vec),
    function(k) {
      sapply(
        k:length(vec),
        function(l) paste0(vec[k:l], collapse = "")
      )
    }
  )
)

which produces

 [1] "0"          "01"         "012"        "0123"       "01234"     
 [6] "012345"     "0123456"    "01234567"   "012345678"  "0123456789"
[11] "1"          "12"         "123"        "1234"       "12345"
[16] "123456"     "1234567"    "12345678"   "123456789"  "2"
[21] "23"         "234"        "2345"       "23456"      "234567"
[26] "2345678"    "23456789"   "3"          "34"         "345"
[31] "3456"       "34567"      "345678"     "3456789"    "4"
[36] "45"         "456"        "4567"       "45678"      "456789"
[41] "5"          "56"         "567"        "5678"       "56789"
[46] "6"          "67"         "678"        "6789"       "7"
[51] "78"         "789"        "8"          "89"         "9"

Another option is sapply embed

unlist(
  sapply(
    seq_along(vec),
    function(k) {
      do.call(paste0, rev(data.frame(embed(vec, k))))
    }
  )
)

which gives

 [1] "0"          "1"          "2"          "3"          "4"
 [6] "5"          "6"          "7"          "8"          "9"
[11] "01"         "12"         "23"         "34"         "45"
[16] "56"         "67"         "78"         "89"         "012"
[21] "123"        "234"        "345"        "456"        "567"
[26] "678"        "789"        "0123"       "1234"       "2345"
[31] "3456"       "4567"       "5678"       "6789"       "01234"
[36] "12345"      "23456"      "34567"      "45678"      "56789"
[41] "012345"     "123456"     "234567"     "345678"     "456789"
[46] "0123456"    "1234567"    "2345678"    "3456789"    "01234567"
[51] "12345678"   "23456789"   "012345678"  "123456789"  "0123456789"
  • Related