Jumbling words

Here’s a function (written in R) to jumble a sentence by rearranging letters other than the first and last of each word. The idea comes from a birthday card I received from my aunt in Australia.

# A function to jumble a vector with no chance of
# returning the original vector
vector_jumble <- function(vector) {
    # Create an initial sample
    jumble <- sample(vector)
    # Keep going until the jumbled vector differs from the original
    while(identical(vector,jumble)) {
        jumble <- sample(vector)

# A function to jumble a word
word_jumble <- function(word) {
    # Split word into individuanl letters
    j <- unlist(strsplit(word,""))
    # If there are only three or fewer letters (i.e., only one middle letter), 
    # there is nothing to do. Otherwise, jumble the middle letters.
    if (length(j) < 4) {
    } else {
        first <- 1
        middle <- 2:(length(j)-1)
        last <- length(j)
        return(paste(j[c(first, vector_jumble(middle), last)], collapse=""))    

# A function to jumble a sentence
sentence_jumble <- function(sentence) {
    # Initialize a variable that will store the jumbled sentence
    y <- NULL
    # Break the sentence into words (separated by spaces)
    x <- unlist(strsplit(sentence, " "))
    # Jumble each word in the sentence
    for (i in x) {
        y <- paste(y,word_jumble(i))
    # Return the result, after deleting leading spaces
    return(gsub("^[ ]+","",y, perl=TRUE))
# A test sentence
a <- "The quick brown fox jumps over the lazy dog"

Some sample output

> sentence_jumble(a)
[1] "The qicuk bworn fox jpmus oevr the lzay dog"

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s