Understanding Do While Loop with nested if else statement - java

My professor made us do this in class and I am super confused looking at those outputs.
Does this(x + " " + y + " " + z) mean add all 3 variables if (y > z) ? The output doesn't make any sense to me at all.
public class Practice
{
public static void main (String[] args)
{
int x=10, y=11, z=3;
do
{
System.out.println(x + " " + y + " " + z);
if (y > z)
{
y = y-5;
}
else
{
y = y + 3;
}
x = x - 2;
} while (x > 0);
System.out.println("Bye");
}
}
OUTPUT:
10 11 3
8 6 3
6 1 3
4 4 3
2 -1 3
Bye

System.out.println(x + " " + y + " " + z);
This is not adding x,y and z. Its just appending values in string for printing
your numbers are converted to strings

Related

How do I get this to output with GCD recursion

This is what it should look like
Calling: gcd(20,12)
Calling: gcd(12,8)
Calling: gcd(8,4)
Calling: gcd(4,0)
Returning: 4 from gcd(4,0)
Returning: 4 from gcd(8,4)
Returning: 4 from gcd(12,8)
Returning: 4 from gcd(20,12)
Returning: 4 from gcd(12,20)
this is my output
Calling: gcd(10,16)
Calling: gcd(16,10)
Calling: gcd(10,6)
Calling: gcd(6,4)
Calling: gcd(4,2)
Returning: 2 from gcd(2,0)
this is my code
public static int gcd(int x, int y, String indent) {
if (y == 0) {
System.out.println(indent + "Returning: " + x + " from gcd(" + x + "," + y + ")");
return x;
} else {
System.out.println(indent + "Calling: gcd(" + x + "," + y + ")");
indent = indent + " ";
return gcd(y, x % y, indent);
}
}
The problem with your code is that you only print "Returning" when y is zero. That only happens once. What you want to do is for each "calling", it has to be paired with a "returning".
In other words, you need to print "calling" at the start of the body of the method and print "returning" before the return statement.
public static int gcd(int x, int y, String ind){
System.out.println(ind + "Calling: gcd(" + x + "," + y + ")"); //<<
int max = Math.max(x,y), min = Math.min(x,y);
int result = (min == 0 ? max : gcd(max%min,min,ind+ind));
System.out.println(ind + "Returning: gcd(" + x + "," + y + ")"); //<<
return result;
}

Java ,int x = 5; System.out.println(" x + 5 is " + x + 5); System.out.println("x += 5 is " + x += 5); why second println is mistake?

Java
int x = 5;
System.out.println(" x + 5 is " + x + 5);//correct
System.out.println("x += 5 is " + x += 5);// why wrong?
Even though, these 2 println is including calculation but why second println is error.Thanks
What you are doing causes an error because the + is seen as an operator to seperate parts of the string. Try placing that part between brackets like:
System.out.println("x += 5 is " + (x += 5));
This might fix it as you exclude the + from the string. Hope this helps you a bit, and that I am correct in my statement.

Using Recursion given m(i)=1+1/2+1/3+1/4+1/5... + 1/i

