Page 1 of 1

Woo hoo!

PostPosted: Wed Oct 14, 2015 9:30 pm
by mrdelurk
Programming n00b, I was solving the book question, "Write a function FIRSTZERO that takes 3 numbers as input and returns a word (one of "first," "second," or "none") indicating where the first zero appears."

So I wrote (defun firstzero (x y z) (if (= x 0) 'first (if (= y 0) 'second (if (= z 0) 'third 'none)))) All done in 92 characters and it works.

Then I went to solutions to check if I got it right. Wow, the author did it with cond instead? (defun firstzero (x) (cond ((zerop (first x)) 'first) ((zerop (second x)) 'second) ((zerop (third x)) 'third) (t 'none))) 121 whopping characters and the numbers must be in list form too!

Did I just outcode the book? I'll be hovering above ground for the rest of the day with little pink trumpeting aureolae circles from happiness. If this was by design to make me feel great, thanks. One is proudest about things one is a n00b at.

(Tomorrow once I'm back on solid ground, feel free to point out how this could be far shorter with a macro. :mrgreen: Macros are still 300 pages away.)

Re: Woo hoo!

PostPosted: Sun Oct 18, 2015 9:34 am
by Goheeca
Not necessarily:
Code: Select all
(defun firstzero (x y z)
  (cond ((= 0 x) 'first)
        ((= 0 y) 'second)
        ((= 0 z) 'third)
        (t 'none)))

a minimal form of the code above:
Code: Select all
(defun firstzero(x y z)(cond((= 0 x)'first)((= 0 y)'second)((= 0 z)'third)(t'none)))

It has 84 characters.

But yeah, your code after minimalization is shorter (for three arguments though):
Code: Select all
(defun firstzero(x y z)(if(= x 0)'first(if(= y 0)'second(if(= z 0)'third'none))))

81 characters.

My solution for unlimited count of arguments:
Code: Select all
(defun z(&rest a)(if #0=(position 0 a)(intern(substitute #\- #\ (format nil"~:@(~:R~)"(1+ #0#))))'none))

106 characters long.

Well, let's do the code golf. :)

Re: Woo hoo!

PostPosted: Sun Oct 25, 2015 11:17 am
by mrdelurk
Thank you for the masterful reply, Goheeca
A week later, I'm still studying some of your solution's elements to grok how it works 8-)