Uniformly distributed random prime generator - java

public class RandomPrime
{
public static void main(String[] args)
{
int squareNumber = readInput();
BigInteger randomPrimes[] = generateRandomPrime(squareNumber);
}
public static BigInteger[] generateRandomPrime(int num)
{
int numberOfPrimes = (int) Math.sqrt(num);
int start, end, step;
start = 1;
step = num / numberOfPrimes;
end = start + (step - 1);
/*int randomPrimes[] = new int[numberOfPrimes];*/
BigInteger randomPrimes[] = new BigInteger[numberOfPrimes];
Random rand = new Random();
int tempPrime;
for (int i = 0; i < numberOfPrimes; i++) {
while (true) {
tempPrime = rand.nextInt(end - start) + start;
if (isPrime(tempPrime)) {
randomPrimes[i] = new BigInteger(tempPrime + "");
System.out.println("Random prime is "+tempPrime);
break;
}
}
start = end + 1;
end = end + (step - 1);
System.out.println("OUTER WHILE");
}
return randomPrimes;
}
public static boolean isPrime(int num)
{
for (int i = 2; i < num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static int readInput()
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num = 0, sqrt;
while (true) {
System.out.println("Enter a square number");
try {
num = Integer.parseInt(br.readLine());
sqrt = (int) Math.sqrt(num);
if (num == (sqrt * sqrt)) {
System.out.println("Entered valid square num is "+num);
break;
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Entered a non square number.So");
}
return num;
}
}
This is the code I wrote. I want to generate uniformly distributed random prime. This code works.
My problem: I am not sure whether my code generated uniformly distributed primes. Is it correct? If not, how do I solve it?

Related

NZEC error for ACODE spoj

I am solving the Acode problem of SPOJ.It is a simple Dp problem here
This is my solution:
//http://www.spoj.com/problems/ACODE/
import java.util.Scanner;
//import java.util.Math;
public class Acode {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String encodedString = sc.next();
while (!encodedString.equals("0")) {
long number = numOfDecodings(encodedString);
System.out.println(number);
encodedString = sc.next();
}
return;
}
public static long numOfDecodings(String encodedString)
{
int lengthOfString = encodedString.length();
long decode[] = new long[lengthOfString];
decode[0] = 1;
if (isCurrentTwoDigitsValid(encodedString, 1)) {
decode[1] = 2;
} else {
decode[1] = 1;
}
for (int i=2; i<lengthOfString; i++) {
if (isCurrentTwoDigitsValid(encodedString, i)) {
decode[i] = decode[i-2] + decode[i-1];
} else {
decode[i] = decode[i-1];
}
}
return decode[lengthOfString-1];
}
public static boolean isCurrentTwoDigitsValid(String encodedString, int startIndex)
{
char c1 = encodedString.charAt(startIndex);
char c2 = encodedString.charAt(startIndex-1);
if ( (c2=='1') || (c2=='2' && c1<='6')) {
return true;
} else {
return false;
}
}
}
But I am getting an NZEC error when I try to submit it.I tested it for large values too and it is not breaking.I am not understanding how else to improve it.
When input size is 1 you get an error in
if (isCurrentTwoDigitsValid(encodedString, 1)) {
decode[1] = 2;
} else {
decode[1] = 1;
}
because of accessing out of the decode array bounds.
You treat 0 as a valid number, but it's not. For example, the correct answer for input "10" is 1, not 2.

Limit execution time of my Method

The following is my Brute force code for Sudoku:
public abstract class SudokuBoard
{
protected int ROWS = 9;
protected int COLS = 9;
int solutionsCounter;
double startTime;
double endTime;
String[] data = new String[8];
int puzzleNum = countTotalRows();
// data accessors
public abstract int get(int r, int c);
public abstract void set(int r, int c, int v);
// specific constraints checker, returns true even if the values are not complete
abstract boolean isRowCompatible(int r, int c);
abstract boolean isColCompatible(int r, int c);
abstract boolean isBoxCompatible(int r, int c);
// returns true if element S[r,c] is compatible, even if some values arount it are not filled
public boolean isCompatible(int r, int c)
{
for (int i=0; i<ROWS; i++)
for (int j=0; j<COLS; j++)
if(! (isRowCompatible(r, c) && isColCompatible(r, c) && isBoxCompatible(r, c)))
return false;
return true;
}
// this is the one called to solve the sudoku
public void solve()
{
//convert to seconds
startTime = System.nanoTime() / 1000000000.0;
solve(1,1);
}
// function to incorporate clues
public void incorporateClues(int[] clues)
{
for (int i=0; i<clues.length; i++)
set(clues[i]/100, (clues[i]%100)/10, clues[i]%10);
}
// the recursive backtracking function that does the hardwork
void solve(int r, int c)
{
while (((System.nanoTime() / 1000000000.0) - startTime) < 10) {
System.out.println("Time: " + ((System.nanoTime() / 1000000000.0) - startTime));
if (r<=9 && c<=9)
{
if (get(r,c) == 0)
{
for (int v=1; v<=COLS; v++)
{
set(r,c,v);
if (isCompatible(r,c))
solve((c==9)?(r+1):r, (c==9)?1:(c+1));
}
set(r, c, 0);
}
else
solve((c==9)?(r+1):r, (c==9)?1:(c+1));
}
else
{
solutionsCounter = solutionsCounter + 1;
//convert to seconds
endTime = System.nanoTime() / 1000000000.0;
// print();
}
}
}
// sample display function
void print()
{
for(int i=1; i<=ROWS; i++)
{
for (int j=1; j<=COLS; j++)
System.out.print(get(i,j));
System.out.println();
}
System.out.println("count: " + solutionsCounter);
}
void saveData (String[] data) throws java.io.IOException
{
try
{
java.io.BufferedWriter outfile = new java.io.BufferedWriter(new java.io.FileWriter("15-clue_results.csv", true));
for (int i = 0; i < data.length; i++) {
outfile.write(String.valueOf(data[i]));
outfile.append(',');
}
outfile.append('\n');
outfile.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
static int countTotalRows () {
int count = 0;
try
{
java.io.BufferedReader bufferedReader = new java.io.BufferedReader(new java.io.FileReader("15-clue_results.csv"));
String input;
while((input = bufferedReader.readLine()) != null)
{
count = count + 1;
}
} catch (java.io.IOException e) {
e.printStackTrace();
}
return count;
}
public static void main(String []arg)
{
int numClues;
try {
java.io.BufferedReader csvFile = new java.io.BufferedReader(new java.io.FileReader("clue_set"));
String dataRow;
while ((dataRow = csvFile.readLine()) != null) {
SudokuBoard board = new SB_IntMatrix();
String[] stringSet = new String[15];
int[] PUZZLE1 = new int[15];
board.puzzleNum = board.puzzleNum + 1;
stringSet = dataRow.split(" ");
for (int i = 0; i < stringSet.length; i++) {
PUZZLE1[i] = Integer.parseInt(stringSet[i]);
}
board.incorporateClues(PUZZLE1);
for (int i = 0; i < 1; i++) {
board.solutionsCounter = 0;
board.solve();
board.data[0] = Integer.toString(board.puzzleNum);
board.data[1] = dataRow;
board.data[2] = Integer.toString(board.solutionsCounter);
board.data[3 + i] = Double.toString(board.endTime - board.startTime);
}
try
{
board.saveData(board.data);
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
csvFile.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}
The requirement is to limit the solving time of solve(int r, int c) to only 1 hour.
To do this, I tried to put it inside a while loop while (((System.nanoTime() / 1000000000.0) - startTime) < 10) . The number 10 is to just test the code.
I understand that I looped it only 5 times in main method but, it resets back to 0 always and never stops and exceeds the limit of my loop in main.
You should use a Future:
final ExecutorService executor = Executors.newFixedThreadPool(4);
final Future<Boolean> future = executor.submit(() -> {
// Call solve here
return true;
});
future.get(60, TimeUnit.MINUTES); // Blocks
You can do something like:
Init the start date:
LocalDateTime startDateTime = LocalDateTime.now();
And check if 1 hour has elapsed:
LocalDateTime toDateTime = LocalDateTime.now();
if (Duration.between(startDateTime, toDateTime).toHours() > 0) {
// stop the execution
}

Failed to make my ArrayList Thread-Safe. Exception in thread "main" java.lang.ClassCastException: What is wrong?

I decided to optimize the piece of code below but encounter with problem. I tried to change the ArrayList to thread-safe collection by using this discussion but unfortunately something went wrong. The code is compiling but throw the exception.
Exception in thread "main" java.lang.ClassCastException:
java.util.Collections$SynchronizedRandomAccessList cannot be cast to
java.util.ArrayList at
bfpasswrd_multi.PasswordCracker.doItMulti(PasswordCracker.java:73) at
bfpasswrd_multi.PasswordCracker.runMulti(PasswordCracker.java:60) at
bfpasswrd_multi.Test.main(Test.java:16)
Please, tell me what is wrong ?
package bfpasswrd_multi;
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
System.out.print("Type password to be cracked: ");
#SuppressWarnings("resource")
String input = new Scanner(System.in).nextLine();
PasswordCracker cracker = new PasswordCracker();
System.out.println("Multithreaded");
cracker.runMulti(input);
cracker = new PasswordCracker();
System.out.println("Finished...");
}
}
package bfpasswrd_multi;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class PasswordCracker
{
String passwordToCrack;
public boolean passwordFound;
int min;
int max;
StringBuffer crackedPassword;
public void prepare(String text)
{
passwordToCrack = text;
passwordFound = false;
min = 48;
max = 57; // http://ascii.cl/
crackedPassword = new StringBuffer();
crackedPassword.append((char) (min - 1));
}
public void result()
{
System.out.println("Cracked Password is: " + crackedPassword.toString());
}
public void incrementString(StringBuffer toCrack, int min, int max)
{
toCrack.setCharAt(0, (char) ((int) toCrack.charAt(0) + 1));
for (int i = 0; i < toCrack.length(); i++)
{
if (toCrack.charAt(i) > (char) max)
{
toCrack.setCharAt(i, (char) min);
if (toCrack.length() == i + 1)
{
toCrack.append((char) min);
}
else
{
toCrack.setCharAt(i + 1, (char) ((int) toCrack.charAt(i + 1) + 1));
}
}
}
}
public void runMulti(String text)
{
prepare(text);
double time = System.nanoTime();
doItMulti();
time = System.nanoTime() - time;
System.out.println(time / (1000000000));
result();
}
public void doItMulti()
{
int cores = Runtime.getRuntime().availableProcessors();
ArrayList<Future<?>> tasks ; // How do I make my ArrayList Thread-Safe? Another approach to problem in Java?
// https://stackoverflow.com/questions/2444005/how-do-i-make-my-arraylist-thread-safe-another-approach-to-problem-in-java
tasks = (ArrayList<Future<?>>) Collections.synchronizedList(new ArrayList<Future<?>>(cores));
// ArrayList<Future<?>> tasks = new ArrayList<>(cores);
ExecutorService executor = Executors.newFixedThreadPool(cores);
final long step = 2000;
for (long i = 0; i < Long.MAX_VALUE; i += step)
{
while(tasks.size() > cores)
{
for(int w = 0; w < tasks.size();w++)
{
if(tasks.get(w).isDone())
{
tasks.remove(w);
break;
}
}
try
{
Thread.sleep(0);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
{
final long j = i;
if (passwordFound == false)
{
tasks.add(executor.submit(new Runnable()
{
public void run()
{
long border = j + step;
StringBuffer toCrack = new StringBuffer(10);
toCrack.append(constructString3(j, min, max));
for (long k = j; k < border; k++)
{
incrementString(toCrack, min, max);
boolean found = toCrack.toString().equals(passwordToCrack);
if (found)
{
crackedPassword = toCrack;
passwordFound = found;
break;
}
}
}
}));
}
else
{
break;
}
}
}
executor.shutdownNow();
}
public String constructString3(long number, long min, long max)
{
StringBuffer text = new StringBuffer();
if (number > Long.MAX_VALUE - min)
{
number = Long.MAX_VALUE - min;
}
ArrayList<Long> vector = new ArrayList<Long>(10);
vector.add(min - 1 + number);
long range = max - min + 1;
boolean nextLetter = false;
for (int i = 0; i < vector.size(); i++)
{
long nextLetterCounter = 0;
while (vector.get(i) > max)
{
nextLetter = true;
long multiplicator = Math.abs(vector.get(i) / range);
if ((vector.get(i) - (multiplicator * range)) < min)
{
multiplicator -= 1;
}
vector.set(i, vector.get(i) - (multiplicator * range));
nextLetterCounter += multiplicator;
}
if (nextLetter)
{
vector.add((long) (min + nextLetterCounter - 1));
nextLetter = false;
}
text.append((char) vector.get(i).intValue());
}
return text.toString();
}
}
Many thanks in advance !
The issue that you're seeing is with this line:
tasks = (ArrayList<Future<?>>) Collections.synchronizedList(new ArrayList<Future<?>>(cores));
Collections.synchronizedList doesn't return an ArrayList; it returns some subclass of List - java.util.Collections$SynchronizedRandomAccessList to be exact - and I don't know anything about that class other than it's a List, but it's not an ArrayList.
The easy solution to this is to declare tasks to be a List<Future<?>>:
List<Future<?>> tasks =
Collections.synchronizedList(new ArrayList<Future<?>>(cores));
Dear community members thanks you for your comments. It seems that now my safe-thread list is working. For the people who interesting in solution I will submit the resolved code below. Also, probably I should mention that I rename task
to futures, please pay attention. Once again everybody thanks !
package bfpasswrd_multi;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class PasswordCracker
{
String passwordToCrack;
public boolean passwordFound;
int min;
int max;
StringBuffer crackedPassword;
public void prepare(String text)
{
passwordToCrack = text;
passwordFound = false;
min = 48;
max = 57; // http://ascii.cl/
crackedPassword = new StringBuffer();
crackedPassword.append((char) (min - 1));
}
public void result()
{
System.out.println("Cracked Password is: " + crackedPassword.toString());
}
public void incrementString(StringBuffer toCrack, int min, int max)
{
toCrack.setCharAt(0, (char) ((int) toCrack.charAt(0) + 1));
for (int i = 0; i < toCrack.length(); i++)
{
if (toCrack.charAt(i) > (char) max)
{
toCrack.setCharAt(i, (char) min);
if (toCrack.length() == i + 1)
{
toCrack.append((char) min);
}
else
{
toCrack.setCharAt(i + 1, (char) ((int) toCrack.charAt(i + 1) + 1));
}
}
}
}
public void runMulti(String text)
{
prepare(text);
double time = System.nanoTime();
doItMulti();
time = System.nanoTime() - time;
System.out.println(time / (1000000000));
result();
}
public void doItMulti()
{
int cores = Runtime.getRuntime().availableProcessors();
// ArrayList<Future<?>> task; // HOW IT WAS
//
// tasks = (ArrayList<Future<?>>) Collections.synchronizedList(new ArrayList<Future<?>>(cores)); // HOW IT WAS
List<Future<?>> futures ; // THE SOLUTION
futures = Collections.synchronizedList(new ArrayList<Future<?>>(cores)); // THE SOLUTION
// ArrayList<Future<?>> tasks = new ArrayList<>(cores);
ExecutorService executor = Executors.newFixedThreadPool(cores);
final long step = 2000;
for (long i = 0; i < Long.MAX_VALUE; i += step)
{
while(futures.size() > cores)
{
for(int w = 0; w < futures.size();w++)
{
if(futures.get(w).isDone())
{
futures.remove(w);
break;
}
}
try
{
Thread.sleep(0);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
{
final long j = i;
if (passwordFound == false)
{
futures.add(executor.submit(new Runnable()
{
public void run()
{
long border = j + step;
StringBuffer toCrack = new StringBuffer(10);
toCrack.append(constructString3(j, min, max));
for (long k = j; k < border; k++)
{
incrementString(toCrack, min, max);
boolean found = toCrack.toString().equals(passwordToCrack);
if (found)
{
crackedPassword = toCrack;
passwordFound = found;
break;
}
}
}
}));
}
else
{
break;
}
}
}
executor.shutdownNow();
}
public String constructString3(long number, long min, long max)
{
StringBuffer text = new StringBuffer();
if (number > Long.MAX_VALUE - min)
{
number = Long.MAX_VALUE - min;
}
ArrayList<Long> vector = new ArrayList<Long>(10);
vector.add(min - 1 + number);
long range = max - min + 1;
boolean nextLetter = false;
for (int i = 0; i < vector.size(); i++)
{
long nextLetterCounter = 0;
while (vector.get(i) > max)
{
nextLetter = true;
long multiplicator = Math.abs(vector.get(i) / range);
if ((vector.get(i) - (multiplicator * range)) < min)
{
multiplicator -= 1;
}
vector.set(i, vector.get(i) - (multiplicator * range));
nextLetterCounter += multiplicator;
}
if (nextLetter)
{
vector.add((long) (min + nextLetterCounter - 1));
nextLetter = false;
}
text.append((char) vector.get(i).intValue());
}
return text.toString();
}
}

How do I input&solve expressions like sin(60)*50/4 in my simple calculator(without GUI) in Java?

I can only do the 4 operations,
I'm having a problem on how to input expressions like this, sin(60)*50/4
without GUI and using Scanner only.
Sorry but I'm just a newbie in programming and still learning the basics.
(1st time in programming subject XD)
This is my current code. I'm having a hard time on how to add sin, cos, tan, square, mod and exponent in my calculator.
import java.util.*;
public class Calculator {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int check=0;
while (check==0)
{
String sInput, sReal, sToken, sMToken, sMULTd;
int t, M, Md, term, a, b, sb, sbb;
System.out.print("Enter Expression: ");
sInput=sc.nextLine();
if (sInput.charAt(0)== '-')
{
sReal = sInput.substring(0,1) + minusTracker(sInput.substring(1));
System.out.print(sReal);
}
else
{
sReal = minusTracker(sInput);
System.out.print(sReal);
}
StringTokenizer sADD = new StringTokenizer(sReal, "+");
t = sADD.countTokens();
double iTerm[] = new double [t];
while(sADD.hasMoreTokens())
{
sToken = sADD.nextToken();
for(a=0; a<=(sToken.length()-1); a++)
{
b=a+1;
if( ((sToken.substring(a,b)).equals("*")) || ((sToken.substring(a,b)).equals("/")) )
{
StringTokenizer sMULT = new StringTokenizer(sToken, "*");
M = sMULT.countTokens();
double iMTerm[] = new double [M];
while(sMULT.hasMoreTokens())
{
sMToken = sMULT.nextToken();
for(sb=0; sb<=(sMToken.length()-1); sb++)
{
sbb= sb+1;
if((sMToken.substring(sb,sbb)).equals("/"))
{
StringTokenizer sMULTdiv = new StringTokenizer(sMToken, "/");
Md = sMULTdiv.countTokens();
double iMdTerm[] = new double [Md];
while(sMULTdiv.hasMoreTokens())
{
sMULTd = sMULTdiv.nextToken();
iMdTerm[--Md] = Double.parseDouble(sMULTd);
}
double MdTotal = getMdQuotient(iMdTerm);
sMToken = Double.toString(MdTotal);
}
}
iMTerm[--M] = Double.parseDouble(sMToken);
double mProduct = getMProduct(iMTerm);
sToken = Double.toString(mProduct);
}
}
}
iTerm[--t]= Double.parseDouble(sToken);
double finalAnswer = getSum(iTerm);
if(sADD.hasMoreTokens()==false)
System.out.println(" = " + finalAnswer );
}
}
}
public static String minusTracker(String sInput)
{
if(sInput.isEmpty())
{
return "";
}
else if(sInput.charAt(0)== '*' || sInput.charAt(0)=='/' || sInput.charAt(0)=='+' )
{
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
else if( sInput.charAt(0)== '-')
{
if(sInput.charAt(1)== '-')
{
sInput = sInput.replaceFirst("--", "+");
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
else
{
sInput = sInput.replaceFirst("-", "+-");
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
}
else
{
return sInput.substring(0,1) + minusTracker(sInput.substring(1));
}
}
public static double getMdQuotient(double iMdTerm[])
{
double quotient= iMdTerm[(iMdTerm.length)-1];
for(int y=(iMdTerm.length)-2; y>=0; y--)
{
quotient = quotient / iMdTerm[y];
}
return quotient;
}
public static double getMProduct(double iMTerm[])
{
double product= 1;
for(int z=(iMTerm.length)-1; z>=0; z--)
{
product = product * iMTerm[z];
}
return product;
}
public static double getSum(double iTerm[])
{
double sum= 0;
for(int z=(iTerm.length)-1; z>=0; z--)
{
sum = sum + iTerm[z];
}
return sum;
}
}

Why do object arrays in my ArrayList fail to retain their values?

I am creating a program in Java to simulate evolution. The way I have it set up, each generation is composed of an array of Organism objects. Each of these arrays is an element in the ArrayList orgGenerations. Each generation, of which there could be any amount before all animals die, can have any amount of Organism objects.
For some reason, in my main loop when the generations are going by, I can have this code without errors, where allOrgs is the Organism array of the current generation and generationNumber is the number generations since the first.
orgGenerations.add(allOrgs);
printOrgs(orgGenerations.get(generationNumber));
printOrgs is a method to display an Organism array, where speed and strength are Organism Field variables:
public void printOrgs(Organism[] list)
{
for (int x=0; x<list.length; x++)
{
System.out.println ("For organism number: " + x + ", speed is: " + list[x].speed + ", and strength is " + list[x].strength + ".");
}
}
Later on, after this loop, when I am trying to retrieve the data to display, I call this very similar code:
printOrgs(orgGenerations.get(0));
This, and every other array in orgGenerations, return a null pointer exception on the print line of the for loop. Why are the Organism objects loosing their values?
Alright, here is all of the code from my main Simulation class. I admit, it might be sort of a mess. The parts that matter are the start and simulator methods. The battle ones are not really applicable to this problem. I think.
import java.awt.FlowLayout;
import java.util.*;
import javax.swing.JFrame;
public class Simulator {
//variables for general keeping track
static Organism[] allOrgs;
static ArrayList<Organism[]> orgGenerations = new ArrayList <Organism[]>();
ArrayList<Integer> battleList = new ArrayList<Integer>();
int deathCount;
boolean done;
boolean runOnce;
//setup
Simulator()
{
done = false;
Scanner asker = new Scanner(System.in);
System.out.println("Input number of organisms for the simulation: ");
int numOfOrgs = asker.nextInt();
asker.close();
Organism[] orgArray = new Organism[numOfOrgs];
for (int i=0; i<numOfOrgs; i++)
{
orgArray[i] = new Organism();
}
allOrgs = orgArray;
}
//graphsOrgs
public void graphOrgs() throws InterruptedException
{
JFrame f = new JFrame("Evolution");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(1000,500);
f.setVisible(true);
Drawer bars = new Drawer();
//System.out.println(orgGenerations.size());
for (int iterator=0;iterator<(orgGenerations.size()-1); iterator++)
{
printOrgs(orgGenerations.get(0));
//The 0 can be any number, no matter what I do it wont work
//System.out.println("first");
f.repaint();
bars.data = orgGenerations.get(iterator);
f.add(bars);
//System.out.println("before");
Thread.sleep(1000);
//System.out.println("end");
}
}
//prints all Orgs and their statistics
public void printOrgs(Organism[] list)
{
System.out.println("Number Of Organisms: " + list.length);
for (int x=0; x<list.length; x++)
{
System.out.println ("For organism number: " + x + ", speed is: " + list[x].speed + ", and strength is " + list[x].strength + ".");
}
System.out.println();
}
//general loop for the organisms lives
public void start(int reproductionTime) throws InterruptedException
{
int generationNumber = 0;
orgGenerations.add(allOrgs);
printOrgs(orgGenerations.get(0));
generationNumber++;
while(true)
{
deathCount = 0;
for(int j=0; j<reproductionTime; j++)
{
battleList.clear();
for(int m=0; m<allOrgs.length; m++)
{
if (allOrgs[m].alive == true)
oneYearBattleCheck(m);
}
battle();
}
reproduction();
if (done == true)
break;
orgGenerations.add(allOrgs);
printOrgs(orgGenerations.get(generationNumber));
generationNumber++;
}
printOrgs(orgGenerations.get(2));
}
//Checks if they have to fight this year
private void oneYearBattleCheck(int m)
{
Random chaos = new Random();
int speedMod = chaos.nextInt(((int)Math.ceil(allOrgs[m].speed/5.0))+1);
int speedSign = chaos.nextInt(2);
if (speedSign == 0)
speedSign--;
speedMod *= speedSign;
int speed = speedMod + allOrgs[m].speed;
if (speed <= 0)
speed=1;
Random encounter = new Random();
boolean battle = false;
int try1 =(encounter.nextInt(speed));
int try2 =(encounter.nextInt(speed));
int try3 =(encounter.nextInt(speed));
int try4 =(encounter.nextInt(speed));
if (try1 == 0 || try2 == 0 || try3 == 0 || try4 == 0 )
{
battle = true;
}
if(battle == true)
{
battleList.add(m);
}
}
//Creates the matches and runs the battle
private void battle()
{
Random rand = new Random();
if (battleList.size()%2 == 1)
{
int luckyDuck = rand.nextInt(battleList.size());
battleList.remove(luckyDuck);
}
for(int k=0; k<(battleList.size()-1);)
{
int competitor1 = rand.nextInt(battleList.size());
battleList.remove(competitor1);
int competitor2 = rand.nextInt(battleList.size());
battleList.remove(competitor2);
//Competitor 1 strength
int strengthMod = rand.nextInt(((int)Math.ceil(allOrgs[competitor1].strength/5.0))+1);
int strengthSign = rand.nextInt(2);
if (strengthSign == 0)
strengthSign--;
strengthMod *= strengthSign;
int comp1Strength = strengthMod + allOrgs[competitor1].strength;
//Competitor 2 strength
strengthMod = rand.nextInt(((int)Math.ceil(allOrgs[competitor2].strength/5.0))+1);
strengthSign = rand.nextInt(2);
if (strengthSign == 0)
strengthSign--;
strengthMod *= strengthSign;
int comp2Strength = strengthMod + allOrgs[competitor2].strength;
//Fight!
if (comp1Strength>comp2Strength)
{
allOrgs[competitor1].life ++;
allOrgs[competitor2].life --;
}
else if (comp2Strength>comp1Strength)
{
allOrgs[competitor2].life ++;
allOrgs[competitor1].life --;
}
if (allOrgs[competitor1].life == 0)
{
allOrgs[competitor1].alive = false;
deathCount++;
}
if (allOrgs[competitor2].life == 0)
{
allOrgs[competitor2].alive = false;
deathCount ++ ;
}
}
}
//New organisms
private void reproduction()
{
//System.out.println("Number of deaths: " + deathCount + "\n");
if (deathCount>=(allOrgs.length-2))
{
done = true;
return;
}
ArrayList<Organism> tempOrgs = new ArrayList<Organism>();
Random chooser = new Random();
int count = 0;
while(true)
{
int partner1 = 0;
int partner2 = 0;
boolean partnerIsAlive = false;
boolean unluckyDuck = false;
//choose partner1
while (partnerIsAlive == false)
{
partner1 = chooser.nextInt(allOrgs.length);
if (allOrgs[partner1] != null)
{
if (allOrgs[partner1].alive == true)
{
partnerIsAlive = true;
}
}
}
count++;
//System.out.println("Count 2: " + count);
partnerIsAlive = false;
//choose partner2
while (partnerIsAlive == false)
{
if (count+deathCount == (allOrgs.length))
{
unluckyDuck=true;
break;
}
partner2 = chooser.nextInt(allOrgs.length);
if (allOrgs[partner2] != null)
{
if (allOrgs[partner2].alive == true)
{
partnerIsAlive = true;
}
}
}
if (unluckyDuck == false)
count++;
//System.out.println("count 2: " + count);
if (unluckyDuck == false)
{
int numOfChildren = (chooser.nextInt(4)+1);
for (int d=0; d<numOfChildren; d++)
{
tempOrgs.add(new Organism(allOrgs[partner1].speed, allOrgs[partner2].speed, allOrgs[partner1].strength, allOrgs[partner2].strength ));
}
allOrgs[partner1] = null;
allOrgs[partner2] = null;
}
if (count+deathCount == (allOrgs.length))
{
Arrays.fill(allOrgs, null);
allOrgs = tempOrgs.toArray(new Organism[tempOrgs.size()-1]);
break;
}
//System.out.println(count);
}
}
}
Main method:
public class Runner {
public static void main(String[] args) throws InterruptedException {
Simulator sim = new Simulator();
int lifeSpan = 20;
sim.start(lifeSpan);
sim.graphOrgs();
}
}
Organism class:
import java.util.Random;
public class Organism {
static Random traitGenerator = new Random();
int life;
int speed;
int strength;
boolean alive;
Organism()
{
speed = (traitGenerator.nextInt(49)+1);
strength = (50-speed);
life = 5;
alive = true;
}
Organism(int strength1, int strength2, int speed1, int speed2)
{
Random gen = new Random();
int speedMod = gen.nextInt(((int)Math.ceil((speed1+speed2)/10.0))+1);
int speedSign = gen.nextInt(2);
if (speedSign == 0)
speedSign--;
speedMod *= speedSign;
//System.out.println(speedMod);
int strengthMod = gen.nextInt(((int)Math.ceil((strength1+strength2)/10.0))+1);
int strengthSign = gen.nextInt(2);
if (strengthSign == 0)
strengthSign--;
strengthMod *= strengthSign;
//System.out.println(strengthMod);
strength = (((int)((strength1+strength2)/2.0))+ strengthMod);
speed = (((int)((speed1+speed2)/2.0))+ speedMod);
alive = true;
life = 5;
}
}
The problem lies in the graphOrgs class when I try to print to check if it is working in preparation for graphing the results. This is when it returns the error. When I try placing the print code in other places in the Simulator class the same thing occurs, a null pointer error. This happens even if it is just after the for loop where the element has been established.
You have code that sets to null elements in your allOrgs array.
allOrgs[partner1] = null;
allOrgs[partner2] = null;
Your orgGenerations list contains the same allOrgs instance multiple times.
Therefore, when you write allOrgs[partner1] = null, the partner1'th element becomes null in all the list elements of orgGenerations, which is why the print method fails.
You should create a copy of the array (you can use Arrays.copy) each time you add a new generation to the list (and consider also creating copies of the Organism instances, if you want each generation to record the past state of the Organisms and not their final state).

Categories