Tower of Hanoi error - java

Alright so I designed a code for the activity "The Towers of Hanoi". It is excellent for recursion exercise. The problem is that when I solve the puzzle via pencil and paper after outputting the results, it turns out to be wrong.
When n = 2, the puzzle works beautifully. But I just tried n = 3, and something is out of place.
My program is designed to make the 3 peg the final place for all the pieces. So the disks all finalize on peg 3.
public class TowersOfHanoi {
public static String hanoi(int nDisks, int fromPole, int toPole)
{
int helpPole;
String Pol1, Pol2, MyStep, MyPol; //contains moves
if(nDisks ==1)
{
return "There is " + nDisks + " disk moving from " + fromPole + "==>" + toPole + "\n";
}
else
{
helpPole = 6 - fromPole - toPole; //fromPole + helpPole + toPole = 6
Pol1 = hanoi(nDisks-1, fromPole, helpPole);
MyStep = "There are/is " + (nDisks-1) + " disk(s) moving from " + fromPole + "==>" + toPole + "\n";
Pol2 = hanoi(nDisks-1, helpPole, toPole);
MyPol = Pol1 + MyStep + Pol2; //+ = String concatenation
return MyPol;
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
int n = 3;
String StepsToSolution;
StepsToSolution = hanoi (n, 1, 3);
System.out.println(StepsToSolution);
}
}
Output:
There is 1 disk moving from 1==>3
There are/is 1 disk(s) moving from 1==>2
There is 1 disk moving from 3==>2
There are/is 2 disk(s) moving from 1==>3
There is 1 disk moving from 2==>1
There are/is 1 disk(s) moving from 2==>3
There is 1 disk moving from 1==>3

nDisks tells the method how many disks are to be moved. It is not an identification or the number of disks being moved at one particular time but the rest of the job in one particular place.
Thus. There will always be one disk moving from one peg to another, never 2. You do (nDisks-1) in myStep where you should have done 1. Or put more simply, myStep could have been: myStep = hanoi(1, fromPole, toPole);
Other than that your output of the moves are correct. That means you can increase to more disks and expect correct moves.

Related

Output keeps moving to next line

I'm having an issue whereby my output upon printing moves to the next line on its own, not the entire line moves, but parts of it. I would like it to be on the same line.
I've tried searching for similar issues online but no luck, I've also double checked my code, it shouldn't be moving to the next line for no reason. I would appreciate some insight on this, perhaps i'm too inexperienced to notice my error. This is what I have: Any help is appreciated! Thanks!
public static void main(String[] args)
{
//for loop to repeat 5 times
for (int i= 1; i < 6; i++)
{
//create 2 new points to use as argument
Point p1 = new Point();
Point p2 = new Point();
//create array to store return values, call method to generate points
Point point[] = getTwoPoints(p1, p2);
System.out.println("Set:" + i);
System.out.print("Given Point:" + "(" + point[0] + ")");
System.out.print("Given Point:"+ "(" + point[1]+ ")");
System.out.print("Line:" + "("+ point[0]+ ")" + "(" + point[1] + ")");
System.out.printf("Distance:"+"%.4f", point[0].getDistance(point[1]));
System.out.println("");
System.out.println("==================================");
}
}
Sample Output:
Set:1
Given Point:(60,57
)Given Point:(-75,83
)Line:(60,57
)(-75,83
)Distance:137.4809
What's the implementation of Point::toString method?
Most likely it contains a \n in it. Thus each time you print a point the caret goes to the next line.

Java - Error with a While loop not exiting when if condition hits break:

I am a beginner programmer so bear with me. I am currently working on a project for my coding class, where I am tasked with writing a program to simulate a batter facing a pitcher in a baseball game for one turn at bat. I think the problem in my code is a logic error, but I'm not quite sure how to fix it. I have tried added additional while loops and if statements but nothing has worked. The code in my batter class and pitcher class work completely fine, it's just the code in my driver. Stuff sometimes breaks out of loop when it's suppose to and other times it doesn't and sometimes it repeats the same line of text when it's not suppose to.
I would really appreciate some help on this. Thank you so much in advance.
Here is my code for the driver program:
public static void main(String[] args) {
Batter batter = new Batter();
batter.getname();
// making the pitcher object and calling the get name method.
Pitcher pitcher = new Pitcher();
pitcher.getname();
System.out.println(pitcher.getname() + " is pitching to " + batter.getname());
while (true) {
int ball = 0;
int strike = 0;
// desiding if the hit method gets called on the batter object
if (pitcher.pitch() == false) {
ball++;
System.out.println("The count is " + ball + " balls " + strike + " strikes");
}
if (pitcher.pitch()== false && ball ==4 ){
System.out.println("The count is " + ball + " balls " + strike + " strikes");
System.out.println(batter.getname() + " walked.");
break;
}
if (batter.hit() == false) {
strike++;
System.out.println("The count is " + ball + " balls " + strike + " strikes");
}
if (batter.hit() == false && strike == 3){
System.out.println("The count is " + ball + " balls " + strike + " strikes");
System.out.println(batter.getname() + " struck out.");
break;
}
if (batter.hit() == true && pitcher.pitch() == true) {
break;
}
}
}
At a quick glance I'd recommend the following.
For a start change to this as there is no point calling the getter every time so give it a variable name:
Batter batter = new Batter();
bName = batter.getname();
Pitcher pitcher = new Pitcher();
pName = pitcher.getname();
You can then replace batter.getName() & pitcher.Name() with bName & pName
I'm not a fan of while(true) and you need move ball and strike so try this instead:
int ball = 0, strike = 0;
boolean game = true;
while(game){
Then i'm not sure if your second if is right as you check for pitcher.pitch()==false in first if so try second one as:
if(ball == 4) {
Finally replace break with:
game = false;
You are resetting the values back to 0 every time the loop starts. Because you include the assignment inside the loop, it returns every time. Please note the number of the comments, meant to be read chronologically.
while (true) {
int ball = 0;
// [3] here, we are resetting ball to 0, so the ++ below is negated
int strike = 0;
if (pitcher.pitch() == false) {
ball++;
// [1] lets assume we get here, the value of ball now is 1.
// [2] we go to comment [3]
if you want to maintain the result, you should set the values before the loop.
int ball = 0;
int strike = 0;
// [1] both are 0 now
while (true) {
// [3] now, we maintain ball is 1. see 4
if (pitcher.pitch() == false) {
ball++;
// [2] setting ball to 1, repeating loop, see [3]
// [4] now we increment ball again, ball has value 2. Etc.

Threeway Duel to the Death

Working on this project from my intro java class, heres the gist of what it needs to do --
In the land of Puzzlevania, Aaron, Bob, and Charlie had anargument over
which one of them was the greatest puzzler of all time. To endthe
argumentonce and for all, they agreed on a duel to the death. Aaronis a poor
shooter and only hits his target with a probability of 1/3. Bob isa bit better
and hits his target with a probability of 1/2. Charlie is an expertmarksman
and never misses. A hit means a kill and the person hit drops outof the duel.
To compensate for the inequities in their marksmanship skills, itis decided
that the contestants would fire in turns starting with Aaron,followed by Bob,
and then by Charlie. The cycle would repeat until there was oneman
standing. And that man would be remembered as the greatest puzzlerof all
time.
a. Write a function to simulate a single shot. It should usethe
following declaration:
voidshoot(bool& targetAlive, double accuracy, int&num_alive);
This would simulate someone shooting at targetAlive with thegiven
accuracy by generating a random number between 0 and 1. If therandom
number is less than accuracy, then the target is hit andtargetAlive should
be set to false. Appendix 4 illustrates how to generate randomnumbers.
For example, if Bob is shooting at Charlie, this could be invokedas:
shoot(charlieAlive,0.5, num_alive);
Here, charlieAlive is a Boolean variable that indicates if Charlieis alive. Test
your function using a driver program before moving on to stepb.
b. An obvious strategy is for each man to shoot at the most
accurate shooter still alive on the grounds that this shooter is the
deadliest and has the best chance of hitting back. Write a second
function named start Duel that uses the shoot function to simulate
an entire duel using this strategy. It should loop until only one
contestant is left, invoking the shoot function with the proper target
and probability of hitting the target according to who is shooting.
The function should return a variable that indicates who won the
duel.
c. In your main function, invoke the startDuel function 1,000 timesin
a loop, keeping track of how many times each contestant wins.
Output the probability that each contestant will win wheneveryone
uses the strategy of shooting at the most accurate shooter left
alive.
d. A counter intuitive strategy is for Aaron to intentionally misson his
first shot. Thereafter, everyone uses the strategy of shooting atthe
most accurate shooter left alive. This strategy means that Aaron is
guaranteed to live past the first round, since Bob and Charlie will
fire at each other. Modify the program to accommodate this new
strategy and output the probability of winning for each contestant.
So here is the code I'm working with... So far it goes through only once, but I'm not sure where I should put the loop? Also any other pointers in code would be much appreciated.
import java.util.Random;
public class Duelist
{
Random rnd = new Random();
static int aaron_wins,bob_wins,charlie_wins;
class Shooter
{
public static final int StartingHits = 1;
private String name;
private double accuracy;
private int hitsLeft = StartingHits;
public Shooter(String name, double accuracy)
{
this.name = name;
this.accuracy = accuracy;
}
public String getName() { return this.name; }
public double getAccuracy() { return this.accuracy; }
public boolean isAlive() { return this.hitsLeft > 0; }
public void takeHit() { this.hitsLeft--; }
public void shoot(Shooter target)
{
if (rnd.nextDouble() <= this.getAccuracy())
{
System.out.println(this.getName() + " hits " + target.getName());
target.takeHit();
if (!target.isAlive())
{
System.out.println(target.getName() + " dies.");
}
else
{
System.out.println(this.getName() + " misses " + target.getName());
}
}
}
}
private Shooter [] shooters;
public Duelist()
{
this.shooters = new Shooter []
{
new Shooter("Aaron", 0.33),
new Shooter("Bob", 0.5),
new Shooter("Charlie", 1)
};
}
public Shooter pickTarget(Shooter shooter) {
Shooter victim = null;
for(Shooter possibleVictim : this.shooters) {
if (!possibleVictim.isAlive()) { continue; }
if (shooter==possibleVictim) { continue; }
if (victim == null || possibleVictim.getAccuracy() > victim.getAccuracy()) {
victim = possibleVictim;
}
}
return victim;
}
public void fireAway() {
int currentShooter = 0;
int maxShooter = this.shooters.length;
while(true) {
Shooter shooter = this.shooters[currentShooter++];
if (shooter.isAlive()) {
Shooter victim = pickTarget(shooter);
if (victim!=null) {
shooter.shoot(victim);
} else {
System.out.println(shooter.getName() + " wins.");
if(shooter.getName().equals("Aaron"))
aaron_wins++;
else if(shooter.getName().equals("Bob"))
bob_wins++;
else if(shooter.getName().equals("Charlie"))
charlie_wins++;
break;
}
}
if (!(currentShooter<maxShooter)) { currentShooter=0; }
}
}
public static String beginDuel_alternative_strategy()
{
boolean aaronAlive = true;
boolean bobAlive = true;
boolean charlieAlive = true;
int num_alive = 3;
aaron_wins=bob_wins=charlie_wins=0;
String winner = "";
int round = 1;
do
{
if (aaronAlive)
{
if (round == 1)
{
if (charlieAlive)
shoot(charlieAlive, 1/3.0, num_alive);
else if (bobAlive)
shoot(bobAlive, 1/3.0, num_alive);
}
}
if (bobAlive)
{
if (charlieAlive)
shoot(charlieAlive, 0.5, num_alive);
else if (aaronAlive)
shoot(aaronAlive, 0.5, num_alive);
}
if(charlieAlive)
{
if (bobAlive)
shoot(bobAlive, 1.0, num_alive);
else if (aaronAlive)
shoot(aaronAlive, 1.0, num_alive);
}
round++;
num_alive--;
}while(num_alive > 1);
if (aaronAlive)
{
winner = "Aaron";
aaron_wins++;
}
else if(bobAlive)
{
winner = "Bob";
bob_wins++;
}
else
{
winner = "Charlie";
charlie_wins++;
}
return winner;
}
public static void shoot(boolean targetAlive, double accuracy, int number_alive)
{
Random rnd2 = new Random();
if (rnd2.nextDouble()< accuracy)
{
targetAlive = false;
number_alive--;
}
}
public static void main(String[] args)
{
Duelist duel = new Duelist();
duel.fireAway();
System.out.println("Using first strategy: \n");
System.out.println("Aaron won " + aaron_wins + " duels or " + aaron_wins * 100 + "%\n");
System.out.println("Bob has " + bob_wins + " duels or " + bob_wins * 100 + "%\n");
System.out.println("Charlie has " + charlie_wins + " duels or " + charlie_wins * 100 + "%\n");
System.out.println();
System.out.println("Using alternate strategy: \n");
System.out.println("Winner :" + beginDuel_alternative_strategy());
System.out.println();
System.out.println("Aaron has " + aaron_wins + " duels or " + aaron_wins * 100 + "%\n");
System.out.println("Bob won " + bob_wins + " duels or " + bob_wins * 100 + "%\n");
System.out.println("Charlie won " + charlie_wins + " duels or " + charlie_wins * 100 + "%\n");
}
}
The answer of your question is written in the requirements for your problem:
c. In your main function, invoke the startDuel function 1,000 timesin a loop, keeping track of how many times each contestant wins. Output the probability that each contestant will win when everyone uses the strategy of shooting at the most accurate shooter left alive.
// main() pseudocode:
Shooter[] shooters = new Shooter[3](); // or however java syntax is ...
// Set the strategy, name for each of the 3 shooters...
shooters[0].setName("..");
shooters[0].setStrategy(...);
// ...
// get some storage to count which player wins a round...
int[] winCounters = new int[3];
for( int i = 0; i < 1000; i++ )
{
int winner = startDuel(shooters); // returns index of winner...
winCounters[winner]++;
}
// ... output the statistics ....

I need a short code to include in my program about the system to determine randomly who goes first in java

Hi guys this is my program ive been using java for about 3 weeks. I have achieved to do this simple game, has taken me long, but what i would like to do is how to include a code that randomly chooses who goes first in the game, some advice would be great, (bare in mind im very amateur if not less)
This isnt homework, or an assignment or work... just something im learning next week in class thought id learn it earlier and be ahead... (slighly a neek haha)
Thanks to anyone who helps
import java.util.Scanner;
/**
* The simple NIM game.
* There are 21 matches in the pile. On each move, each user take turns picking
* up 1, 2, or 3 matches until there are no more matches left.
* The one who picks up the last match loses.
*/
public class SimpleNIM {
private int matchesLeft = 21;
private String player = "A";
/**
* Starts and runs the game
*/
public void start() {
Scanner input= new Scanner(System.in);
while (true) {
int pickmatches = 0;
do {
System.out.print(
"Player " + player + ": How many matches do want to pick? (1, 2, or 3) ");
pickmatches = input.nextInt();
if (validMove(pickmatches)) {
break;
}
System.out.println(
matchesLeft - pickmatches < 0
? "You can't pick "
+ pickmatches
+ " matches as only "
+ matchesLeft
+ " matches left"
: "That's an illegal move. "
+ "Choose 1, 2, or 3 matches.");
}
while (true);
updateMatchesLeft(pickmatches);
System.out.println(
"Player "
+ player
+ " takes "
+ pickmatches
+ ( (pickmatches == 1) ? " match, " : " matches, ")
+ "leaving "
+ matchesLeft
+ '\n');
player = otherPlayer(player);
if (gameOver()) {
System.out.println("Player " + player + " wins the game!");
break;
}
}
}
/**
* Update the number of matches left in pile.
* pickmatches No. of matches picked
*/
private void updateMatchesLeft(int pickmatches) {
matchesLeft = matchLeft - pickmatches;
}
/**
* Game Over?
* true if game is over.
*/
private boolean gameOver() {
}
/**
* Returns the other player
* The current player ("B" or "A")
* The other player ("A" or "B")
*/
private String otherPlayer(String p) {
// YOUR CODE GOES HERE
}
/**
* Valid move?
* numMatches The number of matches picked
* true if there are enough matches left and numMatches is between 1 and 3
*/
private boolean validMove(int numMatches) {
}
/**
* Plays the game
* args ignored
*/
public static void main(String[] args) {
SimpleNIM pickUpMatches = new SimpleNIM();
welcome();
pickUpMatches.start();
}
/**
* Displays the startup information banner.
*/
private static void welcome() {
System.out.println("WELCOME TO THE SIMPLE NIM GAME: 21 MATCHES IN PILE");
}
}
new Random().nextInt(n) gives you a random number between 0 and n-1, so you can do
Player[] players = ...
playerToStart = players[new Random().nextInt(players.length)];
to randomly choose one.
If you plan to pick multiple players consider reusing Random instance.
You could do something like:
public void start() {
Scanner input = new Scanner(System.in);
player = Math.random() < 0.5 ? "A" :"B";
do {
But please learn something about Java in general before.
Inside your welcome method add the lines:
if(new java.util.Random().nextBoolean())
player = "A";
else
player = "B";
Have a look at the documentation for Random class.
Add this line to your libraries
import java.util.Random;
Then this line adds a new random number generator, kind of like Scanner.
Random generator = new Random();
Use this resource for more information.
Random rand = new Random();
int result = rand.nextInt(2); // a random number, either 0 or 1, see http://docs.oracle.com/javase/6/docs/api/java/util/Random.html#nextInt(int)
if (result == 0) {
// Player 1 goes first
}
else {
// Player 2 goes first
}

Towers Of Hanoi Java

This is a homework that I was working on. I have created 2 classes to play Towers of Hanoi. The first one is the basically a runner to run the actual game class.
import java.util.Scanner;
class TowersRunner {
public static void main(String[] args) {
TowersOfHanoi towers = new TowersOfHanoi();
towers.TowersOfHanoi()
}
}
public class TowersOfHanoi {
public static void main(String[] args) {
System.out.println("Please enter the starting " + "number of discs to move:");
Scanner scanner = new Scanner(System.in);
int num_of_discs = scanner.nextInt();
solve(num_of_discs, 'A', 'B', 'C');
}
public static void solve(int first_disc, char aTower, char bTower, char cTower) {
if (first_disc == 1) {
System.out.println("Disk 1 on tower " + aTower + " moving to tower " + cTower);
} else {
solve(first_disc - 1, aTower, cTower, bTower);
System.out.println("Disk " + first_disc + " on tower " + aTower + " moving to tower " + cTower);
solve(first_disc - 1, bTower, aTower, cTower);
}
}
}
What I need help with is to make the TowersOfHanoi class to run from my TowersRunner class. I also need to implement a counter display how many times it took for the game to run until the game is finished in my TowersOfHanoi class. Basically I need line that is System.out.println("It took" + counter + "turns to finish.");
I don't know how to implement the counter correctly. Also, can't make the runner class to run the TowersOfHanoi. The TowersOfHanoi class runs fine by itself but the requirment for the homework is we need at least 2 classes min.
Help would be much appreciated!!! Please I am a novice in Java and programming in general please don't go too advanced on me. :D
You don't need the main-Function in the TowersOfHanoi class.
Instead, replace your TowersRunner main(String args[]) method with
public static void main(String[] args) {
System.out.println("Please enter the starting " + "number of discs to move:");
Scanner scanner = new Scanner(System.in);
int num_of_discs = scanner.nextInt();
TowersOfHanoi.solve(num_of_discs, 'A', 'B', 'C');
}
You can just pass the counter in the function and have it be incremented. For example:
public static void solve(int first_disc, char aTower, char bTower, char cTower, int counter) {
System.out.println("Currently on turn #" + counter);
if (first_disc == 1) {
System.out.println("Disk 1 on tower " + aTower + " moving to tower " + cTower);
} else {
solve(first_disc - 1, aTower, cTower, bTower, counter + 1);
System.out.println("Disk " + first_disc + " on tower " + aTower + " moving to tower " + cTower);
solve(first_disc - 1, bTower, aTower, cTower, counter + 1);
}
}
In the first call of solve, you would pass in 1. As you can see, each time solve is called recursively, the counter is incremented.
I'll leave you to adapt this to return the final value of counter :) If you just need the final value, you don't need to add a parameter at all. Just make the function return int instead of void then try and figure out how you would make it return the value you want.

Categories

Resources