user760220
user760220

Reputation: 1237

Having for loop output sets of numbers?

I have the following code

    for (int k=0; k<maxThreads; k++) {
        int firstpart = k * tasksPerThread;
        int secondpart = ((k+1) * tasksPerThread) - 1;
        System.out.println(firstpart + "," + secondpart);
    }

Where maxThreads is inputted by the user and tasksPerThread is 10/maxThreads. MaxThreads is never less than 1. This outputs pairs of numbers. For example, if maxThreads = 2 (making tasksPerThread = 5) then it outputs

0,4
5,9

Covering all ten values 0-9

I want all ten values to be covered if maxThreads = 4. Right now the code outputs this

0,1
2,3
4,5
6,7

But I would like it to cover 0-9. So ideally it would output

0-2
3-5
6-7
8-9

Or really any combination that has maxThreads number of sets of numbers and covers 0-9. How can I adjust the for loop to do this?

Thank you.

Upvotes: 0

Views: 93

Answers (4)

Aritz
Aritz

Reputation: 31651

You have to take one thread more in the tasksPerThread variable in this case. You're calculating it as 10/maxThreads but you need to apply ceiling to it.

int tasksPerThread = Math.ceil(10/(double) maxThreads);

Note that you have to get maxThreads as a double, because if you take it as an int, the div result will always be an int.

This should do it:

 int tasksPerThread = Math.ceil(10/(double) maxThreads);
 for (int k=0; k<maxThreads; k++) {
    int firstpart = k * tasksPerThread;
    int secondpart = ((k+1) * tasksPerThread) - 1;
    System.out.println(firstpart + "," + secondpart);
}

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234795

This code will divide up n tasks among maxThreads threads:

public static void schedule(int n, int maxThreads) {
    int tasksPerThread = (n + maxThreads - 1) / maxThreads;
    int nExtra = tasksPerThread * maxThreads - n;
    int nFull = tasksPerThread * (maxThreads - nExtra);
    int start = 0;
    while (start < nFull) {
        int end = start + tasksPerThread - 1;
        System.out.printf("%1$d,%2$d%n", start, end);
        start = end + 1;
    }
    while (start < n) {
        int end = start + tasksPerThread - 2;
        System.out.printf("%1$d,%2$d%n", start, end);
        start = end + 1;
    }
}

Upvotes: 1

SamYonnou
SamYonnou

Reputation: 2068

You can do something like :

for (int k = 0; k < maxThreads; k++) {
  int firstpart = (int) (k * tasksPerThread);
  int secondpart = (int) (((k + 1) * tasksPerThread) - 1);
  System.out.println(firstpart + "," + secondpart);
}

where tasksPerThread is computed as :

double tasksPerThread = 10.0 / maxThreads;

or equivalently

double tasksPerThread = 10 / (double) maxThreads;

Upvotes: 1

Bagzli
Bagzli

Reputation: 6569

it is being rounded down I think, try using ceiling.

Upvotes: 1

Related Questions