Puzzle

Q&A's, tips, howto's
Locked
cameyo
Posts: 183
Joined: Sun Mar 27, 2011 3:07 pm
Location: Italy
Contact:

Puzzle

Post 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 :-)

fdb
Posts: 66
Joined: Sat Nov 09, 2013 8:49 pm

Re: Puzzle

Post by fdb »

The simplest i could think of is:

Code: Select all

(define-macro (f n)
  (- (n 1)))
But i do not know if macro's are allowed!

cameyo
Posts: 183
Joined: Sun Mar 27, 2011 3:07 pm
Location: Italy
Contact:

Re: Puzzle

Post by cameyo »

Hi fdb, nice solution :-)
However it is possible to solve the puzzle using a "normal" function with any programming language.

ralph.ronnquist
Posts: 228
Joined: Mon Jun 02, 2014 1:40 am
Location: Melbourne, Australia

Re: Puzzle

Post 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)))))

fdb
Posts: 66
Joined: Sat Nov 09, 2013 8:49 pm

Re: Puzzle

Post 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))))

cameyo
Posts: 183
Joined: Sun Mar 27, 2011 3:07 pm
Location: Italy
Contact:

Re: Puzzle

Post 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

Locked