I am getting an error (variable y might not have been initialised in the if's in the loop. How to solve that? - variables

import java.util.Scanner;
public class RPS
{
public void show()
{
int i;
System.out.println("1 - Rock 2 - Paper 3 - Scissor");
Scanner in = new Scanner(System.in);
i = in.nextInt();
double x = Math.random();
int y;
if(x<=0.33)
{
y=1;
}
else if(x>0.33 && x<0.67)
{
y=2;
}
else if(x>=0.67)
{
y=3;
}
for(;;)
{
if(i==y)
System.out.println("It's a draw!");
else if(i==1 && y==2)
System.out.println("Computer wins!");
else if(i==1 && y==3)
System.out.println("You win!");
else if(i==2 && y==1)
System.out.println("You win!");
else if(i==2 && y==3)
System.out.println("Computer wins!");
else if(i==3 && y==1)
System.out.println("Computer wins!");
else if(i==3 && y==2)
System.out.println("You win!");
else
System.out.println("Error!");
}
}
}
Whats wrong?
It gives an error that variable y might not have been intialised in the if's in the for loop.
I have assigned a value to y in the previous if-else section.
so why isnt it getting intialised?

javac is not smart enough to realize that the way your conditions are constructed, one of them will always be true.
You can rewrite your if-statements to make javac realize one branch will always be triggered:
int y;
if(x<=0.33)
{
y=1;
}
else if(x>0.33 && x<0.67)
{
y=2;
}
else // This only triggers when x >= 0.67, so no need to check
{
y=3;
}
Now javac sees that if the first two don't trigger, the last will, so y will always have a value.
You can alternatively add an else branch with an error, in case someone breaks the conditions:
int y;
if(x<=0.33)
{
y=1;
}
else if(x>0.33 && x<0.67)
{
y=2;
}
else if(x >= 0.67)
{
y=3;
}
else
{
// This should never happen
throw new IllegalArgumentException("Something's gone terribly wrong for " + x);
}
This also compiles, and if someone later decides to skew the numbers and turns the first condition into x <= 0.2 but forgets to update the other condition, you'll get an exception at runtime.

Related

Time/Space-Complexity method

I got a question to answer with the best complexity we can think about.
We got one sorted array (int) and X value. All we need to do is to find how many places in the array equals the X value.
This is my solution to this situation, as i don't know much about complexity.
All i know is that better methods are without for loops :X
class Question
{
public static int mount (int [] a, int x)
{
int first=0, last=a.length-1, count=0, pointer=0;
boolean found=false, finish=false;
if (x < a[0] || x > a[a.length-1])
return 0;
while (! found) **//Searching any place in the array that equals to x value;**
{
if ( a[(first+last)/2] > x)
last = (first+last)/2;
else if ( a[(first+last)/2] < x)
first = (first+last)/2;
else
{
pointer = (first+last)/2;
count = 1;
found = true; break;
}
if (Math.abs(last-first) == 1)
{
if (a[first] == x)
{
pointer = first;
count = 1;
found = true;
}
else if (a[last] == x)
{
pointer = last;
count = 1;
found = true;
}
else
return 0;
}
if (first == last)
{
if (a[first] == x)
{
pointer = first;
count = 1;
found = true;
}
else
return 0;
}
}
int backPointer=pointer, forwardPointer=pointer;
boolean stop1=false, stop2= false;
while (!finish) **//Counting the number of places the X value is near our pointer.**
{
if (backPointer-1 >= 0)
if (a[backPointer-1] == x)
{
count++;
backPointer--;
}
else
stop1 = true;
if (forwardPointer+1 <= a.length-1)
if (a[forwardPointer+1] == x)
{
count++;
forwardPointer++;
}
else
stop2 = true;
if (stop1 && stop2)
finish=true;
}
return count;
}
public static void main (String [] args)
{
int [] a = {-25,0,5,11,11,99};
System.out.println(mount(a, 11));
}
}
The print command count it right and prints "2".
I just want to know if anyone can think about better complexity for this method.
Moreover, how can i know what is the time/space-complexity of the method?
All i know about time/space-complexity is that for loop is O(n). I don't know how to calculate my method complexity.
Thank a lot!
Editing:
This is the second while loop after changing:
while (!stop1 || !stop2) //Counting the number of places the X value is near our pointer.
{
if (!stop1)
{
if ( a[last] == x )
{
stop1 = true;
count += (last-pointer);
}
else if ( a[(last+forwardPointer)/2] == x )
{
if (last-forwardPointer == 1)
{
stop1 = true;
count += (forwardPointer-pointer);
}
else
forwardPointer = (last + forwardPointer) / 2;
}
else
last = ((last + forwardPointer) / 2) - 1;
}
if (!stop2)
{
if (a[first] == x)
{
stop2 = true;
count += (pointer - first);
}
else if ( a[(first+backPointer)/2] == x )
{
if (backPointer - first == 1)
{
stop2 = true;
count += (pointer-backPointer);
}
else
backPointer = (first + backPointer) / 2;
}
else
first = ((first + backPointer) / 2) + 1;
}
}
What do you think about the changing? I think it would change the time complexity to O(long(n)).
First let's examine your code:
The code could be heavily refactored and cleaned (which would also result in more efficient implementation, yet without improving time or space complexity), but the algorithm itself is pretty good.
What it does is use standard binary search to find an item with the required value, then scans to the back and to the front to find all other occurrences of the value.
In terms of time complexity, the algorithm is O(N). The worst case is when the entire array is the same value and you end up iterating all of it in the 2nd phase (the binary search will only take 1 iteration). Space complexity is O(1). The memory usage (space) is unaffected by growth in input size.
You could improve the worst case time complexity if you keep using binary search on the 2 sub-arrays (back & front) and increase the "match range" logarithmically this way. The time complexity will become O(log(N)). Space complexity will remain O(1) for the same reason as before.
However, the average complexity for a real-world scenario (where the array contains various values) would be very close and might even lean towards your own version.

Infix to Postfix Conversion

I'm trying to code that converts infix expressions to postfix expressions. Currently, the program works correctly if I enter for e.g "5+6" it will output the correct answer which is "5 6 +". The problem occurs when I enter more than one operator for e.g "5+6-3", it outputs and incorrect answer "+3-". Can someone please point out where I'm making the error ? Thanks, in advance !
void main(){
Stack *s = new Stack;
string input;
cout <<"Enter Expression"<<endl;
cin>>input;
InfixToPostfix(input);
system("PAUSE");
}
string InfixToPostfix(string input){
Stack *S = new Stack();
string postfix = "";
for (int i=0; i < input.length();i++){
if (input[i]== ' '||input[i]==',') continue;
else if (IsOperator(input[i]))
{
while(!S->IsStackEmpty() && S->StackTop() != '(' && HasHigherPrecedence(S->StackTop(),input[i]))
{
postfix=S->StackTop();
S->Pop();
}
S->Push(input[i]);
}
else if(IsOperand(input[i]))
{
postfix +=input[i];
}
else if (input[i] == '(')
{
S->Push(input[i]);
}
else if (input[i]==')')
{
while(!S->IsStackEmpty() && S->StackTop() != '('){
postfix += S->StackTop();
S->Pop();
}
S->Pop();
}
}
while(!S->IsStackEmpty()){
postfix +=S->StackTop();
S->Pop();
}
cout <<""<<postfix;
return postfix;
}
bool IsOperand(char C)
{
if(C>= '0' && C<= '9') return true;
if(C>= 'a' && C<= 'z') return true;
if(C>= 'A' && C<= 'Z') return true;
return false;
}
bool IsOperator(char C)
{
if(C=='+' || C== '-' || C =='*' || C == '/' ||C == '$')
{
return true;
}else{
return false;
}
}
int IsRightAssociative(char op)
{
if(op=='$'){
return true;
}else{
return false;
}
}
int GetOperatorWeight(char op){
int weight = -1;
switch(op)
{
case'+':
case '-':
weight=1;
break;
case '*':
case '/':
weight=2;
break;
case '$':
weight=3;
break;
}
return weight;
}
int HasHigherPrecedence ( char op1, char op2)
{
int op1Weight= GetOperatorWeight(op1);
int op2Weight = GetOperatorWeight(op2);
if(op1Weight == op2Weight)
{
if(IsRightAssociative(op1))
{
return false;
}else{
return true;
}
return op1Weight > op2Weight ? true:false;
}
}
One suggestion: use a tree, rather than a stack, as an intermediate data structure. Let the operator with lowest precedence be the root of the tree and build it recursively from there. Then walk through the tree from left to right, again recursively, to generate the postfix version. That way, you can also keep track of the maximum stack depth for the postfix version, which can be important as many hand-held RPN calculators, for example, have very limited stack depths.

Point.Empty.Equals(Point.Empty) == false // why?

Using NetTopologySuite, these expressions are false:
Point.Empty.Equals(Point.Empty); // false
Polygon.Empty.Equals(Polygon.Empty); // false
Debugging shows that this behavior is implemented by
// Geometry
public IntersectionMatrix Relate(IGeometry g)
{
return RelateOp.Relate(this, g); // Point.Empty, Point.Empty
}
// IntersectionMatrix
public bool IsEquals(Dimension dimensionOfGeometryA, Dimension dimensionOfGeometryB)
{
if (dimensionOfGeometryA != dimensionOfGeometryB)
return false;
return IsTrue(_matrix[(int)Location.Interior, (int)Location.Interior]) &&
_matrix[(int)Location.Interior, (int)Location.Exterior] == Dimension.False &&
_matrix[(int)Location.Boundary, (int)Location.Exterior] == Dimension.False &&
_matrix[(int)Location.Exterior, (int)Location.Interior] == Dimension.False &&
_matrix[(int)Location.Exterior, (int)Location.Boundary] == Dimension.False;
}
I wonder what the reason behind this is. Presumably this behavior occurs in related libraries (jts, GEOS) as well and I also assume there is a justification known by geo-algebra insiders. Can someone explain?

How to switch cases with ( - ) and ( + ) keys presses?

I am working with AutoHotKey. I know I have tagged C also, I think someone with enough C programming knowledge can also help here.
Code below is working for me.
It will read two keyboard input from user and based on what user pressed it will run code for that case.
1::
Input Key, L1
if Key=1
{
;your code
}
if Key=2
{
;your code
}
2::
Input Key, L1
if Key=1
{
;your code
}
if Key=2
{
;your code
}
I would like to know if I can add a loop or something if user presses + or - key it will go do one case at a time,
for example if user presses + for first time it will do
1 1 if user presses + again it will do
1 2 if user presses - it will do
1 1
and so on.
I am not sure if this is do able or not.
I am new to programming. please help :)
You can use global variables. A global variable can be accessed anywhere in the program, unlike a normal variable which exists only inside the function.
Example:
#NoEnv
#Persistent
SetBatchLines, -1
global myVar = 0
h::
myVar := myVar + 1
execute()
return
g::
myVar := myVar - 1
execute()
return
execute()
{
if(myVar == 1)
{
;do stuff
tooltip, myVar: %myVar%
}
else if (myVar == 2)
{
;do stuff
tooltip, myVar: %myVar%
}
else if (myVar == 3)
{
;do stuff
tooltip, myVar: %myVar%
}
else if (myVar == 4)
{
;do stuff
tooltip, myVar: %myVar%
}
else if (myVar == 5)
{
;do stuff
tooltip, myVar: %myVar%
}
else
{
; nothing
tooltip,
}
return
}
I hope this is what you were asking, i wasn't quite sure from the question.
; Some of this is what's called Pseudo code. (not sure if you're familiar). It gives you needs to be turned into actual code...
; Written for AHK...
CurrentNumber = 1
(plus key)::
CurrentNumber += 1
send %CurrentNumber%
return
(minus key)::
CurrentNumber -= 1
send %CurrentNumber%
return
; Not sure if this is what you were looking for or not.. if you want a loop it will be different.
; either way, good luck to you, i'm out..
+::
keywait, +, u
{
If var =
var = 11
Else
var++
}
Return
-::
keywait, -, u
{
If var =
var = 11
Else
var--
}
Return
"var" should have same name with the variable, which has two or one digit number, in your code.
You may use this too
NumpadAdd::
keywait, NumpadAdd, u
{
If var =
var = 11
Else
var++
}
Return
NumpadSub::
keywait, NumpadSub, u
{
If var =
var = 11
Else
var--
}
Return

