Skip to content

Instantly share code, notes, and snippets.

@Roemerb
Created June 16, 2019 22:11
Show Gist options
  • Save Roemerb/986b4ca7fbe3e5d531708a43f73ac3c9 to your computer and use it in GitHub Desktop.
Save Roemerb/986b4ca7fbe3e5d531708a43f73ac3c9 to your computer and use it in GitHub Desktop.
class Ding
{
public static int[][] splitInBuckets(int min, int max, int nBuckets, int[] arr) throws Exception
{
if (min < 0)
{
throw new Exception("min cannot be smaller than 0");
}
int[][] output = new int[nBuckets][]; // the output array
int[] distribution = new int[nBuckets]; // stores the distribution of elements in the array
int[] found = new int[nBuckets]; // stores how many digits of each group are found
int useMin = min == 0 ? 1 : min; // if min is 0, use 1 to calculate min for each slice
// Calculate the distribution
for (int i = 0; i < arr.length; i++)
{
for (int j = 0; j < nBuckets; j++)
{
// if the value in the range of this slice, add 1 to the length of the slice and break
if (
(arr[i] >= (j*useMin)) && (arr[i] <= (int) Math.ceil(max/nBuckets))
)
{
distribution[j]++;
break;
}
}
}
// initialize all output sub arrays
for (int i = 0; i < nBuckets; i++)
{
output[i] = new int[distribution[i]];
}
// fill up the output
for (int i = 0; i < arr.length; i++)
{
for (int j = 0; j < nBuckets; j++)
{
if (
(arr[i] >= (j * (j*useMin)-1)) && // min is the bucket no. x min
(arr[i] <= (j+1)*(int) Math.ceil(max/nBuckets)) // max is bucket no. * max divided by noBuckets. +1 bc j starts at 0
)
{
output[j][found[j]] = arr[i];
found[j]++;
break;
}
}
}
return output;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment