Temp integers not resetting - java

I am creating a histogram using another class to help display it, but that is not important to my question. Let me start by showing my code below
public class DisplayHistogram {
public static void main(String[] args) {
int temp = 0;
int holder = 0;
int average;
Random rand = new Random();
Histogram x = new Histogram(1, 20);
for(int i = 0; i<=10000; i++)
{
for(int j = 0; j<=3; j++)
{
temp = rand.nextInt(20) + 1;
holder = holder + temp;
}
average = Math.round(holder / 3);
x.submit(average);
}
System.out.println(x.toString());
}
}
the problem I am having is I set the histogram to have a min of 1 and max of 20. I am generating three random integers and finding the average of the 3 and submitting it to the histogram 10,000 times. However, after the first loop of 10000, the "holder" variable doesn't reset back to 0 causing my program trying to submit a value outside of the max, and creating an error. I have attempted to set holder to 0 at the end of every loop by doing
x.submit(average);
holder = 0;
temp = 0;
However that does not help.
I have tried some of your suggestions making my code look like
import java.util.*;
public class DisplayHistogram {
public static void main(String[] args) {
Random rand = new Random();
Histogram x = new Histogram(1, 20);
for(int i = 0; i<=10000; i++)
{
int temp = 0;
int holder = 0;
int average = 0;
for(int j = 0; j<=3; j++)
{
temp = rand.nextInt(20) + 1;
holder = holder + temp;
}
average = Math.round(holder / 3);
x.submit(average);
}
System.out.println(x.toString());
}
}
However it still returns this error
Exception in thread "main" HistogramOutOfBoundsException:
*******
Submitted value 22 is outside range [1,20] of Histogram.
*******
at Histogram.submit(Histogram.java:31)
at DisplayHistogram.main(DisplayHistogram.java:19)

Write your loops like this:
for(int i = 0; i<=10000; i++)
{
holder = 0; // add this line
for(int j = 0; j<=3; j++)
{
temp = rand.nextInt(20) + 1;
holder = holder + temp;
}
average = Math.round(holder / 3);
x.submit(average);
}
System.out.println(x.toString());
}

Fixed. Was looping four times instead of three. For loop should've looked like
for(int i=0; i<=2; i++)

Short answer
Pay attention to details.
The answer you want
Unlike the other answer,
don't just initialize the holder variable every loop.
Instead, minimize the scope of the holder variable to the loop.
public static void main(String[] args)
{
int average;
Random rand = new Random();
Histogram x = new Histogram(1, 20);
for (final int trialCount = 0; trialCount <= 10000; ++trialCount)
{
int holder = 0;
for (final int sampleCount = 0; sampleCount <= 3; ++sampleCount)
{
int temp = rand.nextInt(20) + 1;
holder += temp;
}
average = Math.round(holder / 3);
x.submit(average);
}
System.out.println(x.toString());
}

Related

Random array elements

I'm very new to coding.
I'm writing this code and I'm struggling because I need to make a code that makes an array with 8 random integers and then it swaps the largest integer with the first number in the array.
When doing this though I'm getting an error and I cannot seem to fix it.
import java.util.Scanner;
import java.util.Random;
public class finalExam {
public static void main(String []args) {
Scanner input = new Scanner(System.in);
Random spinner = new Random();
int [] userInputs = new int [8];
for (int i = 0; i < userInputs.length; i++) {
userInputs[i] = spinner.nextInt(100)+1;
System.out.println(userInputs[i]);
}
int largest = userInputs[0];
for(int j = 1; j < userInputs.length; j++) {
if(userInputs[j] > largest)
largest = userInputs[j];
}
System.out.println("Your largest number is: " + largest);
int holder;
int [] arr = new int[101];
for (int m = 0; m <= arr.length; m++) {
holder = largest;
userInputs[0] = userInputs[largest];
holder = userInputs[0];
}
}
}
The error comes from the last bit of your code. userInputs[largest] is out of bound because the array is only 8 integers long (while largest can have a value of 100).
Since you need the position of the largest number, you'll have to save it in largestPosition when you identify which number is the largest, like so:
int largest = userInputs[0];
int largestPosition = 0;
for(int j = 1; j < userInputs.length; j++) {
if(userInputs[j] > largest){
largest = userInputs[j];
largestPosition = j;
}
}
That said, the loop which you used at the end also isn't needed here. You could just swap the first value of the array with the largest one using this method:
int first = userInputs[0];
userInputs[0] = largest;
userInputs[largestPosition] = first;

Java modify array elemens

Hey guys I want to write program that shifts elements in an array once to the left but I tried everything and it's not working. The code below is outputting just 0's. Can someone please tell me how I can do this. Thank you!
import java.util.Scanner;
public class StudentScores {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
final int SCORES_SIZE = 4;
int[] oldScores = new int[SCORES_SIZE];
int[] newScores = new int[SCORES_SIZE];
int i;
for (i = 0; i < oldScores.length; ++i) {
oldScores[i] = scnr.nextInt();
}
int temp = newScores[0];
for (i = 0; i < oldScores.length - 1; ++i) {
newScores[i] = newScores[i+1];
}
temp = newScores[oldScores.length - 1];
for (i = 0; i < newScores.length; ++i) {
System.out.print(newScores[i] + " ");
}
System.out.println();
}
}````
As pointed out by people in comments, you seem to be assigning newScores[] to newScores[] value(an uninitialized array has all values set to 0):
int temp = newScores[0]; // Should be oldScores[0]
// ...
newScores[i] = newScores[i+1]; // Should be oldScores[i+1]
You need to have oldScores[] values on RHS. Since you only want to shift by one place, I think extra array is unnecessary. You can do it in place like this:
int temp = oldScores[0];
for (i = 0; i < oldScores.length - 1; ++i) {
oldScores[i] = oldScores[i + 1];
}
oldScores[oldScores.length - 1] = temp;

How to plot out my two vector lists of data on jfreechart