How to code the chess stalemate rule ?

I'm trying to write a chess game and find that I cannot find solutions to find a stalemate situation. I'm trying to google, but can't find anything. Is there a well-known algorithm or something?
Your move generator will be one of two different designs;
either it checks for legality while generating the moves
or you generate all possible moves and remove those that are illegal afterwards.
The former is better as it doesn't need post-processing.
A stalemate condition is simply one where there are no legal moves and the moving-side's king is not in check. A checkmate condition is one where there are no legal moves but the moving-side's king is in check.
In other words if you've figured out how to detect check and checkmate, you've already got everything necessary to detect stalemate.
Here is an Open-source code with all the rules for the classic Chess game:
https://github.com/cjortegon/basic-chess
You can run the project right after cloning the project (Android, iOS, Desktop and Web), or you can use the main logic, which is here: https://github.com/cjortegon/basic-chess/tree/master/libgdx/core/src/com/mountainreacher/chess/model
I based my solution on a 3-moments algorithm, first moment is when the player selects a piece from the board, then when the destination of this piece has been chosen and finally when the piece reaches that position (considering that it is an animated game, if not, you can merge step 2 and 3).
The following code has been implemented in Java. From the properties of the model class:
boolean turn;
GenericPiece selected, conquest;
ClassicBoard board;
List<int[]> possibleMovements;
int checkType;
The first method will handle moments 1, 2 and the special 'conquest' moment (applied to pawn piece only):
public boolean onCellClick(int row, int column) {
if (row == -1 && conquest != null) {
checkType = 0;
conquest.changeFigure(column);
return true;
} else if (selected != null) {
if (possibleMovements != null) {
for (int[] move : possibleMovements) {
if (move[0] == row && move[1] == column) {
// Move the PieceActor to the desired position
if (selected.moveTo(row, column)) {
turn = !turn;
}
break;
}
}
}
selected = null;
possibleMovements = null;
return true;
} else {
selected = board.getSelected(turn ? Piece.WHITE_TEAM : Piece.BLACK_TEAM, row, column);
if (selected != null) {
possibleMovements = new ArrayList<>();
possibleMovements.addAll(((GenericPiece) selected).getMoves(board, false));
// Checking the movements
board.checkPossibleMovements(selected, possibleMovements);
if (possibleMovements.size() == 0) {
possibleMovements = null;
selected = null;
return false;
} else {
return true;
}
}
}
return false;
}
And the following method will handle the 3rd moment (when animation finishes):
public void movedPiece(Piece piece) {
Gdx.app.log(TAG, "movedPiece(" + piece.getType() + ")");
// Killing the enemy
Piece killed = board.getSelectedNotInTeam(piece.getTeam(),
piece.getRow(), piece.getColumn());
if (killed != null) {
killed.setAvailable(false);
}
// Checking hacks
GenericPiece[] threat = board.kingIsInDanger();
if (threat != null) {
checkType = board.hasAvailableMoves(threat[0].getTeam()) ? CHECK : CHECK_MATE;
} else {
checkType = NO_CHECK;
}
// Checking castling
if (piece.getFigure() == Piece.ROOK && ((GenericPiece) piece).getMovesCount() == 1) {
Piece king = board.getSelected(piece.getTeam(),
piece.getRow(), piece.getColumn() + 1);
if (king != null && king.getFigure() == Piece.KING && ((GenericPiece) king).getMovesCount() == 0) {
// Left Rook
if (board.getSelected(piece.getRow(), piece.getColumn() - 1) == null) {
king.moveTo(piece.getRow(), piece.getColumn() - 1);
}
} else {
king = board.getSelected(piece.getTeam(),
piece.getRow(), piece.getColumn() - 1);
if (king != null && king.getFigure() == Piece.KING && ((GenericPiece) king).getMovesCount() == 0) {
// Right Rook
if (board.getSelected(piece.getRow(), piece.getColumn() + 1) == null) {
king.moveTo(piece.getRow(), piece.getColumn() + 1);
}
}
}
}
// Conquest
else if (piece.getFigure() == Piece.PAWN && (piece.getRow() == 0 || piece.getRow() == board.getRows() - 1)) {
conquest = (GenericPiece) piece;
checkType = CONQUEST;
}
}
That code covers all the rules from the classic chess, including: regular piece movements, castling, check, check-mate and conquests of pawns.