From e51446df9f9e88533694613c1f4c233571d7f176 Mon Sep 17 00:00:00 2001 From: eneller Date: Mon, 23 Mar 2026 21:22:38 +0100 Subject: [PATCH] feat: cdma --- cdma.Rmd | 30 +++++++++++++++++++++++------- input.txt | 8 ++++---- 2 files changed, 27 insertions(+), 11 deletions(-) diff --git a/cdma.Rmd b/cdma.Rmd index 6b99a9a..59e36da 100644 --- a/cdma.Rmd +++ b/cdma.Rmd @@ -27,12 +27,21 @@ ASCII characters require 7 bits of information per character. ```{r input} lines <- readLines('./input.txt',encoding = 'ASCII') strToBin <- function(s){ - # FIXME for strings longer than 1 r <- as.integer(intToBits(utf8ToInt(s))) r <- r[1:7] return(r) } -lines_bin <- do.call(rbind, lapply(lines, strToBin)) + +lines_bin <- list() +for (line in lines){ + line_bin <- list() + for (char in strsplit(line, "")[[1]]){ + s <- strToBin(char) + line_bin <- append(line_bin, s) + } + lines_bin <- append(lines_bin, list(line_bin)) +} +lines_bin <- do.call(rbind,lines_bin) ``` ```{r input-demo, echo=FALSE} @@ -63,7 +72,7 @@ for (j in 1:ncol(lines_bin)){ col <- lines_bin[,j] output_symbol <- 0 for (i in 1:length(col)){ - symbol <- col[i] # the symbol to be encoded + symbol <- col[[i]] # the symbol to be encoded code <- orthogonals[i,] # the code vector single_symbol <- (-1)^(1+symbol) * code # the resulting encoded vector @@ -97,19 +106,26 @@ decoded_m == lines_bin Then we apply our text encoding on each line separately, respecting the LSB/MSB order. ```{r text-decode} chunk <- function(x, chunk_size) { - split(x, cut(seq_along(x), breaks = + chunks <- split(x, cut(seq_along(x), breaks = seq(0, length(x), by = chunk_size), include.lowest = TRUE)) + lapply(chunks, as.list) } +final <- c('','','','') for (i in 1:nrow(decoded_m)){ line <- decoded_m[i,] symbols <- chunk(line, 7) - for (symbol in symbols){ - binary_str <- paste(rev(symbol), collapse = "") + for (j in 1:length(symbols)){ + binary_str <- paste(rev(symbols[[j]]), collapse = "") # Convert the binary string to a decimal value decimal <- strtoi(binary_str, base = 2) # Convert the decimal value to an ASCII character char <- intToUtf8(decimal) - print(char) + final[i] <- paste0(final[i], char) } } + +``` + +```{r text-decode-demo, echo=FALSE} +print(final) ``` \ No newline at end of file diff --git a/input.txt b/input.txt index d68dd40..d2eaf61 100644 --- a/input.txt +++ b/input.txt @@ -1,4 +1,4 @@ -a -b -c -d +da +cb +bc +ad