Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,35 @@
#lang racket
(define (interprete expr numbers)
;; the cashe for used numbers
(define cashe numbers)
;; updating the cashe and handling invalid cases
(define (update-cashe! x)
(unless (member x numbers) (error "Number is not in the given set:" x))
(unless (member x cashe) (error "Number is used more times then it was given:" x))
(set! cashe (remq x cashe)))
;; the parser
(define parse
(match-lambda
;; parsing arythmetics
[`(,x ... + ,y ...) (+ (parse x) (parse y))]
[`(,x ... - ,y ...) (- (parse x) (parse y))]
[`(,x ... * ,y ...) (* (parse x) (parse y))]
[`(,x ... / ,y ...) (/ (parse x) (parse y))]
[`(,x ,op ,y ...) (error "Unknown operator: " op)]
;; opening redundant brackets
[`(,expr) (parse expr)]
;; parsing numbers
[(? number? x) (update-cashe! x) x]
;; unknown token
[x (error "Not a number: " x)]))
;; parse the expresion
(define result (parse expr))
;; return the result if cashe is empty
(if (empty? cashe)
result
(error "You didn`t use all numbers!")))

View file

@ -0,0 +1,36 @@
;; starting the program
(define (start)
(displayln "Combine given four numbers using operations + - * / to get 24.")
(displayln "Input 'q' to quit or your answer like '1 - 3 * (2 + 3)'")
(new-game))
;; starting a new game
(define (new-game)
;; create a new number set
(define numbers (build-list 4 (λ (_) (+ 1 (random 9)))))
(apply printf "Your numbers: ~a ~a ~a ~a\n" numbers)
(new-input numbers))
;; processing a new user input
(define (new-input numbers)
;; if an exception is raized while processing, show the exeption message
;; and prompt for another input, but do not stop the program.
(with-handlers ([exn? (λ (exn)
(displayln (exn-message exn))
(new-input numbers))])
;; get the answer
(define user-expr (read-the-answer))
;; interprete it
(case user-expr
[(q) (display "Good buy!")]
[(n) (new-game)]
[else (define ans (interprete user-expr numbers))
(case ans
[(24) (printf "Indeed! ~a = 24\n" user-expr)
(new-game)]
[else (error "Wrong!" user-expr '= ans)])])))
;; reading and preparing the user's answer
;; "1 + 2 * (3 + 4)" --> '(1 + 2 * (3 + 4))
(define (read-the-answer)
(read (open-input-string (format "(~a)" (read-line)))))