galba84
galba84

Reputation: 112

divide (split) the line into segments of arbitrary length each. (short at begining wide at the end)

Assume there is a line (1, 30) (float x = 30) I need to split it into segments, each next segment should be wider than previous one, and the last segment should be X times wider than first one.

I have idea first split line into equal parts and than increase next and decrease previous until two conditions reached: - first segment is shorter than last X times - each segment (except first) is wider than previous for the same multiplier

    //input:
    int lineDimension = 30;
    int numberOfSegments = 5;
    int step = 1;

    float[] splitLineIntoSegments(float lineDimension, int numberOfSegments, float differenceBetweenFirstAndLastSegmentMultiplicator, float step) {
      float[] result = new float[numberOfSegments];
      //first split into equal segments
      for (int i = 0; i < numberOfSegments; i++) {
        result[i] = lineDimension / numberOfSegments;
      }
      //increase each next value untill difference reached
      do {
        for (int ii = 0; ii < numberOfSegments; ii++) {
          if (result[ii]-step<=0)
            return result;
            if (ii>numberOfSegments/2){
              result[ii] += step;
            }
            else result[ii] -= step;
        }
      }
      while ((float)result[numberOfSegments] / (float)result[0] > differenceBetweenFirstAndLastSegmentMultiplicator);

      return result;
    }

float [] res = splitLineIntoSegments(lineDimension,numberOfSegments,2,step);

as the result it should be 4,5,6,7,8

There is a better way to do it ?

Upvotes: 0

Views: 587

Answers (2)

Prune
Prune

Reputation: 77837

You can force a simple arithmetic sequence for this. Start with the problem parameters:

N = quantity of segments
X = scale factor: segment[N-1] / segment[0]
L = length of line

First, find the required mean:

mean = L / N

Now, we need the first and last terms to average to the mean. Let a be the length of the first segment, currently unknown. Solve for a

(a + X*a) / 2 = mean
 a = 2*mean / (1+X)

You now have the first (a) and last (X*a) terms, and the quantity of terms. Now it's trivial to find the common difference:

d = (X*a - a) / (N-1)

Your sequence of segments is now

[ a + i*d for 0 <= i < N ]    // i being a sequence of integers

Upvotes: 0

user1196549
user1196549

Reputation:

If the ratios must be constant, let r, the relative lengths of the segments are 1, r, , , … r^(n-1) for n parts and this sums to (r^n-1) / (r-1). We also have X = r^(n-1), giving r = X^(1/(n-1)).

If the length of the line segment is L, the parts are

L.r^k.(r-1) / (r^n-1)

E.g. for 4 parts and X=27/8, we have r=3/2 and the parts are 8/65, 12/65, 18/65, and 27/65 of L.


If the ratios needn't be constant and the parts are proportional to some given numbers Rk (such that X=R[n-1]/R0), take the sum R and use

L.Rk / R

Upvotes: 3

Related Questions