使用Dr。Dr.的Magic 1089计划

时间:2014-10-01 07:36:56

标签: string numbers scheme racket

我正在尝试创建一个消耗xyz的程序,数字按递减顺序排列,并产生1089.我必须取xyz,反转数字,确定xyz之间的区别,反之并称之为diff ,添加差异,它反过来然后得到1089的答案。我已经尝试了几个小时,但我无法弄清楚如何创建代码。到目前为止,我只尝试过功能,但我仍然无法让它工作。我做错了什么?:

1)

(define h 100)
(define t 10)
(define o 1)

(define (front xyz)
  (number->string (substring xyz 0 1)))

(define (mid xyz)
  (number->string (substring xyz 1 2)))

(define (back xyz)
  (number->string (substring xyz 2 3)))

(define (reversexyz xyz)
  (string->number (+ (* (back xyz) h) (* (mid xyz) t) (* (front xyz) o))))

(define (diff abc)
  (- xyz (reversexyz)))

(define (frontdiff abc)
  (number->string (substring frontdiff 0 1)))

(define (middiff abc)
  (number->string (substring middiff 1 2)))

(define (backdiff abc)
  (number->string (substring backdiff 2 3)))

(define (reversediff xyz)
  (number->string (+ (* (backdiff abc) h) (* (middiff abc) t) (* (frontdiff abc) o))))

(define (magic xyz)
  (+ diff reversediff))

1 个答案:

答案 0 :(得分:1)

基于this explanation,这应该像以下一样简单:

(define (pad0 str) ; add leading 0's to a string, 3 characters wide
  (~a #:width 3 #:align 'right #:left-pad-string "0" str))

(define (reverse-num n) ; reverse a number
  (string->number (list->string (reverse (string->list (pad0 (number->string n)))))))

(define (magic xyz) ; the magic happens here
  (define diff (abs (- (reverse-num xyz) xyz)))
  (+ diff (reverse-num diff)))

测试:

> (magic 123)
1089
> (magic 678)
1089
> (magic 321)
1089
> (magic 546)
1089

FWIW,在此修改之后,仍有90个数字介于100和999(含)之间,算法无效:

> (for/sum ((i (in-range 100 1000)) #:when (not (= (magic i) 1089))) 1)
90