Why is my arrayList selecting items that have been removed? - java

I have an arrayList, with about 80 objects, I am trying to randomly select one of the objects, assign it to another object, remove it from the array list then return the selected object. Instead I am returning objects that have already been removed.
here is my code:
while (!ballStorage.isEmpty()) {
SecureRandom rnd = new SecureRandom();
int arraySize = ballStorage.size();//this is 80
for (int j = 80; j >= 0; j--) {
while (arraySize > 0) {
int i = rnd.nextInt(arraySize);
ballSelected = ballStorage.get(i);
ballStorage.remove(i);
ballStorage.trimToSize();
arraySize--;
//debugging println's
System.out.print(ballStorage);
System.out.println("random number generated is: " + i);
System.out.println("ball selected is: " +ballSelected);
System.out.println("Array size is: " + arraySize);
return ballSelected;
}
}
}
return ballSelected;
//output:45W,[62Bl,, 74Bl,]random number generated is: 2
ball selected is: 16W,
Array size is: 2
16W,[62Bl,]random number generated is: 1
ball selected is: 74Bl,
Array size is: 1
74Bl,[]random number generated is: 0
ball selected is: 62Bl,
Array size is: 0

while (!ballStorage.isEmpty()) {
SecureRandom rnd = new SecureRandom();
int i = rnd.nextInt(ballStorage.size());
ballSelected = ballStorage.get(i);
ballStorage.remove(i);
ballStorage.trimToSize();
System.out.print(ballStorage);
System.out.println("random number generated is: " + i);
System.out.println("ball selected is: " +ballSelected);
System.out.println("Array size is: " + arraySize);
}
return ballSelected;
I can't understand why you return inside a loop. This is the reason why your
loop executing 1 time.
But i suppose you want to return the BallSelected every time so:
class BallStorage implements Iterator<Ball>, Iterable<Ball> {
private int size;
private Random random;
private ArrayList<Ball> balls;
public BallStorage() {
this.size = 0;
this.balls = new ArrayList<>();
this.random = new Random();
}
public void add(Ball ball) {
this.size++;
balls.add(ball);
}
Ball next() {
Ball b = balls.get(random.nextInt(size));
balls.remove(b);
this.size--;
return b;
}
boolean hasNext() {
return size > 0;
}
Iterator<Ball> iterator() {
return this;
}
public static void main(String[] args) {
//Create Balls and add them in ballStorage object
for(Ball ball: ballStorage)
System.out.println("ball selected is: " +ball);
}
}

Related

How to place a number in every position my horse pawn has been to (in a 2D "board" array)

