This program is a Domino memory game where you flip dominos until you make a correct guess where the correct dominos are supposed to stay revealed. However the problem is that while the game does work correctly the dominos do not stay revealed nor does the game end.
This is the code for my Domino Class
`
public class Domino {
private int top, bottom;
private boolean revealed;
public Domino(int x, int y) {
if (x > y) {
top = y;
bottom = x;
} else {
top = x;
bottom = y;
}
}
public int getTop() {
return top;
}
public int getBottom() {
return bottom;
}
public boolean isRevealed() {
if (revealed)
return true;
return false;
}
public void setRevealed(boolean revealed) {
this.revealed = revealed;
}
public boolean equals(Domino other) {
if (top == bottom)
return true;
return false;
}
}
`
Then here is the memory game class (called MemoryLane)
`
import java.util.Arrays;
import java.util.Random;
public class MemoryLane
{
private Domino[] board;
public MemoryLane(int max)
{
board = new Domino[(max * max) + max];
int i = 0;
for(int top = 1; top <= max; top++)
for(int bot = 1; bot <= max; bot++)
{
// make new Domino(2x) +
// save into array
if(top <= bot)
{
board[i] = new Domino(top, bot);
i++;
board[i] = new Domino(top, bot);
i++;
}
}
shuffle();
}
private void shuffle()
{
int index;
Random random = new Random();
for (int i = board.length - 1; i > 0; i--)
{
index = random.nextInt(i + 1);
if (index != i)
{
Domino temp = board[index];
board[index] = board[i];
board[i] = temp;
}
}
}
public boolean guess(int i, int k)
{
if(board[i] == board[k])
{
return true;
}
return false;
}
public String peek(int a, int b)
{
String text = new String();
text += ("[" + board[a].getTop()+ "] [" + board[b].getTop()+ "]\n");
text += ("[" + board[a].getBottom()+ "] [" + board[b].getBottom()+ "]\n");
return text;
}
public boolean gameOver() {
int count = 0;
for(int i=0; i< board.length; i++)
{
if(board[i].isRevealed())
count ++;
}
return (count == board.length);
}
public String toString() {
String text = new String();
for(int i=0; i< board.length; i++)
{
if(board[i].isRevealed())
text += ("[" + board[i].getTop()+ "] ");
else
text += ("[ ] ");
}
text += ('\n');
for(int i=0; i< board.length; i++)
{
if(board[i].isRevealed())
text += ("[" + board[i].getBottom()+ "] ");
else
text += ("[ ] ");
}
return text;
}
}
`
Then here is the driver (the driver was provided to me by a third party so it must work as it is presented and cannot be changed)
`
import java.util.Scanner;
public class MemoryLaneDriver
{
public static void main(String[] args)
{
String message = "Welcome to Memory Lane!" + "\n" +
"Choose two indexes to reveal the corresponding dominoes." + "\n" +
"If the dominoes match, they stay revealed." + "\n" +
"Reveal all the dominoes to win the game!" + "\n";
System.out.println(message);
Scanner input = new Scanner(System.in);
MemoryLane game = new MemoryLane(2);
long start = System.currentTimeMillis();
while(!game.gameOver())
{
System.out.println(game);
System.out.print("First: ");
int first = input.nextInt();
System.out.print("Second: ");
int second = input.nextInt();
game.guess(first, second);
System.out.println(game.peek(first, second) + "\n");
}
long stop = System.currentTimeMillis();
long elapsed = (stop - start) / 1000;
System.out.println(game);
System.out.println("\nYou win!");
System.out.println("Total time: " + elapsed + "s");
}
}
`
I have tried using the methods in Domino like setRevealed and isRevealed in the guess method (for example when i try board.setRevealed = true or board.isRevealed = true), but it wont work and turns up red in IntelliJ. I can also not use any Stringbuilder uses (such as append) because it is outside of what has been covered in class.
When I say the game is working correctly, I mean that it outputs my choices like:
`
Welcome to Memory Lane!
Choose two indexes to reveal the corresponding dominoes.
If the dominoes match, they stay revealed.
Reveal all the dominoes to win the game!
[ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ] [ ]
First: 1
Second: 3
[2] [2]
[2] [2]
[ ] [ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ] [ ]
First:
`
However as you can see it is not revealing the correct guess, and even if I guess all of the Dominos correctly the game does not end.
So, in your original code, you were using board[i] == board[k] which is comparing memory address locations and not the object properties, instead, you should be using board[i].equals(board[k]).
In this case you need to override equals method of the Domino class in order to change how the comparison works, for example...
#Override
public int hashCode() {
int hash = 7;
hash = 59 * hash + this.getTop();
hash = 59 * hash + this.getBottom();
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Domino)) {
return false;
}
final Domino other = (Domino) obj;
if (this.getTop() != other.getTop()) {
return false;
}
if (this.getBottom() != other.getBottom()) {
return false;
}
return true;
}
It's important to remember, if you override equals you should also override hashCode as they have an important relationship to each other.
You also never call setRevealed, which I guess should be done in guess
public boolean guess(int i, int k) {
if (board[i].equals(board[k])) {
board[i].setRevealed(true);
board[k].setRevealed(true);
return true;
}
return false;
}
Runnable example...
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
new Main();
}
Main() {
String message = "Welcome to Memory Lane!" + "\n"
+ "Choose two indexes to reveal the corresponding dominoes." + "\n"
+ "If the dominoes match, they stay revealed." + "\n"
+ "Reveal all the dominoes to win the game!" + "\n";
System.out.println(message);
Scanner input = new Scanner(System.in);
MemoryLane game = new MemoryLane(2);
long start = System.currentTimeMillis();
while (!game.gameOver()) {
// This is just making it easier to cheat.
System.out.println(game.debug());
System.out.println(game);
System.out.print("First: ");
int first = input.nextInt();
System.out.print("Second: ");
int second = input.nextInt();
game.guess(first, second);
System.out.println(game.peek(first, second) + "\n");
}
long stop = System.currentTimeMillis();
long elapsed = (stop - start) / 1000;
System.out.println(game);
System.out.println("\nYou win!");
System.out.println("Total time: " + elapsed + "s");
}
public class Domino {
private int top, bottom;
private boolean revealed;
public Domino(int x, int y) {
if (x > y) {
top = y;
bottom = x;
} else {
top = x;
bottom = y;
}
}
public int getTop() {
return top;
}
public int getBottom() {
return bottom;
}
public boolean isRevealed() {
return revealed;
}
public void setRevealed(boolean revealed) {
this.revealed = revealed;
}
#Override
public int hashCode() {
int hash = 7;
hash = 59 * hash + this.getTop();
hash = 59 * hash + this.getBottom();
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Domino)) {
return false;
}
final Domino other = (Domino) obj;
if (this.getTop() != other.getTop()) {
return false;
}
if (this.getBottom() != other.getBottom()) {
return false;
}
return true;
}
}
public class MemoryLane {
private Domino[] board;
public MemoryLane(int max) {
board = new Domino[(max * max) + max];
int i = 0;
for (int top = 1; top <= max; top++) {
for (int bot = 1; bot <= max; bot++) {
// make new Domino(2x) +
// save into array
if (top <= bot) {
board[i] = new Domino(top, bot);
i++;
board[i] = new Domino(top, bot);
i++;
}
}
}
shuffle();
}
private void shuffle() {
int index;
Random random = new Random();
for (int i = board.length - 1; i > 0; i--) {
index = random.nextInt(i + 1);
if (index != i) {
Domino temp = board[index];
board[index] = board[i];
board[i] = temp;
}
}
}
public boolean guess(int i, int k) {
if (board[i].equals(board[k])) {
board[i].setRevealed(true);
board[k].setRevealed(true);
return true;
}
return false;
}
public String peek(int a, int b) {
String text = new String();
text += ("[" + board[a].getTop() + "] [" + board[b].getTop() + "]\n");
text += ("[" + board[a].getBottom() + "] [" + board[b].getBottom() + "]\n");
return text;
}
public boolean gameOver() {
int count = 0;
for (int i = 0; i < board.length; i++) {
if (board[i].isRevealed()) {
count++;
}
}
return (count == board.length);
}
public String debug() {
String text = new String();
for (int i = 0; i < board.length; i++) {
text += ("[" + board[i].getTop() + "] ");
}
text += ('\n');
for (int i = 0; i < board.length; i++) {
text += ("[" + board[i].getBottom() + "] ");
}
return text;
}
public String toString() {
String text = new String();
for (int i = 0; i < board.length; i++) {
if (board[i].isRevealed()) {
text += ("[" + board[i].getTop() + "] ");
} else {
text += ("[ ] ");
}
}
text += ('\n');
for (int i = 0; i < board.length; i++) {
if (board[i].isRevealed()) {
text += ("[" + board[i].getBottom() + "] ");
} else {
text += ("[ ] ");
}
}
return text;
}
}
}
I figured it out
The problem was my equals method was comparing top to bottom which is why i was getting such weird results. I changed it to
public boolean equals(Domino other){
return this.top == other.top && this.bottom == other.bottom
}
and now it works perfectly fine thanks for all of the help guys!
Related
Here is the full code for it:
public void trackAll() {
int north = count(Direction.North) * 25;
int east = count(Direction.East) * 25;
int south = count(Direction.South) * 25;
int west = count(Direction.West) * 25;
if ((north == 0) && (east == 0) && (south == 0) && (west == 0)) {
this.player.sendMessage(ChatColor.RED + "Not a valid tracking compass.");
return;
}
for (Direction direction : Direction.values()) {
int length = count(direction) * 25;
if (length != 0) {
#SuppressWarnings("rawtypes")
Set players = new TreeSet();
for (Player player : Bukkit.getOnlinePlayers()) {
if (this.player.canSee(player)) if ((on(player, direction) & !player.equals(this.player))) {
players.add(player.getDisplayName());
}
}
FancyMessage message = new FancyMessage(direction + " (" + length + "): ").color(ChatColor.DARK_AQUA);
int i = 0;
for (String str : players) {
if (i == players.size() - 1)
message.then(str).color(ChatColor.GRAY).tooltip(ChatColor.GREEN + "Click here to track " + ChatColor.RESET + str + ChatColor.GREEN + ".").command("/track " + ChatColor.stripColor(str));
else {
message.then(str).color(ChatColor.GRAY).tooltip(ChatColor.GREEN + "Click here to track " + ChatColor.RESET + str + ChatColor.GREEN + ".").command("/track " + ChatColor.stripColor(str)).then(", ");
}
i++;
}
message.send(this.player);
}
}
}
And I also have another issue "Type mismatch: cannot convert from element type Object to Block"
public int count(Direction direction, boolean b) {
int length = 0;
#SuppressWarnings("rawtypes")
Set toDelete = new HashSet();
for (int i = 1; i < 10000; i++) {
Block next = this.middle.getRelative(BlockFace.valueOf(direction.toString().toUpperCase()), i);
if (next.getType() == Material.COBBLESTONE) {
length++;
toDelete.add(next); } else {
if (next.getType() == Material.STONE) {
length++;
toDelete.add(next);
toDelete.add(this.middle);
break;
}
length = 0;
toDelete.clear();
break;
}
}
if (b) {
for (Block block : toDelete) {
block.getWorld().playEffect(block.getLocation(), Effect.STEP_SOUND, block.getTypeId());
block.setType(Material.AIR);
}
}
return length;
}
I currently don't have someone that can look over the code I personally do not see the issue but I've been working on it for hours so yeah ;/ Thanks. This code is to do with a Minecraft plugin it's tracking a players location and sending the information to the player that executed the command.
Use
Set<String> players = new TreeSet<>();
and
Set<Block> toDelete = new HashSet<>();
I'm currently trying to convert my code to ArrayList and I can't seem to make it work. I'm running the whole program and it tells me Index out bounds. I'm sure I forgot to add the size of the array for the cards, but I don't know how to add it. Thanks for the help!
Edit: The error I get is at the bottom. Also, it tells me to go to the removeTop method. It looks fine there.
import java.util.Random;
import java.util.List;
import java.util.ArrayList;
public class CardPile {
private ArrayList<Card> cards = new ArrayList<Card>();
private static Random r = new Random(1);
public void addToBottom(Card c) {
if (this.cards.size() == 52) {
System.out.println("The CardPile is full. You cannot add any more Card objects.");
}
this.cards.add(c);
}
public Card removeCard(Card c) {
if (this.cards.contains(c)) {
this.cards.remove(c);
}
return null;
}
public Card removeTop() {
return this.cards.remove(0);
}
public int searchValue(int value) {
int count = 0,
for (int i = 0;i < this.cards.size();i++) {
if (this.cards.get(i).getValue() == value) {
count++;
}
}
//System.out.println("Count = "+count);
return count;
}
public Card[] removeAll(int value)
//System.out.println("(removeAll) cards ="+ cards);
int count = searchValue(value);
Card[] removed = new Card[count];
int deletedCount = 0;
int i = 0;
while (deletedCount < count) {
if (this.cards.get(i).getValue() == value) {
removed[deletedCount] = this.cards.remove(i);
deletedCount++;
} else {
i++;
}
}
return removed;
}
public int getNumberCards() {
return this.cards.size();
}
public String toString() {
if (this.cards.isEmpty()) {
return "";
}
String builder = "";
for (int i = 0;i < this.cards.size() - 1;i++) {
builder = builder + this.cards.get(i) + ", ";
}
builder = builder + this.cards.get(this.cards.size() - 1);
return builder;
}
public void shuffle() {
if (this.cards.isEmpty()) {
return;
}
for (int count = 0; count < 100000;count++) {
int i = r.nextInt(this.cards.size());
int j = r.nextInt(this.cards.size());
Card temp = this.cards.get(i);
this.cards.set(i, this.cards.get(j));
this.cards.set(j, temp);
}
}
public static CardPile makeFullDeck() {
CardPile deck = new CardPile();
for (int suit = 0;suit < 4;suit++) {
for (int value = 1; value <= 13;value++) {
deck.addToBottom(new Card(suit, value));
}
}
deck.shuffle();
return deck;
}
}
**Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.remove(ArrayList.java:492)
at CardPile.removeTop(CardPile.java:40)
at GoFish.dealCards(GoFish.java:112)
at GoFish.main(GoFish.java:13)**
EDIT:
This is the Player class:
public class Player {
private boolean[] books;
private CardPile pile;
private static int MAXIMUM_VALUE_CARD = 13;
public Player()
{
this.pile = new CardPile();
this.books = new boolean[13]; //by default all are false
}
public boolean hasCard(int value)
{
return this.pile.searchValue(value) > 0;
}
public Card[] removeAll(int value)
{
return this.pile.removeAll(value);
}
public void addAll(Card[] cards)
{
for (int i = 0; i < cards.length; i++)
{
this.pile.addToBottom(cards[i]);
}
}
//optional additional method
public void addCard(Card card)
{
this.pile.addToBottom(card);
}
public int getNumberCards()
{
return this.pile.getNumberCards();
}
public int countBooks()
{
int count = 0;
for (int i = 0; i < MAXIMUM_VALUE_CARD; i++)
{
if (books[i])
{
count++;
}
}
return count;
}
public void addBook(int value)
{
this.books[value - 1] = true;
}
public void printHand()
{
System.out.println("Player's hand is " + this.pile);
}
}
And this is the GoFish class:
import java.util.Scanner;
public class GoFish {
private static Scanner reader;
public static void main(String[] args)
{
System.out.println("How many players?");
reader = new Scanner(System.in);
int numberPlayers = reader.nextInt();
Player[] players = createPlayersArray(numberPlayers);
int currentTurn = 0;
CardPile deck = CardPile.makeFullDeck();
dealCards(deck, players);
int maximumRetries = 2;
int numRetries = 0;
while(deck.getNumberCards() > 0 && players[currentTurn].getNumberCards() > 0)
{
updateBooks(players[currentTurn]);
if (numRetries == maximumRetries)
{
numRetries = 0;
currentTurn++;
if (currentTurn == numberPlayers)
{
currentTurn = 0;
}
}
System.out.println("Player " + currentTurn + ", here is your hand. What card would you like to ask for?");
players[currentTurn].printHand();
int queryCard = reader.nextInt();
System.out.println("And from whom would you like to get it from?");
int queryPlayer = reader.nextInt();
if (queryCard < 1 || queryCard > 13 || queryPlayer < 0 || queryPlayer >= numberPlayers || queryPlayer == currentTurn)
{
System.out.println("Invalid entries. Please retry");
numRetries++;
}
else
{
numRetries = 0;
boolean hasCard = players[queryPlayer].hasCard(queryCard);
if (hasCard)
{
System.out.println("Cards found!");
Card[] removed = players[queryPlayer].removeAll(queryCard);
players[currentTurn].addAll(removed);
}
else
{
System.out.println("Go fish!");
Card top = deck.removeTop();
System.out.println("You drew " + top);
players[currentTurn].addCard(top);
//check to make sure this extra card didn't form a book
//Note this could happen even if it doesn't match the card they were asking about
updateBooks(players[currentTurn]);
if (top.getValue() == queryCard)
{
System.out.println("You successfully went fishing!");
}
else
{
currentTurn++;
if (currentTurn == numberPlayers)
{
currentTurn = 0;
}
}
}
}
}
//calculate the winner now
int maxPlayer = 0;
int maxPlayerBooks = players[0].countBooks();
for (int i = 1; i < numberPlayers; i++)
{
int currentBooks = players[i].countBooks();
if (currentBooks > maxPlayerBooks)
{
maxPlayer = i;
maxPlayerBooks = currentBooks;
}
}
System.out.println("Congratulations! Player " + maxPlayer + " you have won the game by accumulating " + maxPlayerBooks + " books!");
}
private static Player[] createPlayersArray(int numPlayers)
{
Player[] players = new Player[numPlayers];
for (int i = 0; i < numPlayers; i++)
{
players[i] = new Player();
}
return players;
}
private static void dealCards(CardPile deck, Player[] players)
{
final int NUMBER_CARDS_PER_PLAYER = 7;
for (int i = 0; i < NUMBER_CARDS_PER_PLAYER * players.length; i++)
{
Card next = deck.removeTop();
players[i % players.length].addCard(next);
}
}
private static void updateBooks(Player player)
{
for (int i = 1; i <= 13; i++)
{
//alternative option would be to modify the hasCard method to return an int instead of boolean. Then we could just count (this is probably better design)
Card[] valued = player.removeAll(i);
if (valued.length == 4)
{
player.addBook(i);
}
else
{
player.addAll(valued);
}
}
}
}
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).
I am using Comb Sort to sort out a given array of Strings. The code is :-
public static int combSort(String[] input_array) {
int gap = input_array.length;
double shrink = 1.3;
int numbOfComparisons = 0;
boolean swapped=true;
//while(!swapped && gap>1){
System.out.println();
while(!(swapped && gap==1)){
gap = (int)(gap/shrink);
if(gap<1){
gap=1;
}
int i = 0;
swapped = false;
String temp = "";
while((i+gap) < input_array.length){
numbOfComparisons++;
if(Compare(input_array[i], input_array[i+gap]) == 1){
temp = input_array[i];
input_array[i] = input_array[i+gap];
input_array[i+gap] = temp;
swapped = true;
System.out.println("gap: " + gap + " i: " + i);
ArrayUtilities.printArray(input_array);
}
i++;
}
}
ArrayUtilities.printArray(input_array);
return numbOfComparisons;
}
The problem is that while it sorts many arrays , it gets stuck in an infinite loop for some arrays, particularly small arrays. Compare(input_array[i], input_array[i+gap]) is a small method that returns 1 if s1>s2, returns -1 if s1
try this version. The string array is changed to integer array (I guess you can change it back to string version). The constant 1.3 is replaced with 1.247330950103979.
public class CombSort
{
private static final int PROBLEM_SIZE = 5;
static int[] in = new int[PROBLEM_SIZE];
public static void printArr()
{
for(int i=0;i<in.length;i++)
{
System.out.print(in[i] + "\t");
}
System.out.println();
}
public static void combSort()
{
int swap, i, gap=PROBLEM_SIZE;
boolean swapped = false;
printArr();
while ((gap > 1) || swapped)
{
if (gap > 1)
{
gap = (int)( gap / 1.247330950103979);
}
swapped = false;
for (i = 0; gap + i < PROBLEM_SIZE; ++i)
{
if (in[i] - in[i + gap] > 0)
{
swap = in[i];
in[i] = in[i + gap];
in[i + gap] = swap;
swapped = true;
}
}
}
printArr();
}
public static void main(String[] args)
{
for(int i=0;i<in.length;i++)
{
in[i] = (int) (Math.random()*PROBLEM_SIZE);
}
combSort();
}
}
Please find below implementation for comb sort in java.
public static void combSort(int[] elements) {
float shrinkFactor = 1.3f;
int postion = (int) (elements.length/shrinkFactor);
do {
int cursor = postion;
for(int i=0;cursor<elements.length;i++,cursor++) {
if(elements[i]>elements[cursor]) {
int temp = elements[cursor];
elements[cursor] = elements[i];
elements[i] = temp;
}
}
postion = (int) (postion/shrinkFactor);
}while(postion>=1);
}
Please review and let me know your's feedback.
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());
}
}