Reverse loop TicTacToe - java

I've got loop:
for (int i = 0; i<3; i++){
System.out.println(i);
}
output:
0
1
2
I need to reverse this loop to output:
2
1
0
I need it because I work on TicTacToe Java game.
Here is my code for check win:
static boolean checkWin(char dot) {
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
if (map[0][i] == dot && i == 2) {
return true;
}
if (map[1][i] == dot && i == 2) {
return true;
}
if (map[2][i] == dot && i == 2) {
return true;
}
if (map[i][0] == dot && i == 2) {
return true;
}
if (map[i][1] == dot && i == 2) {
return true;
}
if (map[i][2] == dot && i == 2) {
return true;
}
if (map[i][i] == dot && i == 2) {
return true;
}
if (map[i][0] == dot && i == 2) {
return true;
}
}
}
return false;
}
last thing that I need to refactor this method:
static boolean checkWin(char dot) {
if (map[0][0] == dot && map[0][1] == dot && map[0][2] == dot) {
return true;
}
if (map[1][0] == dot && map[1][1] == dot && map[1][2] == dot) {
return true;
}
if (map[2][0] == dot && map[2][1] == dot && map[2][2] == dot) {
return true;
}
if (map[0][0] == dot && map[1][0] == dot && map[2][0] == dot) {
return true;
}
if (map[0][1] == dot && map[1][1] == dot && map[2][1] == dot) {
return true;
}
if (map[0][2] == dot && map[1][2] == dot && map[2][2] == dot) {
return true;
}
if (map[0][0] == dot && map[1][1] == dot && map[2][2] == dot) {
return true;
}
if (map[0][2] == dot && map[1][1] == dot && map[2][0] == dot) {
return true;
}
return false;
}
}
I almost done it.
Last thing that i need refactor this part of code:
if (map[0][2] == dot && map[1][1] == dot && map[2][0] == dot) {
return true;
}
to something like
if (map[i][0] == dot && i == 2) {
return true;
}
Main question is here:
for (int i = 0; i<3; i++){
System.out.println(i);
}
output:
0
1
2
I need to reverse this loop to output:
2
1
0
to feel this last part:
if (map[i][0] == dot && i == 2) {
return true;
}
i need to feel this last condition with values 2 1 0
if (map[i][insert here] == dot && i == 2) {
return true;
}
Please Help.

If all you want to do is reverse the loop output, you can just invert what you're doing in the for loop
for (int i = 2; i>=0; i--){
System.out.println(i);
}
output:
2
1
0
As a quick example.

Related

Parentheses matching algorithm java

