Page 1 of 1
Puzzle
Posted: Thu Nov 21, 2019 1:05 pm
by cameyo
Write a function f so that
f (f (n)) = -n for every integer n.
Code: Select all
Examples:
(f (f -1)) = 1
(f (f 1)) = -1
(f (f 4)) = -4
(f (f -4)) = 4
(f (f 0)) = 0
I'll post the solution the next week :-)
Re: Puzzle
Posted: Fri Nov 22, 2019 10:21 pm
by fdb
The simplest i could think of is:
But i do not know if macro's are allowed!
Re: Puzzle
Posted: Sat Nov 23, 2019 1:38 pm
by cameyo
Hi fdb, nice solution :-)
However it is possible to solve the puzzle using a "normal" function with any programming language.
Re: Puzzle
Posted: Sun Nov 24, 2019 10:03 am
by ralph.ronnquist
Yes, quite challenging. Especially with the (implied) constraint that
f is restricted to integers, as arguments and values (otherwise it's all too easy). Perhaps the following is acceptable?
Code: Select all
(define (f n)
(if (= n) 0 (> n)
(if (odd? n) (inc n) (- (dec n)))
(if (odd? n) (dec n) (- (inc n)))))
Re: Puzzle
Posted: Sun Nov 24, 2019 10:08 am
by fdb
ah yes to easy when n doesn't need to be a number...
Code: Select all
(define (f n)
(if (number? n)
(list n)
(- (n 0))))
Re: Puzzle
Posted: Sun Nov 24, 2019 2:02 pm
by cameyo
@ralph.ronnquist: you right :-)
@fbd: another good lisp-style solution
Solution:
One method is to separate the sign and magnitude of the number by the parity of the number.
We have three cases:
1) If the number is even, it keeps the same sign and moves 1 closer to 0
(subtract 1 from a positive even number and add 1 to a negative even number).
2) If the number is odd, it changes sign and moves 1 farther from 0
(multiply by -1 and subtract 1 from a positive odd number and multiply by -1 and add 1 to a negative even number)
3) If the number is 0 do nothing (it has no sign)
Code: Select all
(define (f n)
(cond ((and (> n 0) (even? n)) (- n 1))
((and (> n 0) (odd? n)) (- (- n) 1))
((and (< n 0) (even? n)) (+ n 1))
((and (< n 0) (odd? n)) (+ (- n) 1))
(true 0)))
(f (f 1))
;-> -1
(f (f -1))
;-> 1
(f (f 3))
;-> -3
(f (f -3))
;-> 3
(f (f 0))
;-> 0
Thanks fdb and ralph.ronnquist