This is what I have so far. I can't tell exactly how to change the numbers so it makes sense. Do I need to include the index as part of the equation? Although it seems like n1(the previous number) + (1/n2) should give me a new n2. Any thoughts?
package myrecursivemethod;
public class MyRecursiveMethod {
private static double index = 0;
private static double stoppingPoint=10;
public static void main(String[] args) {
double n1= 0;
double n2= 1;
System.out.println("index: " + index + "->" + n1 );
myRecursiveMethod(n1, n2);
}
public static void myRecursiveMethod(double n1, double n2)
{
System.out.println("index: " + index + " -> " + (n1+(1/n2)));
if (index == stoppingPoint)
return;
index ++;
myRecursiveMethod(n2, n1+(1/n2));
}
}
You need to take a look at your formula little closer and try to find a way to present this formula using similar formula with different arguments. For instance
sum(i) = 1 + 2 + 3 + 4 + ... + (i-1) + i
is same as
sum(i) = (1 + 2 + 3 + 4 + ... + (i-1)) + i
but since
1 + 2 + 3 + 4 + ... + (i-1) = sum(i-1)
we can rewrite entire formula as
sum(i) = sum(i-1) + i
(or actually)
{ sum(i-1) + i if i>0
sum(i) = {
{ 0 if i==0
Formula from your question is very similar to this one and can be presented in similar (recursive) way.

How to most efficiently choose 3 random questions and sort them in a random order?

I am working on a project for school, and was asked to create a "store" that sells silly items. After the user adds the appropriate number of items to his/her cart, they select the option to checkout. After doing so, the user is prompted with a trivia question, based on Star Wars knowledge.
For bonus points in the class, I need to create a file that stores several questions and answers, and then check if they are correct.
I currently have 2 files, a trivaQ.txt and a triviaA.txt. They both hold "Question1"-"Question10" and "Answer1"-"Answer10". Question1's answer is Answer1, and Question2's answer is Answer2, and so on.
I wrote a simple ReadFile class that can access the file, and I am trying to build a method that will select the correct answer (the same as the question index) and then 2 other random ones.
Here is the current code:
public int askA(){
int cAnswer = Question;
int answer1= (int)(Math.random() *10);
int answer2= (int)(Math.random() *10);
while(answer1 == cAnswer || answer1 == answer2){
answer1 = (int)(Math.random() *10);
}
while(answer2 == cAnswer || answer2 == answer1){
answer2 = (int)(Math.random() *10);
}
int x = random.nextInt(3)+1;
int y = random.nextInt(3)+1;
int z = random.nextInt(3)+1;
while( x == y || x == z){
x = random.nextInt(3)+1;
}
while( y == x || y == z){
y = random.nextInt(3)+1;
}
while( z == x || z == y){
z = random.nextInt(3)+1;
}
if(x > y && x > z){
//x is first
if(y > z){
//y is second
//z is third
System.out.println("[1.] " + itemData.get(cAnswer));
System.out.println("[2.] " + itemData.get(answer1));
System.out.println("[3.] " + itemData.get(answer2));
System.out.println("Answer is 1");
}else{
//z is second
//y is third
System.out.println("[1.] " + itemData.get(cAnswer));
System.out.println("[2.] " + itemData.get(answer2));
System.out.println("[3.] " + itemData.get(answer1));
System.out.println("Answer is 1");
}
}else if(y > x && y > z){
//y is first
if(x > z){
//x is second
//z is third
System.out.println("[1.] " + itemData.get(answer1));
System.out.println("[2.] " + itemData.get(cAnswer));
System.out.println("[3.] " + itemData.get(answer2));
System.out.println("Answer is 2");
}else{
//z is second
//x is third
System.out.println("[1.] " + itemData.get(answer1));
System.out.println("[2.] " + itemData.get(answer2));
System.out.println("[3.] " + itemData.get(cAnswer));
System.out.println("Answer is 2");
}
}else if(z > y && z > x){
//z is first
if(y > x){
//y is second
//x is third
System.out.println("[1.] " + itemData.get(answer2));
System.out.println("[2.] " + itemData.get(answer1));
System.out.println("[3.] " + itemData.get(cAnswer));
System.out.println("Answer is 3");
}else{
//x is second
//y is third
System.out.println("[1.] " + itemData.get(answer2));
System.out.println("[2.] " + itemData.get(cAnswer));
System.out.println("[3.] " + itemData.get(answer1));
System.out.println("Answer is 3");
}
}
System.out.println("X is - " + x);
System.out.println("CorrectAnswer --- " + cAnswer);
return x;
}
This method currently doesn't work as I want it to. It selects a question and it selects the correct answer and 2 random answers, however; it does not sort them in the proper order.
I check if the returned value x is equivalent to the user input, and while it works probably 6/10 times, it fails 4/10 times.
Is there a more efficient way to do this? What is going wrong with my code?
Easy as :
java.util.Collections.shuffle(itemData);
result = FluentIterable.from(itemData).limit(3).toList(); //(using Google Guava)
result = itemData.stream().limit(3).collect(Collectors.toList());//(using java 8):
ref : http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html
ref : https://code.google.com/p/guava-libraries/
After you call shuffle you can alternatively read values from
itemData.get(0)
itemData.get(1)
itemData.get(2)
The easiest way for me to get it to work without having to use Google guava etc., was by creating another integer reAnswer.
int reAnswer = 0;
After every:
//z is second
//y is third
System.out.println("[1.] " + itemData.get(cAnswer));
System.out.println("[2.] " + itemData.get(answer2));
System.out.println("[3.] " + itemData.get(answer1));
System.out.println("Answer is 1");
I would add:
reAnswer = 1;
Or whatever the correct answer corresponded with. I then returned the value reAnswer from the method and checked it in the main file. It was a simple work around. Thank you for the help everyone, I just didn't think about doing it this way until now.
Connor

Searching for 'bubbles' in 2D array of chars in Java

I'm dealing with a problem in my Go Game project.
I have a board (goban), represented by 2D Array of chars. Before every next move, I would like to check for 'bubbles' in the array. Bubble should be an 4-connected area of identical chars surrounded in 4 directions by another group of specific identical chars.
If this 'bubble' exists, the characters inside should be replaced by some others. But there could be more areas and not all of them are enclosed.
For example, I have this board:
1 2 3 4 5 6 7 8 9 10 11 12 13
- - - - - - - - - - - - - - -
A | + + + + + + + + + + + + + |
B | + + + + + + + + + + + + + |
C | + + + + + + + + + + + + + |
D | + + + + + + + + + + + + + |
E | + + + + + + + + + + + + + |
F | + + O O O O + + + + + + + |
G | + O X X X X O + + + + + + |
H | + + O O X X O + + + + + + |
I | + + + + O X X O + + + + + |
J | + + + + O X O + + + + + + |
K | + + + + + O + + + + + + + |
L | + + + + + + + + + + + + + |
M | + + + + + + + + + + + + + |
- - - - - - - - - - - - - - -
And I would like to find the bubble of Xs, count them and replace them with 'Z's.
I've googled it and I think that some Connected-component labeling algorithm or FloodFill can do the job, but I'm not sure how to implement it. Is this the way or something less complicated could solve it?
Thank you
Edit:
I tried to find some pattern which could find the areas of specific character and count their liberties, but it always failed when the location was multilayered.
Changing the data structure might be the solution, but if it is possible, I would like to do it as it is now.
My current solution idea:
public void solve(){
if (boardContainsEnclosedAreas(goban, onMovePlayerStone, oppositePlayerStone){
onMovePlayerScore += countElementsInAreaAndReplaceThem(onMovePlayerStone, 'Z');
}
}
public boolean boardContainsEnclosedAreas(char[][] playingBoard, char searchedChar, char surroundingChar){
// this method should find the bubble in the playingBoard array
}
public int countElementsInAreaAndReplaceThem(char searchedChar, char replacingChar){
// the method should go through the bubble and replace all inner chars
// returns amount of replaced chars
}
You can do that with a recursive method, indeed using the FloodFill theory.
Basically, run through your grid, and each time you find an X, replace it with a Z, as well as its 4 neighbours (if applicable). But the trick is: instead of just replacing them and having to loop again each time, call the same (calling) method again to do it. The recursivity will do the rest.
Here is a (quickly done) pseudo-code version of it:
(assuming your grid is indexed from 0 to xmax, from 0 to ymax)
int numberOfBubbles = 0;
for (x = 0 to xmax) {
for (y = 0 to ymax) {
if (getCharAt(x, y) == "X") { // this if is needed because you want to count the bubbles. If not, you could just do handleBubble(x, y);
numberOfBubbles++;
handleBubble(x, y);
}
}
}
// Recursive method
void handleBubble(int x, int y) {
if (getCharAt(x, y) != "X") {
return; // exit condition
}
getCharAt(x, y) = "Z";
if (x > 0) handleBubble(x-1, y);
if (x < xmax) handleBubble(x+1, y);
if (y > 0) handleBubble(x, y-1);
if (y < ymax) handleBubble(x, y+1);
}
As far as I know, this is the only solution for this problem, which works whatever weird shape your bubble is. The complexity is not bad either.
This can be optimised further, as it currently checks for chars that are obviously not containing an X any more (because they've just been replaced with Z). This is left as an exercise to the reader :)
(NB: The minesweeper game, among other, is based on that solution)
Here's an algorithm (in pseudocode) that I've used for similar image analysis needs:
regions = Collection<Set<Point>>
foreach (Point p : allBoardLocations)
if (charAtLocation(p) != 'X') continue
foundInRegion = false
for (Set<Point> s : regions)
if (s.contains(p))
foundInRegion=true
break;
if (!foundInRegion)
newRegion = new Set<Point>()
stack = new Stack<Point>()
stack.push(p)
while (!stack.empty())
foreach (Point n : neighboringPoints(stack.pop()))
if (charAtLocation(n) == 'X')
if (!newRegion.contains(n))
newRegion.add(n);
stack.push(n);
Bascially, you maintain a collection of sets of points where each set represents a "bubble" of contiguous points on the board. Scan each location on the board and if it's an 'X' and it is not already in a region then create a new region and a stack containing the location and while there is any item on the stack, visit its neighbors searching for unvisited 'X's, adding them to the new region and stack as discovered.
At the end the you'll have a collection of sets of points, each representing a "bubble".

Categories