So I have this dummy 2D array:
int mat[][] = {
{10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89}};
I want to add up all the values by columns so it would add 10 + 15 + 27 + 32 and return 84 and so on. I have this so far:
public void sum(int[][] array) {
int count = 0;
for (int rows = 0; rows < array.length; rows++) {
for (int columns = 0; columns < array[rows].length; columns++) {
System.out.print(array[rows][columns] + "\t");
count += array[0][0];
}
System.out.println();
System.out.println("total = " + count);
}
}
Can anyone help with this? Also the System.out.print(array[rows][columns] + "\t" ); prints the array out by rows, is there a way to print it out by columns?
One possible Solution would be to first find maximum size of all sub arrays and iterate that many times to find sum of each column avoiding unavailable values.
public static void main(String[] args) {
int mat[][] = {{10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89},
};
// Find maximum possible length of sub array
int maxLength = 0;
for (int i = 0; i < mat.length; i++) {
if (maxLength < mat[i].length)
maxLength = mat[i].length;
}
for (int i = 0; i < maxLength; i++) {
int sum = 0;
for (int j = 0; j < mat.length; j++) {
// Avoid if no value available for
// ith column from this subarray
if (i < mat[j].length)
sum += mat[j][i];
}
System.out.println("Sum of Column " + i + " = " + sum);
}
}
Use an ArrayList to get the sum of all the columns.
public static void sum(int[][] array) {
ArrayList<Integer> sums = new ArrayList<>();
for (int row = 0; row < array.length; row++) {
for (int column = 0; column < array[row].length; column++) {
if (sums.size() <= column) {
sums.add(column, 0);
}
int curVal = sums.get(column);
sums.remove(column);
sums.add(column, curVal + array[row][column]);
}
}
for (int i = 0; i < sums.size(); i++) {
System.out.println("Sum of column " + i + " = " + sums.get(i));
}
}
Here is one alternative.
The supplied data.
int mat[][] = { { 10, 20, 30, 40, 50, 60, 70, 80, 90 },
{ 15, 25, 35, 45 }, { 27, 29, 37, 48 },
{ 32, 33, 39, 50, 51, 89 }, };
First, find the maximum length of the array in which to store the sum.
int max = Arrays.stream(mat).mapToInt(a -> a.length).max().orElse(0);
Allocate the new array to hold the sums.
int[] sums = new int[max];
Now just use the Arrays.setAll method to sum them, taking careto not exceed the current array's length.
for (int[] arr : mat) {
Arrays.setAll(sums, i-> i < arr.length ? sums[i] + arr[i] : sums[i]);
}
System.out.println(Arrays.toString(sums));
Prints
[84, 107, 141, 183, 101, 149, 70, 80, 90]
You can use Stream.reduce method to summarise the elements of the rows of the matrix by the columns:
int[][] matrix = {
{10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89}};
int[] arr = Arrays.stream(matrix)
// summarize in pairs
// the rows of the matrix
.reduce((row1, row2) -> IntStream
// iterate over the indices
// from 0 to maximum row length
.range(0, Math.max(row1.length, row2.length))
// summarize in pairs the elements of two rows
.map(i -> (i < row1.length ? row1[i] : 0) +
(i < row2.length ? row2[i] : 0))
// an array of sums
.toArray())
// the resulting array
.get();
System.out.println(Arrays.toString(arr));
// [84, 107, 141, 183, 101, 149, 70, 80, 90]
See also:
• Sum of 2 different 2d arrays
• How to calculate the average value of each column in 2D array?
…and the same with lambda:
int[] array = Arrays.stream(mat)
.reduce((a1, a2) -> IntStream.range(0, Math.max(a1.length, a2.length))
.map(i -> i < a1.length && i < a2.length ? a1[i] + a2[i]
: i < a1.length ? a1[i] : a2[i] ).toArray()).get();
gets the sums of each column in the int[] array:
[84, 107, 141, 183, 101, 149, 70, 80, 90]
Related
ReadFile randomGenerate = new ReadFile();
Input userNum = new Input();
String classnum = userNum.fileToSelect();
int lineNumber = randomGenerate.lineCounter(classnum);
//number of students in classnum.txt
ArrayList<String> people = randomGenerate.readPeople();
//a string of names(first word on each row)
int userPut = userNum.numInput();
int maxNum = lineNumber/userPut;
Right not, I am reading off a txt file - the first word of each row which is the name of a person. I want to distribute this ArrayList of people into even groups, with the number of groups based on userinput.
int[] numbers = RandomNumbersWithoutRepetition(0, lineNumber, lineNumber);
//an array of numbers IN ORDER
int[] randomNumbers = RandomizeArray(numbers);
//shuffles the array
I generated a set of numbers in order, and then shuffled them, which works fine.
But, my method of grouping people has been based off ifelse conditions which don't work so well. So is there an efficient method to put this ArrayList of names into user-desired groups?
I have x number of students.
I have n number of groups.
I'm assuming there's no other criteria for dividing students into groups.
Basically, you divide the number of groups into the number of students. Yes, you have to deal with a remainder. But it's straightforward.
Here are the results of a test. I created 53 students and shuffled them. I then divided the students into 4 groups. I manually formatted the output to fit in the answer. Group 1 has 14 students, while the remaining groups have 13 students.
Students: 42, 27, 5, 26, 32, 30, 44, 10, 17, 29, 40, 52,
47, 38, 49, 18, 46, 24, 34, 12, 13, 53, 35, 20, 1,
2, 41, 23, 43, 28, 8, 11, 50, 37, 9, 7, 48, 3, 33,
25, 31, 15, 22, 21, 14, 45, 36, 16, 51, 19, 4, 6, 39
Group 1: 42, 27, 5, 26, 32, 30, 44, 10, 17, 29, 40, 52, 47, 38
Group 2: 49, 18, 46, 24, 34, 12, 13, 53, 35, 20, 1, 2, 41
Group 3: 23, 43, 28, 8, 11, 50, 37, 9, 7, 48, 3, 33, 25
Group 4: 31, 15, 22, 21, 14, 45, 36, 16, 51, 19, 4, 6, 39
And here's the code. The groupStudents and sortStudents methods are the methods that do the work.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class StudentGroups {
public static void main(String[] args) {
int numberOfGroups = 4;
int numberOfStudents = 53;
StudentGroups sg = new StudentGroups(numberOfStudents);
sg.printStudents();
List<List<Integer>> groups = sg.groupStudents(
numberOfGroups);
sg.printGroups(groups);
}
private List<Integer> students;
public StudentGroups(int numberOfStudents) {
students = new ArrayList<>(numberOfStudents);
for (int i = 0; i < numberOfStudents; i++) {
students.add(i + 1);
}
Collections.shuffle(students);
}
public void printStudents() {
System.out.print("Students: ");
for (int i = 0; i < students.size(); i++) {
System.out.print(students.get(i));
if (i < (students.size() - 1)) {
System.out.print(", ");
}
}
System.out.println();
}
public List<List<Integer>> groupStudents(int groups) {
List<List<Integer>> output = new ArrayList<>();
int size = students.size();
int group = size / groups;
int remainder = size % groups;
sortStudents(output, size, group, remainder);
return output;
}
private void sortStudents(List<List<Integer>> output,
int size, int group, int remainder) {
List<Integer> list = new ArrayList<>();
int count = 0;
for (int i = 0; i < size; i++) {
list.add(students.get(i));
if (count == 0 && remainder > 0) {
if (group > 0) {
list.add(students.get(++i));
}
remainder--;
}
if (++count >= group) {
addList(output, list);
list = new ArrayList<>();
count = 0;
}
}
addList(output, list);
}
private void addList(List<List<Integer>> output,
List<Integer> list) {
if (list.size() > 0) {
output.add(list);
}
}
public void printGroups(List<List<Integer>> groups) {
for (int j = 0; j < groups.size(); j++) {
System.out.print("Group ");
System.out.print(j + 1);
System.out.print(": ");
List<Integer> students = groups.get(j);
for (int i = 0; i < students.size(); i++) {
System.out.print(students.get(i));
if (i < (students.size() - 1)) {
System.out.print(", ");
}
}
System.out.println();
}
}
}
public class BarChart // Modified from Fig 7.6
{
public static void main(String[] args)
{
int[] grades = {90, 71, 89, 75, 83, 87, 81, 100, 99, 83,
65, 100, 91, 78, 88, 62, 55, 84, 73, 89}; // 20 elements
int[] frequency = new int[11]; // 11 ranges
System.out.println("Grade distribution:");
for (int i = 0; i < grades.length; i++) {
frequency[grades[i]/10]++; //How does this work? why does it say 10
}
for (int i = 0; i < frequency.length; i++)
{
if (i == 10) {
System.out.printf("%5d: ", 100);
}
else {
System.out.printf("%02d-%02d: ", i * 10, i * 10 + 9);
}
for (int stars = 0; stars < frequency[i]; stars++) { // How does it know where to print the stars?
System.out.print("*");
}
System.out.println();
}
}
}
Output:
I am having trouble understanding how this program works. I put in some questions as comments to get a clearer answer. I attached a pic of the output as well.
I have commented in the code directly:
public class BarChart // Modified from Fig 7.6
{
public static void main(String[] args)
{
/*array that contains the data that will be used to display the distribution*/
int[] grades = {90, 71, 89, 75, 83, 87, 81, 100, 99, 83,
65, 100, 91, 78, 88, 62, 55, 84, 73, 89}; // 20 elements
/*this frequecncy is used to divided your interval [0,100] in 11 slices*/
int[] frequency = new int[11]; // 11 ranges
System.out.println("Grade distribution:");
for (int i = 0; i < grades.length; i++) {
/*division of your i element of grade array by 10,
10 here is used here to make correspond your grades
to your slices defined in the frequency variable,
(type int divided by 10 will give an int as output
(the decimals are truncated -> equivalent as taking the floor of the number)
so you have an int that can be used as an index for your frequency array,
the grades[i]/10 will be incremented by 1 -> this will allow to print the stars after*/
frequency[grades[i]/10]++;
}
for (int i = 0; i < frequency.length; i++) //loop that will do the display
{
if (i == 10) {
System.out.printf("%5d: ", 100);//this will print the last line of your output,
//printf will not print the EOL char so the other printing operations are done on the same line
}
else {
System.out.printf("%02d-%02d: ", i * 10, i * 10 + 9);
//this is will create your DD-DD intervals (00-09:, 10-19)
}
for (int stars = 0; stars < frequency[i]; stars++) {
// the value stored in frequency thanks to this operation: frequency[grades[i]/10]++; will be displayed,
//you loop from 0 until you reach the value of frequency[i] and display a star at each loop
System.out.print("*");
}
System.out.println();//this will print the end of line character
}
}
}
I have 2 dimensional array like :
{2 , 6 , 46, 8 , 7 , 25, 64 , 9 , 10},
{6 , 10, 50, 12, 11, 29, 68 , 13, 14},
{46, 50, 90, 52, 51, 69, 108, 53, 54}
How can I find the duplicate elements like '6', '46' and '50'?
My code finds consecutive duplicates:
for (int i = 0; i < a2.length; i++) {
for (int j = 0; j < a2[i].length; j++) {
cursor = a2[i][j];
if(j + 1 < a2[i].length){
if(cursor == a2[i][j + 1]){
System.out.println(cursor + "has duplicate in this array");
}
}
}
}
Iterate through all elements and save it in a temporary set.
When you encounter a duplicate, the list will contain it.
import java.util.HashSet;
import java.util.HashSet;
public class HelloWorld
{
public static void main(String[] args)
{
int[][] arr = {
{2 , 6 , 46, 8 , 7 , 25, 64 , 9 , 10},
{6 , 10, 50, 12, 11, 29, 68 , 13, 14},
{46, 50, 90, 52, 51, 69, 108, 53, 54}
};
HashSet<Integer> elements = new HashSet<>();
HashSet<Integer> duplicates = new HashSet<>();
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if(elements.contains(arr[i][j])) {
duplicates.add(arr[i][j]);
}
elements.add(arr[i][j]);
}
}
System.out.println(duplicates.toString());
}
}
Output:
[50, 6, 10, 46]
Try this code:-
import java.util.Arrays;
import java.util.List;
public class ArrayTest {
public static void main(String[] args) {
Integer[][] myarray = new Integer[][]{
{ 10, 20, 30, 40 },
{ 50, 77, 60, 70 },
{ 33, 22, 88, 99 },
{ 21, 66, 65, 21 }
};
int i,j;
for(i=0;i<myarray.length;i++)
{
for(j=0;j<myarray.length;j++)
{
int temp= myarray[i][j];
myarray[i][j]=0;
List<Integer> rowvalues = Arrays.asList(Arrays.asList(myarray).get(i));
Boolean b=rowvalues.contains(temp) ;
if(b==true)
{
System.out.println("duplicate at ["+i+"]["+j+"] is: "+temp);
}
myarray[i][j]=temp;
}
}
}
}
I feel like the answer so simple but I just can't figure out what it is. I have an multidimensional array such as this:
int [][] number =
{{ 10, 15, 11, 13, 72, 87, 266},
{ 50, 65, 80, 94, 12, 134, 248},
{ 1, 2, 1, 9, 1, 39, 26},
{ 13, 20, 76, 4, 8, 72, 28},
{ 2, 1, 29, 2, 12, 907, 92},
{ 16, 4, 308, 7, 127, 1, 52}
};
I'm trying to add up all the integers in the each array index and display it at the end so what I thought up of is this
int total=0;
for (int k=0;k<6;k++){
for (int i=0;i<7;i++){
total=number[k][i]+total;}}
System.out.println(total);
What I noticed is that it will add up all the numbers in the entire array. But how do I stop it at the end of each index?
Your question is not clear . But from what I understood you must do
for (int k=0;k<6;k++){
int total=0;
for (int i=0;i<7;i++){
total=number[k][i]+total;}
System.out.println(total);}
It will print sum of all rows
Couldn't the loop be like this:
for (int k = 0; k < 6; k++) {
int total = 0;
for (int i = 0; i < 7; i++) {
total += number[k][i];
}
System.out.println(total);
}
Assuming I get what you mean by stop it at the end of each index.
And better should it be if you parametrize your loops to fit in each dimension length:
for (int k = 0; k < number.length; k++) {
int total = 0;
for (int i = 0; i < number[k].length; i++) {
total += number[k][i];
}
System.out.println(total);
}
Not sure if this exact question's been asked before, though a similar question has been asked here. Essentially, what I'm trying to is generate random integers of a minimum size that still sum up to a certain value (an invariant is that the sum / (number of randoms you want) is greater than the minimum value. Here's a sad attempt I coded up:
import java.util.Arrays;
import java.util.Random;
public class ScratchWork {
private static Random rand = new Random();
public static void main(String[] args) {
int[] randoms = genRandoms(1000, 10, 30);
for (int i = 0; i<randoms.length; i++) sop("Random Number "+ (i+1) + ": " + randoms[i]);
sop("Sum: " + sum(randoms));
}
public static int sum(int[] array) { int sum = 0; for (int i : array) sum+=i; return sum; }
public static int[] genRandoms(int n, int numberOfRandoms, int min) {
if (min > n/numberOfRandoms) throw new UnsupportedOperationException();
int[] intRandArray = {0};
while (sum(intRandArray) != n) {
////////////////////////
// See https://stackoverflow.com/questions/2640053/getting-n-random-numbers-that-the-sum-is-m
Double[] randArray = new Double[numberOfRandoms];
double workerSum = 0;
for (int i = 0; i<numberOfRandoms; i++) {
randArray[i] = ((double)rand.nextInt(n-1)+1);
workerSum += randArray[i];
}
for (int i = 0; i<randArray.length; i++) {
randArray[i] = n*(randArray[i]/(workerSum));
}
/////////////////////////
while (existsSmallerNumThanMin(randArray, min))
randArray = continueToFix(randArray, min);
//Convert doubles to ints
intRandArray = new int [randArray.length];
for (int i = 0; i < intRandArray.length; i++)
intRandArray[i] = (int)Math.round(randArray[i]);
}
return intRandArray;
}
public static boolean existsSmallerNumThanMin(Double[] randArray, int min) {
for (double i : randArray) if (i < (double)min) return true;
return false;
}
public static Double[] continueToFix(Double[]randArray, int min) {
Double[] tempArray = Arrays.copyOf(randArray, randArray.length);
Arrays.sort(tempArray);
int smallest = Arrays.asList(randArray).indexOf(tempArray[0]);
int largest = Arrays.asList(randArray).indexOf(tempArray[tempArray.length-1]);
double randomDelta = rand.nextInt(min);
randArray[smallest]+=randomDelta;
randArray[largest]-=randomDelta;
return randArray;
}
public static void sop(Object s) { System.out.println(s); }
}
This is neither an elegant nor high-performing way to do this... It also doesn't seem to work well (if at all) when passed in, say, (100,10,10), which only allows for the number 10 in the array. The distribution of the random numbers is also pretty bad.
Is there an elegant approach to this??
Also, my end goal is to implement this in Objective-C, though I'm still just learning the ropes of that language, so any tips for doing this in that language would be greatly appreciated.
I did some more testing, and my Java implementation is broken. I think my algorithm is bad.
How about something like getting N random numbers in [0,1] and normalize the results based on their sums (different than the desired sum). Then multiply these values against the desired number sum.
This assumes the minimum size is 0. Generalizing this to maintain a minimum for each result is simple. Just feed in sum - min * n for sum. Add min to all the results.
To avoid potential floating point issues, you can do something similar with using a range of integer values that are logically on the scale [0,M] (M arbitarily large) instead of [0,1]. The idea is the same in that you "normalize" your random results. So lets say you get a random sum of N (want N to have to be a multiple of sum+1... see REMARK). Divy N up by sum+1 parts. The first part is 0, second is 1, ..., last is sum. Each random value looks up its value by seeing what part of N it belongs to.
REMARK: If you are okay with an arbitrarily small amount of bias, make each die roll a magnitude larger than sum (might want BigInteger for this). Let N be the sum. Then N = k*sum + rem where rem < sum. If N is large, then rem / k -> 0, which is good. N is probabilistically large if M is large.
Algorithm psuedo code:
F(S, N):
let R[] = list of 0's of size N
if S = 0: return R[]
for 0 <= i < N
R[i] = random integer in [0, M] -- inclusive and (M >= S). M should be an order larger than S. A good pick might be M = 1000*S*N. Not sure though. M should probably be based on both S and N though or simply an outragously large number.
let Z = sum R[]
for 0 <= i < N
R[i] = (Z mod R[i]) mod (S+1)
return R[]
Java implementation:
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
public class Rand {
private final Random rand;
public Rand () {
this(new Random());
}
public Rand (Random rand) {
this.rand = rand;
}
public int[] randNums (int total, int minVal, int numRands) {
if (minVal * numRands > total) {
throw new IllegalArgumentException();
}
int[] results = randNums(total - minVal * numRands, numRands);
for (int i = 0; i < numRands; ++i) {
results[i] += minVal;
}
return results;
}
private int[] randNums (int total, int n) {
final int[] results = new int[n];
if (total == 0) {
Arrays.fill(results, 0);
return results;
}
final BigInteger[] rs = new BigInteger[n];
final BigInteger totalPlus1 = BigInteger.valueOf(total + 1L);
while (true) {
for (int i = 0; i < n; ++i) {
rs[i] = new BigInteger(256, rand);
}
BigInteger sum = BigInteger.ZERO;
for (BigInteger r : rs) {
sum = sum.add(r);
}
if (sum.compareTo(BigInteger.ZERO) == 0) {
continue;
}
for (int i = 0; i < n; ++i) {
results[i] = sum.mod(rs[i]).mod(totalPlus1).intValue();
}
return results;
}
}
public static void main (String[] args) {
Rand rand = new Rand();
Map<Integer, Integer> distribution = new TreeMap<Integer, Integer>();
final int total = 107;
final int minVal = 3;
final int n = 23;
for (int i = total - (n-1) * minVal; i >= minVal; --i) {
distribution.put(i, 0);
}
for (int i = 0; i < 100000; ++i) {
int[] rs = rand.randNums(total, minVal, n);
for (int r : rs) {
int count = distribution.get(r);
distribution.put(r, count + 1);
}
}
System.out.print(distribution);
}
}
Does this do what you need?
import java.util.Arrays;
import java.util.Random;
public class ScratchWork {
static Random rng = new Random();
public static int randomRange(int n) {
// Random integer between 0 and n-1
assert n > 0;
int r = rng.nextInt();
if(r >= 0 && r < Integer.MAX_VALUE / n * n) {
return r % n;
}
return randomRange(n);
}
public static int[] genRandoms(int n, int numberOfRandoms, int min) {
int randomArray[] = new int[numberOfRandoms];
for(int i = 0; i < numberOfRandoms; i++) {
randomArray[i] = min;
}
for(int i = min*numberOfRandoms; i < n; i++) {
randomArray[randomRange(numberOfRandoms)] += 1;
}
return randomArray;
}
public static void main(String[] args) {
int randoms[] = genRandoms(1000, 10, 30);
System.out.println(Arrays.toString(randoms));
}
}
Based on the revised requirements in the comments below.
public static int[] genRandoms(int total, int numberOfRandoms, int minimumValue) {
int[] ret = new int[numberOfRandoms];
Random rnd = new Random();
int totalLeft = total;
for (int i = 0; i < numberOfRandoms; i++) {
final int rollsLeft = numberOfRandoms - i;
int thisMax = totalLeft - (rollsLeft - 1) * minimumValue;
int thisMin = Math.max(minimumValue, totalLeft / rollsLeft);
int range = thisMax - thisMin;
if (range < 0)
throw new IllegalArgumentException("Cannot have " + minimumValue + " * " + numberOfRandoms + " < " + total);
int rndValue = range;
for (int j = 0; j * j < rollsLeft; j++)
rndValue = rnd.nextInt(rndValue + 1);
totalLeft -= ret[i] = rndValue + thisMin;
}
Collections.shuffle(Arrays.asList(ret), rnd);
return ret;
}
public static void main(String... args) throws IOException {
for (int i = 100; i <= 1000; i += 150)
System.out.println("genRandoms(" + i + ", 30, 10) = " + Arrays.toString(genRandoms(1000, 30, 10)));
}
prints
genRandoms(100, 30, 10) = [34, 13, 22, 20, 26, 12, 30, 45, 22, 35, 108, 20, 31, 53, 11, 35, 20, 11, 18, 32, 14, 30, 20, 19, 31, 31, 151, 45, 25, 36]
genRandoms(250, 30, 10) = [30, 27, 25, 34, 28, 33, 34, 82, 45, 30, 24, 26, 26, 45, 19, 18, 95, 28, 22, 30, 30, 25, 38, 11, 18, 27, 77, 26, 26, 21]
genRandoms(400, 30, 10) = [48, 25, 19, 22, 36, 65, 24, 29, 49, 24, 11, 30, 33, 41, 37, 33, 29, 36, 28, 24, 32, 12, 28, 29, 29, 34, 35, 28, 27, 103]
genRandoms(550, 30, 10) = [25, 44, 72, 36, 55, 41, 11, 33, 20, 21, 33, 19, 29, 30, 13, 39, 54, 26, 33, 30, 40, 32, 21, 31, 61, 13, 16, 51, 37, 34]
genRandoms(700, 30, 10) = [22, 13, 24, 26, 23, 61, 44, 79, 69, 25, 29, 83, 29, 35, 25, 13, 33, 32, 13, 12, 30, 26, 28, 26, 14, 21, 26, 13, 84, 42]
genRandoms(850, 30, 10) = [11, 119, 69, 14, 39, 62, 51, 52, 34, 16, 12, 17, 28, 25, 17, 31, 32, 30, 34, 12, 12, 38, 11, 32, 25, 16, 31, 82, 18, 30]
genRandoms(1000, 30, 10) = [25, 46, 59, 48, 36, 32, 29, 12, 27, 34, 33, 14, 12, 30, 29, 31, 25, 16, 34, 44, 25, 50, 60, 32, 42, 32, 13, 41, 51, 38]
IMHO, Shuffling the result improves the randomness of the distribution.
Maybe a recursive approach:
if numberOfRandoms is 1, return n
if numberOfRandoms is x+1
get a random integer (myNumber) between min and n-min*x (so that at least min is left for each of the remaining x numbers)
get the remaining x that add up to n-myNumber
This is a utility method for generating a fixed length random number.
public final static String createRandomNumber(long len) {
if (len > 18)
throw new IllegalStateException("To many digits");
long tLen = (long) Math.pow(10, len - 1) * 9;
long number = (long) (Math.random() * tLen) + (long) Math.pow(10, len - 1) * 1;
String tVal = number + "";
if (tVal.length() != len) {
throw new IllegalStateException("The random number '" + tVal + "' is not '" + len + "' digits");
}
return tVal;
}