I’m trying to work out an efficient way to implement population dynamics: if there are 9 office workers in a building I want to pass the list of workers into a function, and have it iterate through that list and assign one third of the total list to floors 1, one third to floor 2, and one third to floor 3. I currently do this with a series of for loops:
for (int i = 0; i < numberOfWorkers/3; i++){
workersArray*.GetComponent<JobAssignment>().AssignedFloor = 1;*
}*
_ for (int i = numberOfWorkers/3; i < (numberOfWorkers/3)2; i++){_
_ workersArray.GetComponent().AssignedFloor = 2;_
_ }_
_ for (int i = 0; i < numberOfWorkers; i++){_ _ workersArray.GetComponent().AssignedFloor = 3; }* This is extremely clunky, requires me to hard-code floor assignments, and will leave 10% of the total workers unassigned if I feed it a value that is not divisible by three. Is there a more efficient way to accomplish this that I’m missing?_
So it’s not just repetitive but you’re also overwriting the values you previously assigned since you’re always start from 0.
Here’s my 2 cents (works only with values divisible by 3):
int[] values = { 1, 2, 3 };
int oneThird = numberOfWorkers / 3;
for (int i = 0, vIndex = -1; i < numberOfWorkers; i++)
{
if (i % oneThird == 0)
vIndex++;
workers*.floor = values[vIndex];*
}*
> and will leave 10% of the total > workers unassigned if I feed it a > value that is not divisible by three Well since you want to assign each one third of your workers, you need a value divisible by three… You could maybe assign the left-overs some per-determined value, I’ll edit my answer soon. Edit: So here’s two ways you could handle left-overs - the first is done in one loop but with more checks, the second is done via two loops but with less checks (same amount of iterations is done in both cases - Note that count is the number of workers):
int[] values = { 1, 2, 3 };*
int leftoverValue = 2; // assign any leftover workers the second floor*
int oneThird = count / 3;*
for (int i = 0, vIndex = -1; i < count; i++)*
{*
if (i % oneThird == 0)*
vIndex++;*
_ workers*.floor = vIndex < values.Length ? values[vIndex] : leftoverValue;_
_ }_ Second:
_ int values = { 1, 2, 3 };_
_ int leftoverValue = 2;_
_ int oneThird = count / 3;_ _ int threeThirds = oneThird * 3;_
_ for (int i = 0, vIndex = -1; i < threeThirds; i++)_
_ {_
_ if (i % oneThird == 0)_
_ vIndex++;_ _ workers.floor = values[vIndex]; } int leftovers = count % 3; for (int i = count - leftovers; i < count; i++) { workers.floor = leftoverValue; }* It’d be interesting if there’s a LINQ solution to this, hmm…_