Exercise1-2 <---> Exercise1-4

Exercise 1.3.

Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers


Ru: Определите процедуру, которая принимает в качестве аргументов три числа и возвращает сумму квадратов двух больших из них.


Scheme solution:

(define (sum-square-max a b c)
  (define x (if (> a b) a b))
  (define y (if (< a b) a b))
  (define z (if (> y c) y c))
  (+ (* x x) (* z z)))

Alternate Scheme solution:

(define (square x) (* x x))
(define (sum-of-squares x y) (+ (square x) (square y)))
(define (sum-of-square-max x y z)
          (cond
            ((and (< x y) (< x z)) (sum-of-squares y z))
            ((and (< y x) (< y z)) (sum-of-squares x z))
            (else (sum-of-squares x y))))

Haskell solution:

sum'square'max a b c = x*x + z*z
  where
    ((x, y), z) = (if a > b then (a, b) else (b, a), if y > c then y else c)

OCaml solution:

let sum_square_max a b c =
  let x, y = if a > b then a, b else b, a in
  let z = if y > c then y else c in
    x*x + z*z

Oberon/Component Pascal solution:

PROCEDURE SumSquareMax (a, b, c : INTEGER) : INTEGER;
VAR x, y : INTEGER;
BEGIN
  IF a > b THEN x := a; y := b ELSE x := b; y := a END;                                 
  IF y < c THEN y := c END;                                     
  RETURN x*x + y*y
END SumSquareMax;

Exercise1-2 <---> Exercise1-4


Comments

Решение на Схеме какое-то корявое... Может улучшить можно?
Posted by Geniepro at 2007-09-13 18:27:08

Вроде бы списки по идее ещё нельзя использовать :) Они же не были введены, так что можно пока просто cond обойтись, правда ещё корявей будет :)

Posted by IvanVeselov ;) at 2007-09-13 23:39:43

убрал списки

Posted by Geniepro at 2007-09-15 11:22:19

А арифметику нельзя использовать?

foo(x,y,z) = x2 + y2 + z2 - min3(x,y,z)2

где min3(x,y,z) = min(x,min(y,z))

Posted by kodt_rsdn :) at 2007-09-17 15:54:45 X

Можно конечно, но не факт, что такое решение проще :) Но интересно, спасибо.

Posted by IvanVeselov at 2007-09-17 16:39:21

У меня было более твердолобое решение

(define (square x) (* x x)) (define (sum-of-squares a b) (+ (square a) (square b))) (define (sum-of-biggest-squares a b c)

  • (cond ((and (> a c) (> b c)) (sum-of-squares a b))

    • ((and (> a b) (> c b)) (sum-of-squares a c)) (else (sum-of-squares b c))

    ))
Posted by moto at 2007-09-21 15:32:47 X

> У меня было более твердолобое решение а в нем нельзя было обойтись без "and",т.е. (> a b c)? вроде с самого начала написано, что многие функции могут принимать "неограниченное" число аргументов

Posted by alex at 2007-09-24 20:40:45 X

> А арифметику нельзя использовать?

ну если уж использовать арифметику, то опять в лоб:

(max (square a b) (square a c) (square b c))

Posted by alex :) at 2007-09-24 20:45:46 X

Мда, действительно... Я вапще-то и не знаток Scheme, так что и не знал, что неограниченное число параметров не только у +-*, но и у min max > < = и т.д...

Posted by Geniepro :\ at 2007-09-24 22:20:45

>(max (square a b) (square a c) (square b c))

не (square x y), а (sum-of-squares x y), надеюсь все меня поняли :(

Posted by 195 at 2007-09-25 07:48:11 X

> не (square x y), а (sum-of-squares x y), надеюсь все меня поняли

да это-то понятно...

Posted by Geniepro :) at 2007-09-25 10:42:46
(define (square x)
  (* x x))

(define (sum-of-squares x y)
  (+ (square x) (square y)))

(define (max-sum-of-squares a b c)
  (sum-of-squares (if (> a b) a b)
                  (cond
                   ((> c b) c)
                   ((> c a) c)
                   ((> a b) b)
                   (else a))))
