whew! I just worked out a problem that was vessel-poppingly hard for me. I get the feeling most people completed this problem in 1 to 2 hours, but it took me about 2 days of painful brain-wracking. still, i feel quite triumphant right now!
it's a just a problem of compressing a string of 1's and 0's. For example, evaluating (1 0 1 1 1 0 0) should return (1 0 3 1 2 0). A lone 1 or lone 0 can't be compressed further, so it just returns 1 or 0 again. Three 1's in a row returns a (3 1), two zeros in a row returns a (2 0), so forth.
Below is my code. It didn't take long for me to decide on my strategy: turn the sentence of 1's and 0's into a sentence of words of 1's or 0's, then count the number of letters in each word. Easy, right? But I fell into a deep abyss of buggery (in every sense of that word) in trying to write that first step. Also, I find solving a coding problem to be much like high-stakes game matches: if you doubt yourself, you are on your way to failure. I kept wondering if the approach I outlined would work, if there is a massively better way to code this, so I got more and more frustrated that I couldn't solve this efficiently or think of that perfect approach. then I imploded from panic. This evening I tried again when I was more relaxed.
Anyway, here's the code- it works, but I'm still pretty sure there is indeed a massively more efficient solution. If somebody feels like showing me the light, I'll be forever grateful.
;; Compresses a sentence of 1s and 0s. Example: (compression '(1 0 1 1 1 0 0)) returns (1 0 3 1 2 0).
(define (compression sent)
(if (= 1 (count (final-boppy sent)))
(helper (first (final-boppy sent)))
(se (helper (first (final-boppy sent)))
(compression (bf (final-boppy sent))))))
(define (helper wd)
(if (= 1 (count wd))
wd
(se (count wd) (first wd))))
;; Takes a sentence of 1s and 0s, returns a sentence of words.
;; Example (0 0 1 1 0) becomes (00 11 0).
(define (final-boppy sent)
(other-boppy (se 4 sent)))
(define (other-boppy sent)
(cond ((<= (count sent) 1) ())
((= (first sent) (first (bf sent)))
(other-boppy (bf sent)))
(else (se (boppy (bf sent)) (other-boppy (bf sent))))))
(define (boppy sent)
(cond ((empty? sent) "")
((= 1 (count sent)) (first sent))
((= (first sent) (first (bf sent)))
(word (first sent) (boppy (bf sent))))
(else (word (first sent)))))
I have the bad habit of naming all my helper functions boppy. Crap, not able to indent!
Subscribe to:
Post Comments (Atom)
1 comment:
Hey! I remember this problem! Congrats!
Post a Comment