Hi I am trying to realize an algorithm and realise the function: when one of the molecule numbers become 0, the whole while loop will end and will automatically proceed to the next chart-drawing step with JFreeChart.
Right now, after using "return", eclipse show no error and process the main method completely. However, i cannot see my chart showing out. Wondering if any steps goes wrong.
I want to show the molecule number of different species at different times. Each specie will represent a new line.
SoI create a new chart
static JPanel chartPanel;
and in the constructor I set something like(just follow online tutorial)
super("Line Chart of molecule numbers at different times");
add(chartPanel, BorderLayout.CENTER);
setSize(640, 480);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
in the main method I want to show my number entered and calculated in a line chart (didn't create another class as afraid of null pointer exception)
public static void main(String args[]) throws Exception {
//input the number of species
System.out.println("Enter the number of species:");
int n = sc.nextInt();
//input the number of reactions
System.out.println("Enter the number of reactions:");
int m = sc.nextInt();
//
int[][]matrixPre = new int[m][n];
enterMatrixDataPre(sc, matrixPre, m, n);
printMatrixPre(matrixPre, m, n);
//convert the 2d int to 2d double
double [][] matrixPre2 = new double[m][n];
for(int i = 0; i <m; i++)
{
for(int j = 0; j < n; j++)
matrixPre2[i][j] = (double) matrixPre[i][j];
}
RealMatrix PreMatrix = new Array2DRowRealMatrix(matrixPre2);
// remember to add space key when doing the typing
int[][]matrixPost = new int[m][n];
enterMatrixDataPost(sc, matrixPost, m, n);
printMatrixPost(matrixPost, m, n);
//convert the 2d int to 2d double
double [][] matrixPost2 = new double[m][n];
for(int i = 0; i <m; i++)
{
for(int j = 0; j < n; j++)
matrixPost2[i][j] = (double) matrixPost[i][j];
}
RealMatrix PostMatrix = new Array2DRowRealMatrix(matrixPost2);
//
RealMatrix matrixSubtract = PreMatrix.subtract(PostMatrix);
System.out.println("So the transpose matrix after subtraction is:\t"+matrixSubtract.transpose());
//input the default maxium time of the whole reaction
System.out.println("Enter the maxium time of the whole reaction:");
double Tmax =sc.nextDouble();
//input the name of all the species
System.out.println("Enter the name of all species");
String[] strs=new String[n];
for(int i = 0; i< n; i++) {
strs[i]=sc.nextLine();
}
//input the rate constant of all the reactions(the coefficient), must be a double
System.out.println("Enter the rate constant of each reaction:");
Double[] rate=new Double[m];
for(int r = 0; r< m; r++) {
rate[r]=sc.nextDouble();
}
//
Vector<Double> timeList = new Vector<Double>(0);
Vector<int[]> allStateList = new Vector<int[]>(0);
timeList.add(newTime);
//input the initial states of numbers of molecules
System.out.println("Enter the initial molecule numbers of all species:");
int[]state = new int[n];
for (int i = 0; i< n; i++)
{
state[i]=sc.nextInt();
}
allStateList.add(state);
while(newTime<Tmax) {
for(int loopIndex =0; loopIndex<allStateList.size(); loopIndex++) {
// calculate the hazard for each reaction and the general hazard
double[] h = new double[m];
H = 0;
try {
for(int i =0; i<m; i++) {
for(int j =0; j<n; j++) {
h[i]=rate[i]*CombinatoricsUtils.binomialCoefficientDouble(allStateList.get(loopIndex)[j],(int)(PreMatrix.getRowVector(i).toArray()[j]));
H +=h[i];
}
}
}
catch(NumberIsTooLargeException exceptionn) {
System.out.println("One of the species has been exhausted and there is no next firing");
return;
}
System.out.println("So the general hazard is:"+H);
// select a random reaction time
Random random = new Random();
double tau = (1*Math.log(1/random.nextDouble()))/H;
System.out.println("So the random reaction time is"+tau);
//put the newTime
newTime = timeList.get(loopIndex)+tau;
System.out.println("So the new reaction time is:" + newTime);
timeList.add(newTime);
//select a random reaction j
Random random2 = new Random();
int index =0;
for (int i=0; i<m; i++) {
if(h[i]>random2.nextDouble()*H)
index =i;
}
System.out.println("So the next simulated event is:"+index);
//Update the state
double[] vectorDoubleArray = matrixSubtract.transpose().getColumnVector(index).toArray();
int[] intArray = new int[n];
for (int i=0; i<n; i++) {
intArray[i] = (int) vectorDoubleArray[i];
}
int[] newState = new int[n];
int newS =0;
for (int p =0; p<n; p++){
newS= intArray[p]+allStateList.get(loopIndex)[p];
newState[p]=newS;
}
System.out.println("Right now the molecule number of all species are:"+Arrays.toString(newState));
allStateList.add(newState);
}
//close the scanner
sc.close();
}
}
with all the preparation done, I want to print the number of two vector list, timeList and allStateList using jfreechart
String chartTitle = "Line chart of molecule numbers";
String categoryAxisLabel = "time";
String valueAxisLabel = "molecule numbers";
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
int[] eachSpecieState = new int[allStateList.size()];
for (int i =0; i<n; i++) {
for (int j=0; j<allStateList.size(); j++) {
eachSpecieState[i]=allStateList.get(j)[i];
}
}
for (int i =0; i<m;i++) {
String series[]= new String[m];
series[i]=""+strs[i];
for(int k =0; k<n;k++) {
for (int j=0; j<allStateList.size(); j++) {
eachSpecieState[k]=allStateList.get(j)[k];
dataset.addValue(eachSpecieState[k],series[i+1],""+timeList.get(j));
}
}
}
JFreeChart chart = ChartFactory.createLineChart(chartTitle,
categoryAxisLabel, valueAxisLabel, dataset);
chartPanel = new ChartPanel(chart);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new StochasticProcess().setVisible(true);
}
});
however no chart shows. As I am not that good in swing language, can anybody help me point out if any parts go wrong?(the last plot and chart part of code) Thanks~
One of the simplest solutions would be to just add the break condition in a simple for Loop
for(int i =0; i < m && allStateList.get(loopIndex)[j]!=0; i++)
{
}
I've to admit that, without a specific knowledge, it's not easy for me to understand and debug the whole code; but, as a general idea, I saw that, a certain point, you wrote:
***while(allStateList.get(loopIndex)[j]==0) {
break;
}***
In my opinion, as general rule, if you want to check a condition, you must use an IF statement, e.g.: something like if(condition==true) { break; }
I think it will be useful for you.
So to solve the problem, I created a list of XYSeries and add a new name to each XYSeries inside the loop. After adding values to each XYSeries, use another loop to add them into the XYCollection.The question was asked a week ago and lots of parts have been modified to get final result.I will post the new version of whole code below to set as an example.
import java.util.*;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.lang.Math;
import org.apache.commons.math3.exception.NumberIsTooLargeException;
import org.apache.commons.math3.linear.Array2DRowRealMatrix;
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.util.CombinatoricsUtils;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.block.BlockBorder;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
The main method part is here:
public class StochasticSimulationProcess extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
static int matrixPre[][];
static int matrixPost[][];
static int m;// the number of reactions
static int n;// the number of species
static double[] h;// the hazard for each reaction
static double[] rate;
static int[] state;
static double newTime;
static int max;
static double Tmax;// the overall reaction time
Vector<Double> timeList;
static double H;
Vector<int[]> allStateList;
static String[] strs;
XYSeriesCollection dataset;
public StochasticSimulationProcess(String s) {
super(s);
newTime = 0;
}
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws Exception {
// input the number of species
System.out.println("Enter the number of species:");
int n = sc.nextInt();
// input the number of reactions
System.out.println("Enter the number of reactions:");
int m = sc.nextInt();
//
int[][] matrixPre = new int[m][n];
enterMatrixDataPre(sc, matrixPre, m, n);
printMatrixPre(matrixPre, m, n);
// convert the 2d int to 2d double
double[][] matrixPre2 = new double[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
matrixPre2[i][j] = (double) matrixPre[i][j];
}
RealMatrix PreMatrix = new Array2DRowRealMatrix(matrixPre2);
// remember to add space key when doing the typing
int[][] matrixPost = new int[m][n];
enterMatrixDataPost(sc, matrixPost, m, n);
printMatrixPost(matrixPost, m, n);
// convert the 2d int to 2d double
double[][] matrixPost2 = new double[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
matrixPost2[i][j] = (double) matrixPost[i][j];
}
RealMatrix PostMatrix = new Array2DRowRealMatrix(matrixPost2);
//
RealMatrix matrixSubtract = PreMatrix.subtract(PostMatrix);
System.out.println("So the transpose matrix after subtraction is:\t" + matrixSubtract.transpose());
// input the default maxium time of the whole reaction
System.out.println("Enter the maxium time of the whole reaction:");
double Tmax = sc.nextDouble();
// input the name of all the species
System.out.println("Enter the name of all species");
String[] strs = new String[n];
for (int i = 0; i < n; i++) {
strs[i] = sc.nextLine();
}
// input the rate constant of all the reactions(the coefficient), must be a
// double
System.out.println("Enter the rate constant of each reaction:");
Double[] rate = new Double[m];
for (int r = 0; r < m; r++) {
rate[r] = sc.nextDouble();
}
//
Vector<Double> timeList = new Vector<Double>(0);
Vector<int[]> allStateList = new Vector<int[]>(0);
timeList.add(newTime);
// input the initial states of numbers of molecules
System.out.println("Enter the initial molecule numbers of all species:");
int[] state = new int[n];
for (int i = 0; i < n; i++) {
state[i] = sc.nextInt();
}
allStateList.add(state);
timeLoop:
while (newTime < Tmax) {
for (int loopIndex = 0; loopIndex < allStateList.size(); loopIndex++) {
// calculate the hazard for each reaction and the general hazard
double[] h = new double[m];
H = 0;
try {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
h[i] = rate[i] * CombinatoricsUtils.binomialCoefficientDouble(
allStateList.get(loopIndex)[j], (int) (PreMatrix.getRowVector(i).toArray()[j]));
H += h[i];
}
}
}
catch (NumberIsTooLargeException exceptionn) {
System.out.println("One of the species has been exhausted and there is no next firing");
break timeLoop;
}
System.out.println("So the general hazard is:" + H);
// select a random reaction time
Random random = new Random();
double tau = (1 * Math.log(1 / random.nextDouble())) / H;
System.out.println("So the random reaction time is" + tau);
// put the newTime
newTime = timeList.get(loopIndex) + tau;
System.out.println("So the new reaction time is:" + newTime);
timeList.add(newTime);
// select a random reaction j
Random random2 = new Random();
int index = 0;
double hi =0;
for (int i = 0; i < m; i++) {
hi +=h[i];
if (hi >= random2.nextDouble() * H) {
index = i;
break;
}
}
System.out.println("So the next simulated event is:" + index);
// Update the state
double[] vectorDoubleArray = matrixSubtract.transpose().getColumnVector(index).toArray();
int[] intArray = new int[n];
for (int i = 0; i < n; i++) {
intArray[i] = (int) vectorDoubleArray[i];
}
int[] newState = new int[n];
int newS = 0;
for (int p = 0; p < n; p++) {
newS = intArray[p] + allStateList.get(loopIndex)[p];
newState[p] = newS;
}
System.out.println("Right now the molecule number of all species are:" + Arrays.toString(newState));
allStateList.add(newState);
}
// close the scanner
sc.close();
}
XYSeriesCollection dataset = new XYSeriesCollection();
XYSeries[] species = new XYSeries[n];
for (int j =0; j<n; j++) {
species[j]=new XYSeries(""+strs[j]+Integer.toString(j));
}
for (int j =0; j<n; j++) {
for (int k=0; k< allStateList.size();k++) {
species[j].add(timeList.get(k).doubleValue(), allStateList.get(k)[j]);
}
dataset.addSeries(species[j]);
}
// plot out the graph
System.out.println("TEST");
JFreeChart chart = ChartFactory.createXYLineChart(
"SSA Modeling",
"time",
"Number of Molecules",
dataset,
PlotOrientation.VERTICAL,
true,
true,
false
);
ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
chartPanel.setBackground(Color.white);
XYPlot plot = chart.getXYPlot();
XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
for (int j =0; j<n;j++){
renderer.setSeriesPaint(j, Color.RED);
renderer.setSeriesStroke(j, new BasicStroke(2.0f));
}
plot.setRenderer(renderer);
plot.setBackgroundPaint(Color.white);
plot.setRangeGridlinesVisible(false);
plot.setDomainGridlinesVisible(false);
chart.getLegend().setFrame(BlockBorder.NONE);
chart.setTitle(new TextTitle("Stochastic Simulation Algorithm",
new Font("Serif", Font.BOLD, 18)
)
);
SwingUtilities.invokeLater(() -> {
StochasticSimulationProcess ex = new StochasticSimulationProcess("SSA");
ex.setContentPane(chartPanel);
ex.pack();
ex.setLocationRelativeTo(null);
ex.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ex.setVisible(true);
});
}
public static void enterMatrixDataPre(Scanner sc, int[][] matrixPre, int m, int n) {
System.out.println("Enter Matrix pre data");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
matrixPre[i][j] = sc.nextInt();
}
}
}
public static void printMatrixPre(int[][] matrixPre, int m, int n) {
System.out.println("Matrix pre is:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrixPre[i][j] + "\t");
}
System.out.println();
}
}
public static void enterMatrixDataPost(Scanner sc, int[][] matrixPost, int m, int n) {
System.out.println("Enter Matrix post data");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
matrixPost[i][j] = sc.nextInt();
}
}
}
public static void printMatrixPost(int[][] matrixPost, int m, int n) {
System.out.println("Matrix post is:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrixPost[i][j] + "\t");
}
System.out.println();
}
}
}
to change colours randomly, as the number of XYSeries that represent species are undefined, so I choose the random set hgb method as they can be combined randomly as long as the value is between 0-255, so I change the line of code as :
renderer.setSeriesPaint(j, Color.getHSBColor(0 + (float)(Math.random() * ((255 - 0) + 1)), 0 + (float)(Math.random() * ((255 - 0) + 1)), 0 + (float)(Math.random() * ((255 - 0) + 1))));

