# Task 1:
# Step 1.1: Creating a Polybius Matrix
# Construct the Polybius square for encryption and decryption
polybius <- matrix(c(" ", "Z", "M", "D", " ", "K", "W", "Q", " ", "G", # Row 0
                     "V", " ", "A", " ", "R", " ", "E", " ", "T", "O", # Row 1
                     " ", "J", "I", "S", "B", "P", "Y", " ", "F", " ", # Row 2
                     "L", " ", " ", "C", " ", "U", "H", "N", " ", "X"), # Row 3
                     nrow = 4, byrow = TRUE)

# Displaying the Polybius matrix
polybius

# Assign row and column identifiers for clarity
rownames(polybius) <- 0:3 
colnames(polybius) <- 0:9

# Display the matrix with labels
polybius

# Task 1:
# Step 2.1: Encrypting the Message
# Define the input message
input_message <- c("CAPTURETHEFORT")
split_message <- substring(input_message,
                           1:nchar(input_message),
                           1:nchar(input_message))

# Display the individual characters of the message
split_message

# Create a placeholder for storing the encoded text
encoded_text <- c()

# Encode the input message using the Polybius matrix
for (character in split_message) { # Loop through each character
  for (row_idx in seq_len(nrow(polybius))) { # Loop through rows
    for (col_idx in seq_len(ncol(polybius))) { # Loop through columns
      if (polybius[row_idx, col_idx] == character) {
        # Concatenate row and column indices as the code
        code_fragment <- paste(row_idx - 1, col_idx - 1, sep = "")
        # Append the encoded fragment to the final output
        encoded_text <- c(encoded_text, code_fragment)
      }
    }
  }
}

# Display the encoded message
encoded_text

# Task 1:
# Step 3.1: Formatting Ciphertext in Groups of 5 Digits
# Define a sample ciphertext for testing
encoded_text <- c("33", "12", "25", "18", "35", "14", "16", "18", "36", "16", "28", "19", "14", "18")

# Combine all codes into a single string for grouping
ciphertext_combined <- paste(encoded_text, collapse = "")

# Create a placeholder for storing grouped ciphertext
final_text <- c()

# Group the ciphertext into blocks of 5 characters
for (start_idx in seq(1, nchar(ciphertext_combined), by = 5)) {
  group <- substring(ciphertext_combined, start_idx, start_idx + 4)
  
  # If the group is less than 5 characters, pad with random digits
  if (nchar(group) < 5) {
    padding <- paste0(sample(0:9, 5 - nchar(group), replace = TRUE), collapse = "")
    group <- paste0(group, padding)
  }
  
  # Append the group to the final text
  final_text <- c(final_text, group)
}

# Display the final grouped ciphertext
final_text