The program basically prompts the user to pick one of the displayed moves and move the horse pawn in the chess board. Ιn this way we try to see how many times the horse can move to the chessboard without being out of bounds or even in the same position.
The problem is that I haven't figured out a way to place a number (starting from 1) for the positions where the horse has been to. More specifically I want it to print H in the current position of the horse and 1 to ... on the past positions.
import java.util.Scanner;
public class Ex7_22 {
private static Scanner scanner = new Scanner(System.in);
private static String[][] board = new String[8][8];
private static int[] horizontal = new int[8];
private static int[] vertical = new int[8];
private static boolean[][] boardPositions = new boolean[8][8];
private static int currentRow = 3;
private static int currentColumn = 4;
public static void main(String[] args){
fillArrays();
boolean outOfBoundsV;
boolean outOfBoundsH;
boolean positionAvailability = false;
int VerticalMove,HorizontalMove;
fillBoard();
board[3][4] = "H";
boardPositions[3][4] = true;
displayBoard();
int pickMove;
for(int i=1;i<=64;i++){
displayBoardPositions();
displayPossibleMoves();
do {
System.out.println("\nPick one of the displayed moves to do (0-7): ");
pickMove = scanner.nextInt();
VerticalMove = moveHorse_Vertical(pickMove);
HorizontalMove = moveHorse_Horizontal(pickMove);
outOfBoundsV = checkForOutOfBounds(VerticalMove);
outOfBoundsH = checkForOutOfBounds(HorizontalMove);
if ((outOfBoundsV)||(outOfBoundsH)){
reverse(pickMove);
}
if((!outOfBoundsV)&&(!outOfBoundsH)){
positionAvailability = checkForPositionAvailability(VerticalMove,HorizontalMove);
if((!positionAvailability)){
reverse(pickMove);
}
}
}while (((outOfBoundsV)||(outOfBoundsH))||(!positionAvailability));
board[VerticalMove][HorizontalMove] = "H";
//placeNumber(VerticalMove,HorizontalMove,pickMove);
boardPositions[VerticalMove][HorizontalMove] = true;
displayBoard();
}
}
/* private static void placeNumber(int VerticalMove, int HorizontalMove, int pickMove) {
//have to place number in every position the horse has been to. Haven't managed to get it working.
reverse(pickMove);
int i=0;
i++;
String iStr = String.valueOf(i);
board[VerticalMove][HorizontalMove] = iStr;
currentRow += vertical[pickMove];
currentColumn += horizontal[pickMove];
} */
private static void reverse(int move){
currentRow -= vertical[move];
currentColumn -= horizontal[move];
}
private static void fillBoard(){
for(int i=0;i<board.length;i++){
for(int j=0;j<board[i].length;j++){
board[i][j] = "0";
}
}
}
private static boolean checkForPositionAvailability(int vertical, int
horizontal) {
if(!boardPositions[vertical][horizontal]){
return true;
}
else{
System.out.println("You've already been in this position.");
return false;
}
}
private static boolean checkForOutOfBounds(int position) {
if((position<0)||(position>=8)){
System.out.print("Position out of bounds\nPlease choose another move\n");
return true;
}
else return false;
}
private static int moveHorse_Vertical(int move) {
currentRow += vertical[move];
return currentRow;
}
private static int moveHorse_Horizontal(int move){
currentColumn += horizontal[move];
return currentColumn;
}
private static void fillArrays() {
//fill horizontal array
horizontal[0] = 2;
horizontal[1] = 1;
horizontal[2] = -1;
horizontal[3] = -2;
horizontal[4] = -2;
horizontal[5] = -1;
horizontal[6] = 1;
horizontal[7] = 2;
//fill vertical array
vertical[0] = -1;
vertical[1] = -2;
vertical[2] = -2;
vertical[3] = -1;
vertical[4] = 1;
vertical[5] = 2;
vertical[6] = 2;
vertical[7] = 1;
}
private static void displayBoard(){
System.out.print("\n");
System.out.println(" 0 1 2 3 4 5 6 7");
System.out.println(" ----------------------------- ");
for(int i=0;i<board.length;i++){
System.out.print(i + "|\t");
for(int j=0;j<board[i].length;j++){
System.out.print(" "+board[i][j] + "\t");
}
System.out.println();
}
}
private static void displayBoardPositions(){
System.out.print("\n");
System.out.println(" 0 1 2 3 4 5 6 7");
System.out.println(" ----------------------------- ");
for(int i=0;i<boardPositions.length;i++){
System.out.print(i + "|\t");
for(int j=0;j<boardPositions[i].length;j++){
System.out.print(" "+boardPositions[i][j] + "\t");
}
System.out.println();
}
}
private static void displayPossibleMoves(){
System.out.println("\n0 -> 1 move up // 2 moves right.\n" +
"1 -> 2 moves up // 1 move right.\n" +
"2 -> 2 moves up // 1 move left.\n" +
"3 -> 1 move up // 2 moves left.\n" +
"4 -> 1 move down // 2 moves left.\n" +
"5 -> 1 move left // 2 moves down.\n" +
"6 -> 1 move right // 2 moves down.\n" +
"7 -> 1 move down // 2 moves right.");
}
}
Hey i don't think you need to change much. You just need to add two integers that keep track of your previous position. I tried to keep the modifications of your code to a minimum:
int previousRow = 3;
int previousColumn = 4;
and update them after you set the current position to "H":
Here is a modified version of your public static main(String[] args):
public static void main(String[] args){
fillArrays();
boolean outOfBoundsV;
boolean outOfBoundsH;
boolean positionAvailability = false;
int VerticalMove,HorizontalMove;
fillBoard();
board[3][4] = "H";
boardPositions[3][4] = true;
// add the two integers that keep track of you previous position:
int previousRow = 3;
int previousColumn = 4;
displayBoard();
int pickMove;
for(int i=1;i<=64;i++){
displayBoardPositions();
displayPossibleMoves();
do {
System.out.println("\nPick one of the displayed moves to do (0-7): ");
pickMove = scanner.nextInt();
VerticalMove = moveHorse_Vertical(pickMove);
HorizontalMove = moveHorse_Horizontal(pickMove);
outOfBoundsV = checkForOutOfBounds(VerticalMove);
outOfBoundsH = checkForOutOfBounds(HorizontalMove);
if ((outOfBoundsV)||(outOfBoundsH)){
reverse(pickMove);
}
if((!outOfBoundsV)&&(!outOfBoundsH)){
positionAvailability = checkForPositionAvailability(VerticalMove,HorizontalMove);
if((!positionAvailability)){
reverse(pickMove);
}
}
} while ((outOfBoundsV)||(outOfBoundsH)||(!positionAvailability));
// set the previous position to your current step of i:
board[previousRow][previousColumn] = String.valueOf(i);
board[VerticalMove][HorizontalMove] = "H";
//update your previous position, with your current position
previousColumn = currentColumn;
previousRow = currentRow;
boardPositions[VerticalMove][HorizontalMove] = true;
displayBoard();
}
}