Java Radomly Generating Numbers Error

I am writing this code to run 10000000 times and randomly generate a number and pick the most oftenly generated number, but the results do not seem random. The I have written is
public class Randomizer {
public static int[][] numbers = new int[45][2];
public static int maxN = 0;
public static int finalChoice;
public static void main(String[] args){
int arithmoi[] = new int[5];
for(int i =0; i < 5; i++){
arithmoi[i] = randomizer(1000000, 45);
System.out.println("A "+i+": "+arithmoi[i]);
}
int extra_num = randomizer(1000000, 20);
System.out.println("\nT: "+extra_num);
}
public static int randomizer(int times, int amount){
int[][] numbers = new int[amount][2];
for(int i = 0; i < amount; i++){
numbers[i][0] = i + 1;
numbers[i][1] = 0;
}
for(int i = 0; i < times; i ++){
int rnd = (int)(Math.random() * amount + 1);
for(int j = 0; j < amount; j++){
if(rnd == numbers [j] [0]){
numbers[j][1] ++ ;
break;
}
}
}
for(int i = 0; i < amount; i++){
if(maxN < numbers[i][1]){
finalChoice = numbers[i][0];
maxN = numbers[i][1];
}
}
return finalChoice;
}
}
The result that it gives me are A 0: 36
A 1: 36
A 2: 36
A 3: 36
A 4: 29
T: 14, A 0: 26
A 1: 44
A 2: 44
A 3: 44
A 4: 44
T: 4
and similar. What could the problem be?
import java.util.Random;
public class Randomizer {
public static int[][] numbers = new int[45][2];
public static int maxN = 0;
public static int finalChoice;
public static void main(String[] args){
int arithmoi[] = new int[5];
for(int i =0; i < 5; i++){
arithmoi[i] = randomizer(1000000, 45);
System.out.println("A "+(i+1)+": "+arithmoi[i]);
}
int extra_num = randomizer(1000000, 20);
System.out.println("\nT: "+extra_num);
}
public static int randomizer(int times, int amount){
int[][] numbers = new int[amount][2];
Random randomGenerator = new Random();
for(int i = 0; i < amount; i++){
numbers[i][0] = i + 1;
numbers[i][1] = 0;
}
for(int i = 0; i < times; i ++){
int rnd = randomGenerator.nextInt(amount);
for(int j = 0; j < amount; j++){
if(rnd == numbers [j] [0]){
numbers[j][1] ++ ;
break;
}
}
}
for(int i = 0; i < amount; i++){
if(maxN < numbers[i][1]){
finalChoice = numbers[i][0];
maxN = numbers[i][1];
}
}
return finalChoice;
}
}
The new code has still the same results(I used the Random Class)
You should use Java's Random class (java.util.Random) instead of writing your own. It is written by experts and has improved over many years as it is used and therefore tested by millions. It has been proven to generate pseudo-random numbers that do not have any particular pattern.
Writing your own pseudo-random generator would not be straight forward as there are a lot of factors involved.
Here is an example of its use:
Random random = new Random();
int maxIterations = 10000000;
int maxRandomValue = 100;
for(int i=0; i< maxIterations; i++)
{
System.out.println("Next random value: " + random.nextInt(maxRandomValue));
}
I think the main problem of you code it the way you tired to solve the task.
First of int[][] numbers = new int[amount][2]; holds redundant information because numbers[*][0] hold the position. Since numbers[i][1] holds the result for position i + 1 you can reduce the structure to int[amount].
Unlike other languages java defines the initial state of an int array to be always zero, so you do not need the first loop.
Your task is to let it rain on a line and check after n rounds, how many raindrops hit a certain spot/position.
It is okay to loop n times but since rnd.nextInt(amount) already gives you the spot the raindrop landed on, you do not have to iterate to find it.
for(int i = 0; i < times; i++) {
number[rnd.nextInt(amount)]++;
}
This will simulate the raindrops, but to get the proper random, you should initialize private static Random rnd = new Random() at class level and not at method level.
I hope this will help to solve your task.

