HenHanna wrote:
e.g. -------- For the (street) Numbers (1,2,3,4,5,6,7,8)
(1,2,3,4,5) and (7,8) both add up to 15.
"In a given street of houses with consecutive numbers between
50 and 500, find the house number, for which, the sum of
numbers on the left is equal to the sum of numbers on the
right"
Gauche Scheme
(define (strand lst)
(let go ((left-sum 0) (tail lst))
(if (null? tail)
#f
(let ((right-sum (fold + 0 (cdr tail))))
(cond ((< left-sum right-sum)
(go (+ left-sum (car tail)) (cdr tail)))
((= left-sum right-sum) (car tail))
(#t #f))))))
(strand '(1 2 3 4 5 6 7 8))
===>
6
(lrange 2 5)
===>
(2 3 4)
(any
(lambda (n)
(if (strand (lrange 50 n))
n
#f))
(lrange 500 50 -1))
===>
352
(strand (lrange 50 352))
Gauche Scheme
(define (strand lst)
(let go ((left-sum 0) (tail lst))
(if (null? tail)
#f
(let ((right-sum (fold + 0 (cdr tail))))
(cond ((< left-sum right-sum)
(go (+ left-sum (car tail)) (cdr tail)))
((= left-sum right-sum) (car tail))
(#t #f))))))
===>
352
Faster:
60551irb(main):002:0> (353..500).sum
63122
x = 1
1
y = 8
8
(x..y).select {|n| (x..(n-1)).sum == ((n+1)..y).sum}
[6]
x = 50
50
y = 500
500
(x..y).select {|n| (x..n-1).sum == (n+1..y).sum}
[]
(x..y).select {|n| puts "#{n} #{(x..(n-1)).sum} #{((n+1)..y).sum}"}
So no house. I’ll skip the full output, but for the tipping point I see:
(x..y).select {|n| puts "#{n} #{(x..(n-1)).sum} #{((n+1)..y).sum}"}
355 61610 62060
356 61965 61704
range_sum_midpoint(1,8)
6.0
range_sum_midpoint(50,500)
355.6332380416656
HenHanna wrote:
e.g. -------- For the (street) Numbers (1,2,3,4,5,6,7,8)
(1,2,3,4,5) and (7,8) both add up to 15.
"In a given street of houses with consecutive numbers between
50 and 500, find the house number, for which, the sum of
numbers on the left is equal to the sum of numbers on the
right"
Gauche Scheme
(define (strand lst)
(let go ((left-sum 0) (tail lst))
(if (null? tail)
#f
(let ((right-sum (fold + 0 (cdr tail))))
(cond ((< left-sum right-sum)
(go (+ left-sum (car tail)) (cdr tail)))
((= left-sum right-sum) (car tail))
(#t #f))))))
(strand '(1 2 3 4 5 6 7 8))
===>
6
(lrange 2 5)
===>
(2 3 4)
(any
(lambda (n)
(if (strand (lrange 50 n))
n
#f))
(lrange 500 50 -1))
===>
352
(strand (lrange 50 352))
===>
251
Sysop: | Keyop |
---|---|
Location: | Huddersfield, West Yorkshire, UK |
Users: | 376 |
Nodes: | 16 (3 / 13) |
Uptime: | 24:21:29 |
Calls: | 8,035 |
Calls today: | 5 |
Files: | 13,034 |
Messages: | 5,829,136 |