Max Effects
Max Effects

Reputation: 13

Dividing and spacing

I need to divide a variable distance in a very specific way. The spacing for the divisions must be 40 units minimum, and 80 units maximum.

I've tried several different various of this code but I am struggling to wrap my head around how to include the min/max variable in my division.

double totaldist = X; 
double division = totaldist / 80;
double roundup = Math.Ceiling(division);
double space = totaldist / roundup;

double increment = 0;
while (increment < totaldist)
{
increment = increment + space;
}

The attached code is obviously short of what I want to accomplish, I'm not sure how to bridge the gap. Thank you

Upvotes: 1

Views: 97

Answers (2)

Maxim Khanov
Maxim Khanov

Reputation: 434

So all you have to do is loop over all the possible divisors and pick the best one. The simplest way to accomplish this is as follows:

public static int remainder(int totalDist)
{
    double minRemainder = (totalDist % 40) / 40;
    int bestDivision = 40;
    for (var i = 40; i <= 80; i++)
    {
        double cRemainder = (totalDist % i) / i;
        if (totalDist % i == 0) return i;
        else if (cRemainder < minRemainder) { minRemainder = cRemainder; bestDivision = i; }
    }
    return bestDivision;
}

This will always return the closest result. Even if there is no real solution, it will still provide an approximate answer as a fallback.

Upvotes: 2

Caius Jard
Caius Jard

Reputation: 74660

I'd test every divisor for mod 0 (no remainder)

int d = 420;
int s = 40;
for(; s <= 80; s++){
  if(d%s==0)
    break;
}
if(s==81)
  Console.Write("There is no suitable divisor");
else
  Console.Write($"{d} divides into {s} segments of {d/s} with no remainder");

If you want to minimise the segment length (greater number of segments) start at 80 and work towards 40 in the loop instead - set your d to 480, start at 80 and you should get "80 segments of length 6" rather than "40 segments of length 12"

You can even get cute with your loop and have no body:

for(; s <= 80 && d%s > 0; s++){ }

But it's not quite so readable/self explanatory

Upvotes: 0

Related Questions