How to generate Random number based on range within List size without accessing zero

I have an Ant Colony Simulator. It is a 27 x 27 grid, and there is a Forager Ant class which locates food and the highest pheromone levels. I need to randomly generate the movement within a range.
This is a very large project, so here is only the method in question (if that's enough):
private GridNode locateHighestPherms() {
Random randomNode = new Random();
LinkedList<GridNode> neighborNodeList = gridLocation.getNeighboringNodes(); //a List of Node Objects that keeps track of adjacent nodes
LinkedList<GridNode> randomGridNode = new LinkedList<>(); //random destination Node
for(Iterator<GridNode> gridNodeIterator = neighborNodeList.iterator(); gridNodeIterator.hasNext();) {
GridNode alreadyVisited = gridNodeIterator.next();
if(foragerMoveHistory.contains(alreadyVisited) || !alreadyVisited.isVisible()) {
gridNodeIterator.remove();
}
}
if(neighborNodeList.size() == 0) {
neighborNodeList = gridLocation.getNeighboringNodes();
}
GridNode nodeWithMostPherms = neighborNodeList.get(0);
for(int checkNode = 1; checkNode < neighborNodeList.size(); checkNode++) {
if(nodeWithMostPherms.isVisible() && nodeWithMostPherms.getPheromoneUnit() < neighborNodeList.get(checkNode).getPheromoneUnit()) {
nodeWithMostPherms = neighborNodeList.get(checkNode);
}
}
for (GridNode neighborNode : neighborNodeList) {
if ((neighborNode.getPheromoneUnit() == nodeWithMostPherms.getPheromoneUnit()) && neighborNode.isVisible()) {
randomGridNode.add(neighborNode);
}
}
//DEBUGGING
//System.out.println(randomGridNode.size());
nodeWithMostPherms = randomGridNode.get(randomNode.nextInt(randomGridNode.size()));
//nodeWithMostPherms = randomGridNode.get(RandomInstance.randomNumberGen(1, randomGridNode.size()));
return nodeWithMostPherms;
}
}
Right there ^ the assignment to nodeWithMostPherms is where I need to access the next Random number. However, when I originally tried the code that's commented out, it was crashing because at times I was trying to access zero when the list size was zero.
I will show you my RandomInstance class. It's short and sweet:
import java.util.Random;
public class RandomInstance {
static int randomNumber;
public static int randomNumberGen(int lowRange, int highRange) {
Random numberGenerator = new Random(); //I would prefer not to have this.
randomNumber = numberGenerator.nextInt(highRange - lowRange + 1) + lowRange;
/** EXAMPLE FOR REFERENCE
* setFoodUnitAmount(RandomInstance.randomNumberGen(500, 1000));
*/
return randomNumber;
}
}
The reason I have my own Random class is because there are many instances of random numbers that are generated, and it was suggested to create our own so we don't have a bunch of instances of java.util.Random all over the place.
Does anyone have any suggestions on how I can make this fit my RandomInstance class?
If I try the code that's commented out, it throws an IndexOutOfBoundsException
Exception in thread "Thread-0" java.lang.IndexOutOfBoundsException: Index: 8, Size: 8
at java.util.LinkedList.checkElementIndex(LinkedList.java:555)
at java.util.LinkedList.get(LinkedList.java:476)
at ForagerObject.locateHighestPherms(ForagerObject.java:121)
Line 121 is the assignment in question mentioned above.
While you can have Random shared, you shouldn't share a multiple field.
public class RandomInstance {
private final Random random = new Random();
public int nextInt(int min, int max) {
return random.nextInt(max - min + 1) + min;
}
}
so when you call it
nodeWithMostPherms = randomGridNode.get(randomInstance.nextInt(1, randomGridNode.size()-1));
or you could use Random directly
nodeWithMostPherms = randomGridNode.get(random.nextInt(randomGridNode.size()-1)+1);

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).

How to make buttons glow while iterating through array of buttons?