This is my implementation of the parenthesis matching algorithm. However can someone tell me what is wrong. I get true all the time for example for input: {}(
public static boolean checkString(char [] stringToCheck){
Deque<Character> stack = new ArrayDeque<Character>();
for(int i= 0; i<stack.size();i++){
char current = stringToCheck[i];
if(current == '(' || current == '{' || current == '['){
stack.push(current);
}
if(current == ')' || current == '}' ||current == ']'){
if(stack.isEmpty()){
return false;
}
char top = stack.peek();
if((current == ']' && top == '[') ||(current == '}' && top == '{') || (current == ')' && top == '(')){
stack.pop();
}else{
return false;
}
}
}
if(stack.isEmpty){
return true;
}else{
return false;
}
}
You are using stack's size as bound instead of stringToCheck's. The stack is initialized just before so your loop is just skipped.
your program is correct except at mentioned comments in below code
public static boolean checkString(char [] stringToCheck){
Deque<Character> stack = new ArrayDeque<Character>();
int n = stringToCheck.length; // take the length of the given char array
for(int i= 0; i < n;i++){
char current = stringToCheck[i];
if(current == '(' || current == '{' || current == '['){
stack.push(current);
}
if(current == ')' || current == '}' ||current == ']'){
if(stack.isEmpty()){
return false;
}
char top = stack.peek();
if((current == ']' && top == '[') ||(current == '}' && top == '{') || (current == ')' && top == '(')){
stack.pop();
}else{
return false;
}
}
}
if(stack.isEmpty()){ // function call of stack isEmpty()
return true;
}else{
return false;
}
}
Use stringToCheck length for the loop instead stack size. Then, stack.isEmpty isEmpty is a method and you forgot the parenthesis.
public static boolean checkString(char [] stringToCheck){
Deque<Character> stack = new ArrayDeque<Character>();
for(int i= 0; i<stringToCheck.length();i++){
char current = stringToCheck[i];
if(current == '(' || current == '{' || current == '['){
stack.push(current);
}
if(current == ')' || current == '}' ||current == ']'){
if(stack.isEmpty()){
return false;
}
char top = stack.peek();
if((current == ']' && top == '[') ||(current == '}' && top == '{') || (current == ')' && top == '(')) {
stack.pop();
}else{
return false;
}
}
}
if(stack.isEmpty()){
return true;
}else{
return false;
}
}

Trying to implement a stack and the bracket matching problem but cannot figure out some semantic errors

I am required to write my own stack using an array which then I have to implement the bracket matching problem.
This is my algorithm: if we're given the string: "(())" it is returning "not balanced" when it should say it is "balanced". If you look over at BracketCheck.java near the end it tests whether the stack is empty where if it is it should return true and say the given string: "(())" is balanced. I am having problems debugging it and the result of the operation is incorrect.
Here is my stack and main class code:
public class Stack {
// instance fields:
private char array[]; // our array
private int topOfStack; // this indicates the value for each position
// overloaded constructor:
public Stack(int size) {
this.array = new char[size]; // here we instantiate a new char type array.
this.topOfStack = -1; // we set the starting position of the topOfStack to -1.
}
// push method:
public void push(char character) {
if(isFull() == true) {
System.out.println("Stack overflow error.");
}
else {
topOfStack++;
array[topOfStack] = character;
}
}
// pop method:
public char pop() {
if(isEmpty() == true) {
//System.out.println("Overflow.");
return '\0';
}
else {
char c = array[topOfStack];
topOfStack--;
return c;
}
}
// top method:
public int top() {
if(isEmpty() == true) {
System.out.println("The stack is empty.");
return 0;
}
else {
return array[topOfStack]; // returns the top element in the stack.
}
}
// size method:
public int size() {
return topOfStack + 1;
}
// isEmpty method:
public boolean isEmpty() {
if(topOfStack == -1) {
return true;
}
else {
return false;
}
}
// isFull method:
public boolean isFull() {
if(topOfStack == array.length -1 ) {
System.out.println("Stack if full.");
return true;
}
else {
return false;
}
}
BracketCheck.java
public class BracketCheck {
public static void main(String args[]) {
String text = "(())";
//boolean check = isBalanced(text);
if(isBalanced(text) == true) {
System.out.println("Balanced.");
}
else {
System.out.println("Not balanced");
}
}
public static boolean isBalanced(String text) {
Stack stack = new Stack(25); // for simplicity our stack is going to be a size of 25.
char[]arr = text.toCharArray(); // convert our string to a set of characters in an array.
// here we are looping through our text
for(int i = 0; i < arr.length; i++) {
if(arr[i] == '{' || arr[i] == '(' || arr[i] == '[') {
stack.push(arr[i]);
}
else if(arr[i] == '}' || arr[i] == ')' || arr[i] == ']') {
if(stack.isEmpty()) {
return false; // if empty then return false.
}
else if((stack.pop() == '(' && arr[i] != ')') || (stack.pop() == '{' && arr[i] != '}') || (stack.pop() == '[' && arr[i] != ']')) {
return false; // here we return false because this tells us that there is a mismatch and not balanced. Also if we did pop out the brace and it was equal
// to it's corresponding closing brace then it will just continue the loop other return false to indicate it is unbalanced.
}
}
}
if(stack.isEmpty()) {
return true; // after looping through the text if the stack turns out to be empty then this shows that there the text is balanced indeed because
}
else {
return false;
}
}
}
In this condition
else if((stack.pop() == '(' && arr[i] != ')') || (stack.pop() == '{' && arr[i] != '}') || (stack.pop() == '[' && arr[i] != ']')) {
You pop 3 times, so you extract 3 different elements from your stack. To fix it, pop once and save popped element in local variable:
if(stack.isEmpty()) {
return false; // if empty then return false.
}
else {
char element = stack.pop();
if((element == '(' && arr[i] != ')') || (element == '{' && arr[i] != '}') || (element == '[' && arr[i] != ']')) {
return false;
}
}

Why won't an IF statement work with rounded floats and doubles?

I am trying to check if a user has inputted a double between 3.5 and 7. I have tried to use the actual double and Math.round();, as well as StrictMath.round(). I have also tried to parse the string inputted as a float but it didn't change anything. Here is the basic code I used:
import java.util.Scanner;
public class IfStatement {
public static void main(String[] args) {
//create a Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter first double: ");
double number = input.nextDouble();
if (isDouble(number)==true) {
double x = Double.parseDouble(number);
if (3.5 <= x <= 7) {
System.out.println("good");
} else {
System.out.println("incorrect input");
}
} else {
System.out.println("incorroct input");
}
}
public static booleen isDouble(String str) {
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
++i;
}
int integerPartSize = 0;
int exponentPartSize = -1;
while (i < length) {
char c = str.charAt(i);
if (c < '0' || c > '9') {
if (c == '.' && integerPartSize > 0 && exponentPartSize == -1) {
exponentPartSize = 0;
} else {
return false;
}
} else if (exponentPartSize > -1) {
++exponentPartSize;
} else {
++integerPartSize;
}
++i;
}
if ((str.charAt(0) == '0' && i > 1 && exponentPartSize < 1)
|| exponentPartSize == 0 || (str.charAt(length - 1) == '.')) {
return false;
}
return true;
}
}
I have also tried making 3.5 3 in the if statement but got no dice. I just need a loose explanation and not a full solution.
I've edited your code.
boolean spelling
isDouble() takes a String
a <= x <= b chained expressions are not allowed in Java
Also,
if ((str.charAt(0) == '0' && i > 1 && exponentPartSize < 1) || exponentPartSize == 0 || (str.charAt(length - 1) == '.')) {
return false;
}
return true;
can be simplified to
return (str.charAt(0) != '0' || i <= 1 || exponentPartSize >= 1)
&& exponentPartSize != 0 && (str.charAt(length - 1) != '.');
Here's the full code.
class Test {
public static boolean isDouble(String str) {
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
++i;
}
int integerPartSize = 0;
int exponentPartSize = -1;
while (i < length) {
char c = str.charAt(i);
if (c < '0' || c > '9') {
if (c == '.' && integerPartSize > 0 && exponentPartSize == -1) {
exponentPartSize = 0;
} else {
return false;
}
} else if (exponentPartSize > -1) {
++exponentPartSize;
} else {
++integerPartSize;
}
++i;
}
return (str.charAt(0) != '0' || i <= 1 || exponentPartSize >= 1)
&& exponentPartSize != 0 && (str.charAt(length - 1) != '.');
}
public static void main(String[] args) {
//create a Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter first double: ");
String number = input.nextLine();
if (isDouble(number)) {
double x = Double.parseDouble(number);
if (3.5 <= x && x <= 7) {
System.out.println("good");
} else {
System.out.println("incorrect input");
}
} else {
System.out.println("incorroct input");
}
}
}

How to check for balanced brackets WITHOUT a stack/regex?

So basically before people start questioning why I'm not using a stack to save time over using counters and stuff.
This is a homework problem working with space complexity, so ignoring time complexity, we are attempting to reduce space complexity.
To do so, I have to use counters to keep track of the brackets.
Possible bracket types: '(' ')' '[' ']'
I've tried some coding but I seem to be having a problem with one of the test strings, and I just can't pinpoint where the problem is happening.
Boolean isWF(String w) {
// maxLevel is found and any variables I'm using has been initialized
for(int i = 0; i < maxLevel; i++) {
x = w.charAt(i);
currentLevel = i;
if(x == '(' || x == '[') {
holder = x; // Store bracket here to check match
savedLevel++;
counter++;
currentLevel++;
for(int j = i+1; j < w.length(); j++) {
x = w.charAt(j);
if(x == '(' || x == '[') {
currentLevel++;
if(currentLevel == savedLevel) {
holder = x;
counter++;
}
}
else if(x == ')' || x == ']') {
if(currentLevel == savedLevel) {
if((holder == '(' && x == ')') || (holder == '[' && x == ']')) {
currentLevel--;
counter--;
}
else
return false;
}
else {
currentLevel--;
}
}
}
}
else if(x == ')' || x == ']') {
counter--;
if(counter < 0) {
return false;
}
}
}
if(counter != 0) {
return false;
}
return true;
}
}
The strings I'm testing:
()[] - expected to be true, actual is true
([)] - expected to be false, actual is false
[([([()])])] - expected to be true, actual is true
([()([])()][()(())]()) - expected to be true, actual is false
([()([])())[()(())]()) - expected to be false, actual is false
Not a direct answer to where is the bug in your approach but the following approach seems to solve your input cases and is much simpler.
Basically you go over the string checking if the next symbol is one you can accept e.g. you can't accept a ) right after a [ and you keep a count of the open/close of brackets. If they ever go negative it means you are missing something.
public static boolean isBalanced(String s) {
int sOpen = 0;
int rOpen = 0;
for(int i = 0; i < s.length() - 1; ++i) {
final char current = s.charAt(i);
final char next = s.charAt(i + 1);
if(!isValidSymbol(current, next)) {
return false;
}
if(current == '(') rOpen++;
else if(current == '[') sOpen++;
else if(current == ')') rOpen--;
else if(current == ']') sOpen--;
if(rOpen < 0 || sOpen < 0) return false;
}
final char lastChar = s.charAt(s.length() - 1);
if(lastChar == '(') rOpen++;
else if(lastChar == '[') sOpen++;
else if(lastChar == ')') rOpen--;
else if(lastChar == ']') sOpen--;
return s.length() > 1 && rOpen == 0 && sOpen == 0;
}
private static boolean isValidSymbol(char from, char to) {
if(from == '(') {
return to == ')' || to == '[' || to == '(' ;
}
else if(from == '[') {
return to == ']' || to == '(' || to == '[';
}
return true;
}
public static void main(String[] args) {
String testInput = "()[]";
assert isBalanced(testInput) : "expected true";
testInput = "([)]";
assert isBalanced(testInput) == false : "expected false";
testInput = "[([([()])])]";
assert isBalanced(testInput) : "expected true";
testInput = "([()([])()][()(())]())";
assert isBalanced(testInput) : "expected true";
testInput = "([()([])())[()(())]()) ";
assert isBalanced(testInput) == false : "expected false";
}

