Homework
April 3, 2020
[ I continue working from home. It is interesting that my commute has gone from a daily 75-minute round-trip by car to a 75-foot round-trip by foot, so I think I should have more energy in the evening, but the opposite is true; I am exhausted by the end of the day, just from sitting in front of my laptop. ]
Today’s exercise is somebody’s homework:
Given positive integers C and N, find N numbers that sum up to C and the difference between the highest and the lowest of these number should not be more than one. For example: with C = 26 and N = 7, the desired output is [4 4 4 4 4 3 3].
Your task is to write a program to solve the student’s homework. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
A perl “1-liner”:
[sourceode lang=”perl”]
print “@{[ hw(@ARGV) ]}\n”;
sub hw {
my($C,$N) = @_;
return map { int($C/$N) + ($_<$C%$N) } 0..($N-1);
}
[/sourcecode]
A simple solution in standard R7RS Scheme and a couple of popular
helpers.
Output:
Here’s a solution in Python.
Output:
Here’s a Haskell version.
https://github.com/dennisporterjr/practice-algorithms/blob/master/one-diff-sum.js
def homework(C, N):
if C % N == 0:
answer = [C / N] * N
return answer
else:
remainder = C % N
C -= remainder
answer = [C / N] * N
for i in range(remainder):
answer[i] += 1
return answer
print(solver(26,7))
Racket: https://github.com/xojoc/programming-praxis/blob/master/2020_04_03.rkt
Using Python with + for concatenation of lists and * for repetition ([1] * 3 == [1, 1, 1]).