# [plt-scheme] Code review: garden fence encryption

 From: Neil Van Dyke (neil at neilvandyke.org) Date: Mon Mar 16 09:37:50 EDT 2009 Previous message: [plt-scheme] Code review: garden fence encryption Next message: [plt-scheme] Code review: garden fence encryption Messages sorted by: [date] [thread] [subject] [author]

```Marek Kubica wrote at 03/16/2009 08:32 AM:
>> To do it functionally, remember that building a result is easy in a
>> recursive algorithm if you're cons-ing a list, and also that in
>> Scheme you can *read* characters at arbitrary positions in a string.
>>
>> Also, I don't think you need to build an explicit list of positional
>> numbers.  Think about how those numbers change at each step of the
>> algorithm, and how you can do that in recursive function calls in one
>> pass, at the same time you are building the result.
>>
>
> I wasn't able to figure out how to get the numbers in one pass. I'll
> look into Davids code to find out how he did it.
>

Methodically writing down a table mapping destination index to source
index might help give an intuition for the numbers.

If you figure out a function for the numbers, then something like the
following code should work.  In this example, the function is just
taking every second letter from the source string and wrapping around
when it runs out.

(define (foo source-string)

(let ((source-length (string-length source-string)))

(define (bar destination-remaining x-value)
(if (zero? destination-remaining)
'()
(let ((new-x-value (modulo (+ x-value 2) source-length)))
;; Above we have our function that maps positions in
;; the destination to positions in the source.  It
;; could be a function of "destination-remaining",
;; "x-value", and/or other values.  In this case, at
;; each step of assembling the destination list,
;; "x-value" at this step is a function of "x-value"
;; at the preceding step.  The "x-value" for this
;; step is then passed to the next recursive step.
(cons (string-ref source-string new-x-value)
(bar (- destination-remaining 1)
new-x-value)))))

(list->string (bar source-length -2))))

(foo "abcdefghijklmnopqrstuvwxyz")
;=> "acegikmoqsuwyacegikmoqsuwy"

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20090316/8474ea3c/attachment.html>
```

 Posted on the users mailing list. Previous message: [plt-scheme] Code review: garden fence encryption Next message: [plt-scheme] Code review: garden fence encryption Messages sorted by: [date] [thread] [subject] [author]