Posted by stassats at 2007-09-28 02:27:11 X

А приведенный "Scheme solution:" совсем не схемовский и не в ключе, в котором повествуется все начало sicp.

Posted by stassats at 2007-09-28 02:31:20 X

(define (cal x y z)

  • (define (sqrsum x y)
    • (+ (* x x) (* y y)))

    (if (and (>= x z) (>= y z))

    • (sqrsum x y) (cal y z x)))
Posted by Eric at 2007-10-09 09:00:23 X
(define (square x)
  (* x x))

(define (sum-of-squares x y)
  (+ (square x) (square y)))

(define (min x y) (if (< x y) x y ) )
(define (max x y) (if (> x y) x y ) )

(define (max-sum-of-squares a b c)
  (sum-of-squares(max a b)(max (min a b) c) ) )

Posted by bdb at 2007-12-30 06:32:04

(define (sum-square-max a b c)
  (if (and (>= a c) (>= b c))
    (+ (* a a) (* b b))
    (sum-square-max c a b)))
Posted by Penguino at 2008-03-20 16:05:39

(define (square x) (* x x))

(define (check a b c)

  • (if (and (> a b) (> b c))

    • (+ (square a) (square b))

      (if (and (> c a) (> b a))

      • (+ (square c) (square b)) (+ (square a) (square c)))))
Posted by nobody at 2008-03-30 17:12:43 X

(define (square x) (* x x)) (define (sum-of-two-largest-squares x y z)

  • (if (or (> x y) (> x z))

    • (+ (square x)
      • (if (> y z)

        • (square y) (square z)))
      (+ (square y) (square z))))
Posted by cpe-24-174-25-63 at 2008-08-10 04:20:18 X

I'm trying to do the same problem, but a different way. But I keep getting a bizzare answer. My conditional returns the first value examined instead of second greatest. In this example a = 100, b = 200, c = 1000, and x equals the greatest of all three (that is, 1000) > (cond (= x a) (greater b c)

  • (= x b) (greater a c) (= x c) (greater a b) )

> (define (greater x y)

  • (cond ( (> x y) x)

    • ( (> y x) y) ) )

Posted by cpe-72-177-145-209 at 2008-09-08 04:36:59 X

(define (sum-of-squares x y) (+ (* x x)(* y y)))

(define (largest-num-sum-squares a b c)

  • (cond ((and (> a c)(> b c)) (sum-of-squares a b))

    • ((and (> a b)(> c b)) (sum-of-squares a c))

      • (else (sum-of-squares b c))))
Posted by ip70-185-167-177 at 2009-05-29 23:05:26 X

Інший варіант розв'язку, не надто елегантний:

(define (sum-square-max x y z)

  • (cond ((and (not (< x z)) (not (< y z))) (+ (* x x) (* y y)))

    • ((and (not (< x y)) (not (< z y))) (+ (* x x) (* z z)))

(else (+ (* y y) (* z z))) ))

Posted by 91 at 2009-06-08 22:25:46 X

(define (sum-squares-max a b c)

  • (let
    • ((m (min a b c))) (- (+ (* a a) (* b b) (* c c))
      • (* m m))))
Posted by 72 at 2009-06-17 00:38:44 X
> > У меня было более твердолобое решение
> а в нем нельзя было обойтись без "and",т.е. (> a b c)?
> вроде с самого начала написано, что многие функции могут
> принимать "неограниченное" число аргументов
(> a b c) эквивалентно (and (> a b) (> b c)), а не (and (> a c) (> b c)). И его проблемматично использовать для получения 3х альтернатив. В частности решение:
>(define (check a b c)
>        (if (and (> a b) (> b c))
>            (+ (square a) (square b))
>            (if (and (> c a) (> b a))
>                (+ (square c) (square b))
>                (+ (square a) (square c)))))
(at 2008-03-30 17:12:43)- в котором можно заменить (and (> a b) (> b c)) на (> a b c), не верно работает в случае c<a<b

Posted by anton0xf at 2009-07-17 01:29:42 X

:) :)) :( ;) :\ |) X-( B) Markup

Exercise1-3 (last edited 2008-11-07 03:39:17 by culled)