I encountered a fun coding challenge while programming today.
Suppose you are teaching a class and you brought with yourself a bag of candy to hand out to your students. You want to hand out every piece of candy, but do it in a way that disperses the candy provided to each student as evenly as possible. No student should have more than 1 extra piece of candy than any other student. Exactly which students get the extra pieces of candy does not matter.
Task: Write a function that takes N students and M pieces of candy, where M > N, and returns an array of length N showing the amount candy given to each student.
Followup Task: Generate this array in O(N) time, where N is the number of students (NOT the amount of candy!)
re: spoilers maybe?
@aschmitz yeah thats what it is
re: spoilers maybe?
@wallhackio It's funny, you can of course come up with a much faster setup function and a query function to return the amount of candy per consumer, but the asymptotic runtime gets wonky if you stare it down too hard or make it too asymptotic.
re: spoilers maybe?
@aschmitz what do you mean exactly?
re: spoilers maybe?
@wallhackio Modular arithmetic on very large numbers has asymptotic bounds I don't remember, and which change depending on the scale of the numbers.
golfed raku solution (49 bytes)
@wallhackio well this is way too parenthesized to golf nicely in any formulation i've come up with lol
musta goofed somewhere (this takes m as first arg then n)
{|((my$d=$^m div$^n)+1 xx$m%$n),|($d xx$n-$m%$n)}
golfed raku solution (49 bytes)
@wallhackio having slept on it, something involving the flip flop operators might manage to shave a few off?
Trying to solve (I probably misunderstood, this seems too trivial?)
@wallhackio Well, if you wanted to evenly distribute M candies to N students and keep the extra pieces yourself, that'd be M / N candies to each student, and you yourself would keep X = M % N pieces, an amount where X < N.
And now you give one extra piece of candy to the first (or the last, it doesn't matter) X students.
I think that storing this as an array would be a huge waste of memory, since it's just an array where the first X elements would be (M / N) + 1 and the remaining N - X elements would be M / N. I'd just write a program like this:
#include <stdio.h>
main(int argc,char** argv){
int M,N,Y,X;
if (argc < 3) {
fprintf(stderr, "%s <candies> <students>\n", *argv);
return 1;
}
M=atoi(argv[1]);N=atoi(argv[2]);
printf("First %d students get %d\n",(X=M%N),(Y=M/N)+1);
printf("Other %d students get %d\n",N-X,Y);
return 0;
}
Or, if you wanted to use the result further (and it's just part of a larger program), I'd return a tuple (doesn't exist in C, but we have structs), (X, N-X, M/N).
spoilers maybe?
@wallhackio Why is this not just M mod N entries of ceil(M/N) and the remaining entries of floor(M/N)?