How to resolve the algorithm Sum and product puzzle step by step in the Racket programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sum and product puzzle step by step in the Racket programming language
Table of Contents
Problem Statement
Solve the "Impossible Puzzle": It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y. So for your convenience, here's a break-down: Terminology:
Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains! See the Python example for an implementation that uses this approach with a few optimizations.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Sum and product puzzle step by step in the Racket programming language
Source code in the racket programming language
#lang racket
(define-syntax-rule (define/mem (name args ...) body ...)
(begin
(define cache (make-hash))
(define (name args ...)
(hash-ref! cache (list args ...) (lambda () body ...)))))
(define (sum p) (+ (first p) (second p)))
(define (mul p) (* (first p) (second p)))
(define (sum= p s) (filter (lambda (q) (= p (sum q))) s))
(define (mul= p s) (filter (lambda (q) (= p (mul q))) s))
(define (puzzle tot)
(printf "Max Sum: ~a\n" tot)
(define s1 (for*/list ([x (in-range 2 (add1 tot))]
[y (in-range (add1 x) (- (add1 tot) x))])
(list x y)))
(printf "Possible pairs: ~a\n" (length s1))
(define/mem (sumEq/all p) (sum= p s1))
(define/mem (mulEq/all p) (mul= p s1))
(define s2 (filter (lambda (p) (andmap (lambda (q)
(not (= (length (mulEq/all (mul q))) 1)))
(sumEq/all (sum p))))
s1))
(printf "Initial pairs for S: ~a\n" (length s2))
(define s3 (filter (lambda (p) (= (length (mul= (mul p) s2)) 1))
s2))
(displayln (length s3))
(printf "Pairs for P: ~a\n" (length s3))
(define s4 (filter (lambda (p) (= (length (sum= (sum p) s3)) 1))
s3))
(printf "Final pairs for S: ~a\n" (length s4))
(displayln s4))
(puzzle 100)
You may also check:How to resolve the algorithm Balanced ternary step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Horizontal sundial calculations step by step in the Factor programming language
You may also check:How to resolve the algorithm Magic squares of doubly even order step by step in the Wren programming language
You may also check:How to resolve the algorithm 2048 step by step in the C++ programming language
You may also check:How to resolve the algorithm Caesar cipher step by step in the zkl programming language