I would like to display how linear search works visually.
I have created and ADT class of just integers. I also have a frame with buttons on it, when I hit the fillButton, it generates an array of random integers which are displayed on an array of buttons.
When i hit the findButton it will look for the specific number entered. As i am iterating through the array, i would like to make corresponding button change color.
I had created a similar program that iterated through an array of buttons, and changed the color as it went through. I had used Thread.sleep(), and it was just the main class. This time i have two classes and i am not sure how to go about it. I dont't know how to go about making a connection between the ADT class and the GUI class. I've used EventObjects and custom EventListeners before, but that was merely to store objects. Any help pointing in the right direction is appreciated. Thank you.
This is part of the ADT class
public class ADT {
private int[] a;
private int nElems;
private int SIZE = 60;
public ADT(){
a = new int[SIZE];
nElems=0;
}
public void initialPlacement(int index, int value,int initialCount){
a[index] = value;
nElems = initialCount;
}
public int linearSearch(int searchKey){
int index = 0;
for(int i = 0; i < nElems; i++){
if(getVal(i) == searchKey){
index = i;
break;
}
else{
index = -1;
}
}
return index;
}
And here is part of the GUI class
public NumberFrame(){///CONSTRUCTOR===========================
arr = new ADT();
//CREATE COMPONENTS
for(int i = 0; i < 60; i++){
listButtons[i] = new JButton(String.valueOf("_"));
}
for(int i = 0; i < 60; i++){
listLabels[i] = new JLabel(String.valueOf("["+i+"]"));
}
for(int i = 0; i < 60; i++){
listMiniPanels[i] = new JPanel();
listMiniPanels[i].add(listLabels[i]);
listMiniPanels[i].add(listButtons[i]);
}
fillButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
boolean sort = true;
if(linearRadio.isSelected()){
System.out.println("linear is checked");
fill(!sort);//fills half the array and array of buttons with random numbers, unsorted
}else if(binaryRadio.isSelected()){
System.out.println("binary is checked");
fill(sort);//fills half the array with random numbers and sorts it
}else{
JOptionPane.showMessageDialog(null, "Please check a sorting method");
}
}
})
findButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
int index= 0;
if(numberField.getText().equals("")){
System.out.print("Arr size = " + arr.size());
JOptionPane.showMessageDialog(null, "You did not enter a number");
}else {
try {
int searchKey = Integer.parseInt(numberField.getText());
if(linearRadio.isSelected()){
index = arr.linearSearch(searchKey);
listButtons[index].setBackground(Color.GREEN);
if(index > -1)
JOptionPane.showMessageDialog(null, "Found number " +searchKey + " # index [" + index + "]");
else
JOptionPane.showMessageDialog(null, "No such number");
}else{
index = arr.binarySearch(searchKey);
if(index > -1)
JOptionPane.showMessageDialog(null, "Found number " + searchKey+ " # index [" + index + "]");
else
JOptionPane.showMessageDialog(null, "No such number!");
}
} catch (NumberFormatException nfe) {
System.out.println("Arr size = " + arr.size());
JOptionPane.showMessageDialog(null, "Not an integer, pleas try again!");
}
}
}
});
}//=======CONSTRUCTOR END=============================

Random number - increase/decrease by 1

I'm working on a method, that takes steps between 3 and -3. My program will not print out the steps in a numerical order, and I can't quite figure out how to do it, and I can't find anything elsewhere.
public static final int SENTINEL = Math.abs(3);
public static void randomWalk(Random rand) {
int walk = 0;
while (walk != SENTINEL) {
walk = (rand.nextInt((3 - (-3)) + 1) - 3);
System.out.println("Position = " + walk);
}
}
If that is what you are looking for :
int walk = 0;
int randomStep = 0;
Random rand = new Random();
while (Math.abs(walk) != 3) {
randomStep = rand.nextInt(2) > 0 ? 1 : -1; // -1 or 1 with 50% probability
walk += randomStep;
System.out.print(walk + " ");
}
//sample output: -1 -2 -1 0 1 2 1 2 3
public static void randomWalk(Random rand) {
int walk = 0;
while (walk != SENTINEL) {
walk += rand.nextInt(3) - 1;
if(walk>3) walk = 3;
if(walk<-3) walk = -3;
System.out.println("Position = " + walk);
}
}
I guess you want this.
while (walk != SENTINEL) {
int walk = 0;
walk = (rand.nextInt((3 - (-3)) + 1) - 3);
System.out.println("Walk is = " + walk);
int temp = walk;
if (walk >= -3) {
System.out.println("Wlak plus = " + (temp + 1));
System.out.println("Wlak minus =" + (temp - 1));
}
}
Could this be what you are looking for?
package com.stackoverflow.random;
import java.util.Random;
public class Walking {
private final int bounds;
public Walking(int bounds) {
this.bounds = bounds;
}
private boolean isWithinBounds(int walk) {
return Math.abs(walk) < bounds;
}
public String randomWalk() {
int walk = 0;
StringBuilder sb = new StringBuilder();
while(isWithinBounds(walk)) {
sb.append(walk);
walk = getNextStep(walk);
}
return sb.toString();
}
private Random random = null;
private int getNextStep(int walk) {
if (random == null)
random = new Random();
boolean increase = random.nextBoolean();
return increase?++walk:--walk;
}
public static void main(String[] args) {
Walking app = new Walking(3);
System.out.println("walking: " + app.randomWalk());
}
}

Categories