Convert four combination of Boolean into true/false - With IF Else statement - java

I actually try to convert four different Boolean into true/false.
My case is,
True false false false Then true else false
false True false false Then true else false
false false True false Then true else false
false false false True Then true else false
I tried like this,
int a=1;
int b=0;
int c=0;
int d=0;
int cnt=0;
// A block of code will be executed only when any one of the four variables is 1 and
//the rest of them is 0. and another block will be executed when the above mentioned
//condition become false.
if (a==0) { cnt+=1; }
if (b==0) { cnt+=1; }
if (c==0) { cnt+=1; }
if (d==0) { cnt+=1; }
if (cnt==3) { // true block } else { //false block }
The above code is working perfectly fine, But i had taken a challenge to check this condition in a single if statement. Then i tried like this.
if(!((!(a==0) && !(b==0)) && (!(c==0) && !(d==0))))
{
//true block
}
else
{
//false block
}
The above condition is failing in some combinations(a=1 b=0 c=1 d=1). Can anybody point out what the issue is.? or suggest any new ideas.?
My objective is convert (3 false + 1 true) into true other wise into false.
[Note: I just gave the scenario for understanding purpose only. a,b,c,d value may be differ. See my objective. Don't say answers in favor of 1 and 0]

I think I would use the following method, which makes the algorithm reusable and support any number of arguments. It returns true only if exactly one argument was true.
private boolean oneTrue(boolean... args){
boolean found = false;
for (boolean arg : args) {
if(found && arg){
return false;
}
found |= arg;
}
return found;
}
You can test it like this:
private void test(){
boolean a = false;
boolean b = true;
boolean c = false;
boolean d = false;
System.out.println(oneTrue(a,b,c,d));
}

Shortest pure bool solution which I can suggest:
System.out.println((a | b) ^ (c | d)) & ((a ^ b) | (c ^ d));
But in your program already already used 1 and 0, if it variables always 1 and 0, you may not use boolean just use following:
if (a + b + c + d == 1)
{
// true
} else
{
// false
}
if this varibales may have any values. In this case I recommend convert it to 1 and 0 instead of boolean and again can simply calculate sum.

How about this?
boolean a = true;
boolean b = false;
boolean c = false;
boolean d = false;
if ((a ? 1 : 0) + (b ? 1 : 0) + (c ? 1 : 0) + (d ? 1 : 0) == 1) {
System.out.println("You win!");
}
[edit]... or here's another way to do it :
if ((a ^ b ^ c ^ d) & ((a & b) == (c & d))) {
System.out.println("**XOR** You win!");
}

You can use the following expression:
a && !(b || c || d) ||
b && !(a || c || d) ||
c && !(a || b || d) ||
d && !(a || b || c)

Related

How can I tell my code that it has a "Flush"?

I'm suppose to create a code that recognizes if my hand has the same card faces
public static boolean sameFace(String hand) {
hand = "s9s7s2sQsK";
char f = hand.charAt(0);
if( hand.charAt(0)==hand.charAt(2) && hand.charAt(0)==hand.charAt(4)
&& hand.charAt(0)==hand.charAt(6) && hand.charAt(0)==hand.charAt(8));
return (hand.charAt(0) == hand.charAt(2) && hand.charAt(0) == hand.charAt(4)
&& hand.charAt(0) == hand.charAt(6) && hand.charAt(0) == hand.charAt(8));
sameface = hand;
if (hand==true;)
return (hand==true;) ;
}
As can be seen above, if all positions are the same characters, it comes true(False, if even one isn't the same.) How can I then use the result of that "return" to let my program recognize it has the same faces or not? If that is even possible.
From what i know, based on my code, it's saying "Yes, positions x=y=z are the same" how can I then tell it "Since they are the same, they have the same card faces."
I tried to put this at the end
sameface = hand;
if (hand==true;)
return (hand==true;) ;
Basically I'm trying to say that when the "hand" return statement is true, then samefaces is true. Meaning that the faces are the same. And if it's false it'll return false.
Basically I'm trying to say that when the "hand" return statement is true, then samefaces is true. Meaning that the faces are the same. And if it's false it'll return false.
You do that simply by returning the result of the expression:
public static boolean sameFace(String hand) {
char f = hand.charAt(0);
return f == hand.charAt(2) &&
f == hand.charAt(4) &&
f == hand.charAt(6) &&
f == hand.charAt(8);
}
Or if you want to be friendly to a different number of cards, use a loop:
public static boolean sameFace(String hand) {
char f = hand.charAt(0);
for (int i = 2, len = hand.length(); i < len; i += 2) {
if (f != hand.charAt(i)) {
// Not a match
return false;
}
}
// All matched
return true;
}

What are alternatives to using numerous boolean switches

I have an old code that needs to be brought back to life, it utilises around 10-15 booleans that dance around the entire class, like so:
if (condition)
{
bool1 = true
}
if (condition)
{
bool2 = true
}
...
then
if (bool1 == true && bool2 == true && bool3 == false)
{
do something
}
else if (bool1 == true && bool2 == false && bool3 == false)
{
do something
}
...
Could coding this way be avoided? Are there better ways to implement this? Perhaps utilising a map?
I would like to improve readability and overall performance, since this piece of code is over 1,000s lines long.
After feedback adding more specific example:
boolean bool1 = false, bool2 = false, bool3 = false, bool4 = false, bool5 = false,
bool6 = false, bool7 = false, bool8 = false, bool9 = false, bool10 = false;
if (string_object.startsWith("Pattern1"))
{
bool1 = true
}
if (string_object.startsWith("Pattern2")
{
bool2 = true
}
if (string_object.startsWith("Pattern3")
{
bool3 = true
}
if (string_object.startsWith("Pattern4")
{
bool4 = true
}
if (string_object.startsWith("Pattern5")
{
bool5 = true
}
// and so on...
if (system_type.equals("type1"))
{
if (bool1 == true && bool2 == true && bool3 == false)
{
system_value.set("value1")
}
else if (bool1 == true && bool2 == false && bool3 == false)
{
system_value.set("value2")
}
else if (bool1 == true && bool3 == false && bool4 == true)
{
system_value.set("value3")
}
}
else if (system_type.equals("type2"))
{
if (bool1 == true && bool2 == true && bool4 == true)
{
system_value.set("value1")
}
else if (bool1 == true && bool3 == false && bool5 == true)
{
system_value.set("value4")
}
else if (bool1 == true && bool3 == false && bool4 == true)
{
system_value.set("value5")
}
}
// and so on...
There are a few things you can do.
as others have mentioned, code like this:
if (condition)
{
bool1 = true;
}
Can be compressed to:
bool1 = (condition);
Another useful tool is one of Martin Fowler's refactors - Decompose Conditional.
An example of this would be something like changing this:
if (bool1 == true && bool2 == true && bool3 == false)
{
do something
}
else if (bool1 == true && bool2 == false && bool3 == false)
{
do something
}
To something like this:
if (firstCondition())
{
do something
}
else if (secondCondition())
{
do something
}
private boolean firstCondition() {
return (bool1 && bool2 && !bool3 );
}
private boolean secondCondition() {
return (bool1 && !bool2 && !bool3);
}
Decomposing complex conditionals like this makes your code easier to read and maintain.
You can construct bit maps from your booleans, and encode desired combinations as integers.
Here is an example: let's say you need three booleans, flag0, flag1, and flag2, and you need to check five different combinations of the flags:
flag2 flag1 flag0 Action
----- ----- ----- ----------
true false false ActionOne
true true false ActionTwo
true false true ActionThree
false false true ActionFour
false true true ActionFive
Then you can build flags as follows:
int flags = 0;
if (condition0) flags |= (1 << 0);
if (condition1) flags |= (1 << 1);
if (condition2) flags |= (1 << 2);
Now each combination of conditions is encoded as a unique number between zero and seven, inclusive, so it could be checked with a switch statement:
switch(flags) {
case 4: actionOne(); break; // 1 0 0
case 6: actionTwo(); break; // 1 1 0
case 5: actionThree(); break; // 1 0 1
case 1: actionFour(); break; // 0 0 1
case 3: actionFive(); break; // 0 1 1
}
Most of the time this antipattern is due to developers not wanting to create a subclass for just one new behavior. If that is the case, polymorphism could help.
Assume you have the following class:
public class Animal {
private final boolean isCat;
private final boolean isReptile;
private final boolean isDog;
private Animal(final boolean isCat, final boolean isReptile, final boolean isDog) {
this.isCat = isCat;
this.isReptile = isReptile;
this.isDog = isDog;
}
public static Animal getLizard() {
return new Animal(false, true, true);
}
public static Animal getDog() {
return new Animal(false, false, false);
}
public String seeStranger() {
final StringBuilder result = new StringBuilder(this.toString());
if (isDog) {
result.append(" barks and");
} else if (isCat) {
result.append(" meows and");
}
if (isReptile) {
result.append(" crawls away.");
} else {
result.append(" walks forward.");
}
return result.toString();
}
}
What you really want are multiple classes with differing behavior:
public abstract class Animal {
public static Animal getLizard() {
return new Lizard();
}
public static Animal getDog() {
return new Dog();
}
public abstract String seeStranger();
private static class Lizard extends Animal {
#Override
public String seeStranger() {
return this.toString() + " crawls away.";
}
}
private static class Dog extends Animal {
#Override
public String seeStranger() {
return this.toString() + " barks and walks forward.";
}
}
}
Depending on your use case, you might find it easier to dispense with Boolean variables altogether and just put the conditions inline in the control flow statements. For example, you could change this:
if (condition1)
{
bool1 = true
}
else if (condition2)
{
bool2 = true
}
...
if (bool1 == true && bool2 == true && bool3 == false)
{
do something
}
else if (bool1 == true && bool2 == false && bool3 == false)
{
do something
}
...
to be something more like this:
if (condition1 && condition2 && condition3)
{
do something
}
else if (condition1 && (not condition2) && codition3)
{
do something
}
...
You might also be able to simplify your conditions. For example, there might be a condition4 equivalent to condition1 && condition2 that doesn't use &&. Consider condition1 := x <= 100 and condition2 := x >= 100. condition1 && condition2 is totally equivalent to x == 100, and I would definitely recommend changing
...
bool1 = (x >= 100);
...
bool2 = (x <= 100);
...
if (bool1 == true && bool2 == true) { ... }
...
to this instead:
...
if (x == 100) { ... }
...
I hesitate to go so far as to call the explicit use of Boolean variables an antipattern, but I tend to prefer to keep Booleans as R-values whenever possible.
In this case I would recommend leaving the booleans alone, if they're well labeled
But a neat thing can be done if they are closely related (ie direction, N/S/E/W), called bitmasks
Related Stack Overflow post: what is a bitmask and a mask
They're useful for direction if you have a grid of streets, each street intersection can have N/S/E/W roads coming out of it, can be defined as 4 bits of a number
Let's define a few constants
N=1 (0001)
S=2 (0010)
E=4 (0100)
W=8 (1000)
An intersection with roads in N and E would be N|E
N|E=1|4=5 (0101)
A full + intersection (NSEW) would be N|S|E|W
N|S|E|W=1|2|4|8=15 (1111)
If you're adding to a bitmask, newMask = oldMask|direction
Let's add S to our NE mask
int newMask = oldMask | S
oldMask was 0101, S is 0010, newMask becomes 0111
It also has an easy way to check if a direction exists
If we want to check if oldMask contains N
boolean N? = (oldMask & N) != 0
oldMask & N will isolate the N bit, making the returned value either be N or 0

how to declare a boolean and only gives true if the first and the last character is "a" [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
Given a string personName, I'm trying to create a boolean condition2 equal to the condition
the first or last letter in personName is 'A' (case-insensitive). e.g., 'aha' or 'A'
Here's what I've tried so far:
boolean condition2;
if (personName.charAt(0) = "a" || personName.charAt(personName.length()-1) = "a") {
condition2 = true;
} else {
condition2 = false;
}
char type in Java is a character so wouldn't you be looking for something like this?
boolean condition2;
if((personName.charAt(0) == 'a' || personName.charAt(0) == 'A') &&
(personName.charAt(personName.length()-1) == 'a' || personName.charAt(personName.length()-1) == 'A'))
{
condition2 = true;
}
else{
condition2 = false;
}
For your first question where first and last character of a String should be 'a'
boolean condition1 = false;
if(personName.charAt(0) == 'a' && personName.charAt(personName.length()-1) == 'a') {
condition1 = true;
}
For your second condition where variable should be true only if age is in the range [18,24]
boolean condition2 = false;
if(personAge >=18 && personAge <=24) {
condition2 = true;
}
You can do it this way except comparison operator is == and you compare characters, not String.
So right way would be:
Character.toLowerCase(personName.charAt(0)) == 'a'
See, double equals and single quote.
use single quote for data type char. and convert it to lower case, so that it allow whether it's upper case or lower case.
Also use == when comparing if it's equal. this = sign, is for assigning value
if(Character.toLowerCase(personName.charAt(0)) == 'a' ||
Character.toLowerCase(personName.charAt(personName.length()-1)) == 'a')
it will look like this
boolean condition2;
if(Character.toLowerCase(personName.charAt(0)) == 'a' || Character.toLowerCase(personName.charAt(personName.length()-1)) == 'a')
{
condition2 = true;
}
else{
condition2 = false;
}
Your problem can be solve in this manner;
public static void main(String[] args) {
String s = "bsdadasd";
boolean condition2;
System.out.println(check(s.toLowerCase().charAt(0),s.toLowerCase().charAt(s.length()-1)));
}
public static boolean check(char a,char b){
return (a == 'a' || b == 'a');
}
You can pass the two characters as parameters for a method where it return true or falsedepending on the condition.
Since both characters are irrelevant of its case first made them to lowercase. toLowerCase() then passed the char at 0 and char at last.
The return statement will return the true or false to you.
And also use == to check if similar = means assigning.
It is circuitous to write
boolean b;
if (some boolean expression)
b = true;
else
b = false;
Much simpler to write
boolean b = some boolean expression;
For reasons I don't understand, there is a widespread reluctance to write a boolean expression (as distinct from the simple literal values true/false) outside an 'if' statement.
And don't get me started on if (b == true)

java boolean method not returning true/false?

In an example in class we were given this method as part of a bigger problem:
public boolean isWinner()
{
return ((points == 4) || (score == 4));
}
My impression of boolean type methods was that they HAVE to return true/false like "return true;" In this example there is no where indicating whether it is returning true/false so if points == 4 does it return true? and if score ==4 does it return false? or is it if either are true then the entire return statement is true?
If either points == 4 or score == 4 is true, the whole thing will be true. All boolean expressions evaluate down to either true or false.
This expression:
return ((points == 4) || (score == 4));
Will either return true or false.
|| is the OR operator. Which for two expressions has the following truth table:
T T = T
T F = T
F T = T
F F = F
So if both points and score are false then the function will return false. Otherwise it will return true.
return ((points == 4) || (score == 4));
Execution of above will result in return true or return false
From specification.
The value produced by the == operator is true if the value of the left-hand operand is equal to the value of the right-hand operand; otherwise, the result is false.
also read about || operation in specification I hope that will clear your doubts
This
return (points == 4) || (score == 4);
is the same as
boolean ret = (points == 4) || (score == 4);
return ret;
which is the same as
if (points == 4) return true;
if (score == 4) return true;
return false;
You should take a look at the Java truth tables for || and &&. This will help give you an understanding of boolean results.
As your question stands, it will return true if either of those statements are true and false if they are both false.
There is only one exception in that code.
In the case that points/score are Integer referencing null, would cause an exception.
public class Snippet {
private Integer points;
private Integer score;
public boolean isWinner() {
return ((points == 4) || (score == 4));
}
public static void main(String[] args) {
System.out.println(new Snippet().isWinner());
}
}
Output:
Exception in thread "main" java.lang.NullPointerException
at snippet.Snippet.isWinner(Snippet.java:8)
at snippet.Snippet.main(Snippet.java:13)

Compare strings using recursion

I've got a homework assignment that I just can't figure out. I have to write a static method match(String x, String y) that returns a boolean for whether or not string x and string y match. The matching process should allow "wild cards" such as '#' character which will match with any single character and the '*' character which will match with 0 or more characters of any type. I'm not allowed to use any loops and I have to use recursion.
What I've written so far is this...
public class CompareStrings {
public static boolean match(String x, String y) {
if (x.length() <= 1 && y.length() <= 1) {
if (x.equals("*") || y.equals("*")) {
return true;
}
if ((x.length() == 1 && y.length() == 1) && (x.equals("#") || y.equals("#"))) {
return true;
}
return x.equals(y);
}
String x1 = "";
String x2 = "";
String y1 = "";
String y2 = "";
if (x.length() == 0 && y.charAt(0) == '*') {
y2 = y.substring(1, y.length());
}
if (y.length() == 0 && x.charAt(0) == '*') {
x2 = x.substring(1, x.length());
}
if (x.length() > 1 && y.length() > 1) {
if (x.length() != y.length() && !x.contains("*") && !y.contains("*")) {
return false;
}
if (x.charAt(0) == '*') {
x1 = "*";
x2 = x.substring(1, x.length());
y1 = "*";
y2 = y.substring(y.length()-x2.length(), y.length());
}
else if (y.charAt(0) == '*') {
y1 = "*";
y2 = y.substring(1, y.length());
x1 = "*";
x2 = x.substring(x.length()-y2.length(), x.length());
}
else {
x1 = x.substring(0, 1);
x2 = x.substring(1, x.length());
y1 = y.substring(0, 1);
y2 = y.substring(1, y.length());
}
}
return match(x1, y1) && match(x2, y2);
}
public static void main(String[] args) {
System.out.println(match("hello", "hello.") + " 1 false"); // should return false
System.out.println(match("hello", "jello") + " 2 false"); // should return false
System.out.println(match("hello", "h#llo") + " 3 true"); // should return true
System.out.println(match("hello", "h####") + " 4 true"); // should return true
System.out.println(match("hello", "h*") + " 5 true"); // should return true
System.out.println(match("hello", "*l*") + " 6 true"); // should return true
System.out.println(match("anyString", "*") + " 7 true"); // should return true
System.out.println(match("help", "h####") + " 8 false"); // should return false
System.out.println(match("help", "h*") + " 9 true"); // should return true
System.out.println(match("help", "*l*") + " 10 true"); // should return true
System.out.println(match("help", "*l*p") + " 11 true"); // should return true
System.out.println(match("help", "h#llo") + " 12 false"); // should return false
System.out.println(match("", "*") + " 13 true"); // should return true
System.out.println(match("", "***") + " 14 true"); // should return true
System.out.println(match("", "#") + " 15 false"); // should return false
System.out.println(match("", "") + " 16 true"); // should return true
}
}
The main method is the test program given by the assignment. I realize my code is a little messy - I was scrambling a bit - but I can seem to get most of it working. The only example that doesn't return the right value is number 11. I get false when it should be true. The reason I think this is happening is because since the string y starts with a '', the thing my method does is splits both x and y strings into their last 3 characters, even though that first '' in y is supposed to represent 2 characters. How can I make it so that cases like this return a match?
Basically you need to understand the concept of recursion (that is the objective of your homework). The way recursion works is that everytime a function calls itself, the current execution (variables/ execution info) goes onto a stack and sleeps there till the new call finishes.
To solve the problem you have mentioned, lets take a simple example, hello and h#llo. A basic way to solve problem will be that match service call itself again and again till
A perfect match is found - return true
A failure condition is found- return false
In absence of above 2, match calls itself with one character less than the prev call
Something like
Call 1: hello & h#llo// calls match again and present call moves to stack, waits for a reply
Call 2: ello & #llo //matches special character
call 3: llo and llo// perfect match return true to call 2
Back to call 2: receives true from prv call and returns back to call 1
Back to call 1: receives true and returns to main.
Once you understand the concept of recursion stack, solving this problem will be simple
Your final match method will look something like
public static boolean match(String x, String y) {
//if both are empty
if(x.length()==0 && y.length()==0) return true;
//if one is empty
if(x.length()==0 )
{
if(y.charAt(0)!='*')
return false;
if(y.length()!=1)
//border line case
return match(x,y.substring(1));
else
return true;
}
if(y.length()==0 )
{
if(x.charAt(0)!='*')
return false;
if(x.length()!=1)
//border line case
return match(y,x.substring(1));
else
return true;
}
//Base case
if(x.equals(y) || x.equals("*") || y.equals("*"))
{
return true;//we are done as strings are equal
}
//we are here that means strings are not equal yet
if(x.charAt(0)=='#' || y.charAt(0)=='#' ||x.charAt(0)==y.charAt(0))
{
if(x.length()==1 && y.length()==1) return true;//this was the last character
if(x.length()>1 && y.length()>1)
{
//we have single char wild card or char 0 equal, lets remove the char at 0th location and check again
return (match(x.substring(1),y.substring(1)));
}
}
if(x.charAt(0)=='*')
{
//this is interesting now, we will need to skip 0..n number of characters till we find matching pattern
//case 0 chars: he*llo and hello
if(match(x.substring(1),y)==true)
{
return true;
}
else if (match(x.substring(1),y.substring(1))==true)
{
//case 1: he*lo and hello
return true;
}
else
{
//case n chars: h*o and hello
return (match(x, y.substring(1)));
}
}
if(y.charAt(0)=='*')
{
//this is interesting now, we will need to skip 0..n number of characters till we find matching pattern
//case 0 chars: he*llo and hello
if(match(y.substring(1),x)==true)
{
return true;
}
else if (match(x.substring(1),y.substring(1))==true)
{
//case 1: he*lo and hello
return true;
}
else
{
//case n chars: h*o and hello
return (match(y, x.substring(1)));
}
}
//nothing worked out
return false;
}
In the spirit of recursion (one of your tags) but not of Java, here is a Scheme implementation that gets all your test cases correct.
(define (match s1 s2) ; assumes s1 = string, s2 = pattern
(let matching ((l1 (string->list s1)) (l2 (string->list s2)))
(if (null? l1)
(or (null? l2) (eq? (car l2) #\*)) ; every #\*
(let ((c1 (car l1))
(c2 (car l2)))
(or (and (or (eq? c2 c1)
(eq? c2 #\#))
(matching (cdr l1) (cdr l2))) ; take one char from l1 and l2
(and (eq? c2 #\*)
(matching (cdr l1) l2))))))) ; take one char from l1
Note, for test cases with "*l*" the above gets the right answer but for the wrong reason. There are others that the above gets wrong (related to "*") but that are not in your test cases.

Categories