Java: Wildcard Pattern Matching

I have been trying to solve the Wildcard pattern matching and I have found a working solution in the below link:
http://www.geeksforgeeks.org/wildcard-character-matching/
I have written an Equivalent java code for the C code given in the above link, which is:
public class wildcard
{
public static void main(String[] args)
{
test("g*ks", "geeks");
//test("g*k", "gee");
//test("c*d*", "cad");
}
static boolean matches(String format, String data)
{
if (format.length() == 0 && data.length() == 0)
{
return true;
}
if ((format.charAt(0) == '*' && format.charAt(1) != 0 && data.length() == 0) && (format.length() != 0 && data.length() != 0))
{
return false;
}
if ((format.charAt(0) == '?' || format.charAt(0) == data.charAt(0)) && (format.length() != 0 && data.length() != 0))
{
return matches(format.substring(1), data.substring(1));
}
if ((format.charAt(0) == '*')&& (format.length() != 0 && data.length() != 0))
{
return matches(format.substring(1), data) || matches(format, data.substring(1));
}
return false;
}
static void test(String first, String second)
{
System.out.println(matches(first, second));
}
}
On Execution, a String out of bounds Exception is thrown, which is:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:658)
at wildcard.matches(wildcard.java:29)
at wildcard.matches(wildcard.java:36)
at wildcard.matches(wildcard.java:42)
at wildcard.matches(wildcard.java:42)
at wildcard.matches(wildcard.java:36)
at wildcard.test(wildcard.java:52)
at wildcard.main(wildcard.java:16)
I can see that this exception occurs at the CharAt() method, is there any other way to make this work??
:)
First I noticed that the code && (format.length() != 0 && data.length() != 0) is not on the original code from the page you provide and are causing conflicts with your algorithm so I remove it and it looks like this:
static boolean matches(String format, String data) {
if (format.length() == 0 && data.length() == 0) {
return true;
}
if (format.charAt(0) == '*' && format.charAt(1) != 0 && data.length() == 0) {
return false;
}
if (format.charAt(0) == '?' || format.charAt(0) == data.charAt(0)) {
return matches(format.substring(1), data.substring(1));
}
if (format.charAt(0) == '*') {
return matches(format.substring(1), data) || matches(format, data.substring(1));
}
return false;
}
The problems I talked about are in the second condition you have data.length() == 0 and in the code I remove was data.length() != 0, so that condition was always false because the length cannot be 0 and not 0 at the same time.
I discovered two problems. The first one was that some cases like matches("ge?ks*", "geeksforgeeks") end up with having a single wildcard at the format and crashed on if (format.charAt(0) == '*' && format.charAt(1) != 0 && data.length() == 0) because of format.charAt(1). To solve this I add the next code to the algorithm:
if (format.length() == 1 && format.charAt(0) == '*')
return true;
The other problem was when the format was empty but still have data and solve it with:
if (format.length() == 0 && data.length() > 0)
return false;
The final algorithm looks like this:
static boolean matches(String format, String data) {
if (format.length() == 0 && data.length() == 0)
return true;
if (format.length() == 1 && format.charAt(0) == '*')
return true;
if (format.length() == 0 && data.length() > 0)
return false;
if (format.charAt(0) == '*' && format.charAt(1) != 0 && data.length() == 0)
return false;
if (format.charAt(0) == '?' || format.charAt(0) == data.charAt(0))
return matches(format.substring(1), data.substring(1));
if (format.charAt(0) == '*')
return matches(format.substring(1), data) || matches(format, data.substring(1));
return false;
}

Categories