Making an array with random values

I am trying to fill an array with random int values from 0 to 6. To control my code i am printing out the random values I generate. I try to exclude duplicates in the nested if-statement inside the for-loop, but when I run the code I get my seven values, but some of them are still duplicated. Can someone please help me?
Here is my code:
import java.util.Random;
public class TesterArrayer
{
public static void main(String[] args)
{
int size = 7;
Random randomNumber = new Random();
int randomArray[] = new int[size];
for(int x =0; x < size; x++)
{
int randomValue = randomNumber.nextInt(6);
if (randomValue != randomArray[x])
{
randomArray[x] = randomValue;
}
}//End for-loop
for (int y = 0; y < size; y++)
{
System.out.println(randomArray[y]);
}
}
}
public static void main(String[] args) {
int size = 7;
boolean add = true;
int counter = 0;
Random randomNumber = new Random();
int randomArray[] = new int[size];
for(int j = 0; j < size; j++)
{
randomArray[j] = -1;
}
while (counter < size) {
add = true;
int randomValue = randomNumber.nextInt(7);
for (int x = 0; x < size; x++) {
if (randomValue == randomArray[x]) {
add = false;
}
}// End for-loop
if(add)
{
randomArray[counter] = randomValue;
counter++;
}
}
for (int y = 0; y < size; y++) {
System.out.println(randomArray[y]);
}
}
Try something like this. You don't want to add the number unless it's not already in the list. Also for your random you need 7 instead of 6 if you want 0-6.
This code will fill your array with 0-6 not repeating any numbers.
If you only want the numbers 0..length-1 in random order you can do something like this:
int length = 7;
List<Integer> list = new ArrayList<>(length);
for(int i=0; i<length; i++){
list.add(Integer.valueOf(i));
}
//list is now in order, need to randomly shuffle it
Collections.shuffle(list);
//now list is shuffled, convert to array
int array[] = new int[length];
for(int i=0; i<length; i++){
array[i] = list.get(i);
}
Change minLimit, maxLimit and noOfItems to get random Numbers
public class RandomIntegers
{
public static final Random random = new Random();
public static final int maxLimit = 6;
public static final int minLimit = 0;
public static final int noOfItems = 7;
public static void main( String[] args )
{
Set<Integer> uniqueRandomIntegerSet = new HashSet< Integer >();
while(uniqueRandomIntegerSet.size() < noOfItems)
uniqueRandomIntegerSet.add( random.nextInt( maxLimit - minLimit + 1 ) + minLimit );
Integer[] randomUniqueIntegers = uniqueRandomIntegerSet.toArray( new Integer[0] );
}
}
As you should use a more optimal data structure for this approach, as mentioned in the other answer and comments, you can still accomplish this with an array of course. As you have defined the problem you would need to change int randomValue = randomNumber.nextInt(6); to int randomValue = randomNumber.nextInt(7); or else this will loop infinitely as there is no possible way to have no duplicates in a size 7 array with only 6 values.
You can do something like this to modify your code for it to work:
boolean flag = false;
for(int x = 0; x < size; x++)
{
int randomValue = randomNumber.nextInt(7);
for (int i = 0; i < x; i++)
{
if (randomValue == randomArray[i])
{
//randomArray[x] = randomValue;
flag = true;
x--;
}
}
if (!flag)
randomArray[x] = randomValue;
flag = false;
}//End for-loop
This code is simply flagging when it sees a duplicate value in the array already and will skip this value and decrement the x value so that it will create another random value for this spot in the array.
byte[] source = new byte[1024];
Random rand = new Random();
rand.nextBytes(source);

Categories

Resources