Puzzle

Started by cameyo, November 21, 2019, 05:05:41 AM

Previous topic - Next topic

cameyo

Write a function f so that f (f (n)) = -n for every integer n.
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

#1
The simplest i could think of is:

(define-macro (f n)
  (- (n 1)))


But i do not know if macro's are allowed!

cameyo

#2
Hi fdb, nice solution :-)

However it is possible to solve the puzzle using a "normal" function with any programming language.

rrq

#3
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?
(define (f n)
  (if (= n) 0 (> n)
      (if (odd? n) (inc n) (- (dec n)))
      (if (odd? n) (dec n) (- (inc n)))))

fdb

#4
ah yes to easy when n doesn't need to be a number...



(define (f n)
  (if (number? n)
(list n)
(- (n 0))))

cameyo

#5
@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)
(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