How to select an already created random true Boolean variable? - java

Lets say I have four Boolean Variables,
Boolean a;
Boolean b;
Boolean c;
Boolean d;
Now, before I select one of these variables, I run a function to find out if they are true or false (it's not relevant why they are true or false).
So lets say:
a = false;
b = true;
c = false;
d = true;
Now, because b and d are true, I want to randomly select one of those two; and, if three variables are true, then I would want to randomly select one from those three.
I am lost how I would be able to accomplish this.

You can use the class java.util.Random and generate a random number and set the bound to 1. Then it generates 0 or 1. Now you can check, if the random number is 0 or 1 and if it's 0 you select b and if its 1 you select d. And the same with 3 Booleans that are true.
// Import the class
import java.util.Random;
// Create an Instance of Random
Random r = new Random();
// Generate a random number between 0 and 1
short randomNumber = r.nextInt(1);
if (randomNumber == 0)
{
// do something with b
}
if (randomNumber == 1)
{
// do something with d
}

It seems that you try to select somehow a specific Boolean variable (a, b, c, d).
However, if unboxed boolean values are assigned to Boolean variable, they will be using the same shared instance:
Boolean a = false;
Boolean b = true;
Boolean c = false;
Boolean d = true;
System.out.println(a == c); // prints true, identical Boolean.FALSE
System.out.println(b == d); // prints true, identical Boolean.TRUE
In order to be distinguished, different Boolean variables need to be created with a constructor (which is deprecated):
Boolean a = new Boolean(false);
Boolean b = new Boolean(true);
Boolean c = new Boolean(false);
Boolean d = new Boolean(true);
System.out.println(a == c); // prints false, non-identical
System.out.println(a.equals(c)); // prints true, equal
System.out.println(b == d); // prints false, non-identical
System.out.println(b.equals(d)); // prints true, equal
Now, upon ensuring that we have different Boolean objects, we can select it randomly:
public static Boolean getTrueIndexRandomly(Boolean... flags) {
List<Boolean> list = Arrays.asList(flags);
// get indexes of flags whose values are true
int[] indexes = IntStream.range(0, list.size())
.filter(list::get)
.toArray();
Random random = new Random();
int randomIndex = indexes[random.nextInt(indexes.length)]; // select one index
System.out.print("random index=" + randomIndex);
return flags[randomIndex];
}
Test:
Boolean random;
System.out.println("Selecting from b, d");
for (int i = 0; i < 4; i++) {
System.out.print("#" + (i + 1) + ": ");
random = getTrueRandomly(a, b, c, d);
System.out.println(" -> " + (random == b ? "b": "d"));
}
a = new Boolean(true);
System.out.println("Selecting from a, b, d");
for (int i = 0; i < 4; i++) {
System.out.print("#" + (i + 1) + ": ");
random = getTrueRandomly(a, b, c, d);
System.out.println(" -> " + (random == a ? "a" : random == b ? "b" : "d"));
}
Output
Selecting from b, d
#1: random index=3 -> d
#2: random index=1 -> b
#3: random index=3 -> d
#4: random index=1 -> b
Selecting from a, b, d
#1: random index=3 -> d
#2: random index=1 -> b
#3: random index=1 -> b
#4: random index=0 -> a

Related

Program to determine if 3 sides form a valid triangle using Java

Given three integers a, b, and c, return true if a, b, and c could be the lengths of the sides of a right triangle. Return false otherwise. Recall that in a right triangle, each side must have a positive length, and the sum of the squares of the leg lengths must equal the square of the length of the hypotenuse.
isRightTriangle(3, 4, 5) → true
isRightTriangle(4, 3, 5) → true
isRightTriangle(5, 4, 3) → true
boolean isRightTriangle(int a, int b, int c) {
if(a>0 && b>0 && c>0){
if((Math.sqrt((double)a)+Math.sqrt((double)b))==Math.sqrt((double)c)){
return true;
}
else{
if((Math.sqrt((double)b)+Math.sqrt((double)c))==Math.sqrt((double)a)){
return true;
}
else{
if((Math.sqrt(c)+Math.sqrt(b))==Math.sqrt(a)){
return true;
}
else{
return false;
}
}
}
}
else{
return false;
}
}
You are using Math.sqrt instead of Math.pow(x, 2). You need to check that a^2+b^2=c^2, not sqrt(a)+sqrt(b)=sqrt(c).
boolean isRightTriangle(int a, int b, int c) {
// lets exit if variables are bad
if(a < 1 || b < 1 || c < 1) {
return false;
}
// lets create an array so we can sort
int[] arry = new int[3];
arry[0] = a;
arry[1] = b;
arry[2] = c;
Arrays.sort(arry);
// now that the array is sorted, the largest number (the hypotenuse) should be arry[2]
return Math.pow(arry[0], 2) + Math.pow(arry[1], 2) == Math.pow(arry[2], 2);
}

Generate two random number between 1 and 10 and run a do while loop while they not equal, my code runs but i dont want the numbers to be ever equal

i made some changes in my variable but still a and b will be the same at one point and the random number have to be unique cant be repeated
public static void main(String args[])
{
int a = 0;
int b = 0;
do
{
a = (int)((Math.random()*10)+1);// a number between 1 and 10
b = (int) ((Math.random()*10)+1);
System.out.print(a + " " +b);
}
while(a != b);
}
while (rand == randT) surely? On the basis that a and b don't change, plus the fact that you are using != instead of ==.

Calculating best case run time complexity of recursive algorithm?

In class i have started learning how to calculate the run time complexity functions of various algorithms and am finding it difficult. I am trying to calculate the best case rune time complexity of my recursive algorithm below.
At the moment i am choosing my fundamental operation to be a comparison between the index of two chars, and assuming i am trying to find the path where my algorithm outputs a result as soon as possible, i am thinking this first comparison being false would lead my algorithm to do this if i am correct.
Would i be correct in thinking the best case run time complexity function for this algorithm would be t(n) = 1 and in taking the comparison of indexes as a fundamental operation?
public class StringShuffleTest {
public static boolean isOrderedShuffle(String a, String b, String c){
//variables for the size of Strings a, b and c.
int n = a.length();
int m = b.length();
int len = c.length();
//if the length of c is not the length of a + b, return false.
if (len != (n + m)){
return false;
}
//if String c contains String b as a substring, then remove String b from c and make m = 0.
//This statement avoids errors when dealing with Strings with very similar characters.
if (c.contains(b)){
c = c.replace(b, "");
m = 0;
}
//if the length of a or b is 0, and c equals a or b, return true, otherwise,
//return false.
if (n == 0 || m == 0){
if (c.equals(a) || c.equals(b)){
return true;
}
else
return false;
}
//if String a has length 1, remove a from String c and make String a empty.
if (n == 1){
c = c.substring(0, c.indexOf(a.charAt(0))) + c.substring(c.indexOf(a.charAt(0)) +1);
a = "";
return isOrderedShuffle(a, b, c);
}
//An ordered shuffle of two given strings, a and b, is a string that can be formed by interspersing
//the characters of a and b in a way that maintains the left-to-right order of the characters from each
//string.
//Recursive algorithm to determine if String c is an ordered shuffle of a and b.
else
if (c.indexOf(a.charAt(0)) >= 0){
int indexOfFirsta = c.indexOf(a.charAt(0));
int indexOfSeconda = c.indexOf(a.charAt(1));
if (indexOfFirsta <= indexOfSeconda){//Taking as fund operation.
c = c.substring(0, indexOfFirsta) + c.substring(indexOfFirsta +1);
a = a.substring(1, n);
System.out.println(a);
System.out.println(c);
return isOrderedShuffle(a, b, c);
}
else
if (c.indexOf(b.charAt(0)) >= 0){
int indexOfFirstb = c.indexOf(b.charAt(0));
int indexOfSecondb = c.indexOf(b.charAt(1));
if (indexOfFirstb <= indexOfSecondb){
c = c.substring(0, indexOfFirstb) + c.substring(indexOfFirstb +1);
b = b.substring(1, m);
System.out.println(b);
System.out.println(c);
return isOrderedShuffle(a, b, c);
}
}
}
return false;
}
public static void main(String[] args) {
System.out.println(StringShuffleTest.isOrderedShuffle("abc", "def", "abedcf"));
}
}

check whether a string C is an interleaving of A and B

Given three strings A, B and C. Write a function that checks whether C is an interleaving of A and B. C is said to be interleaving A and B, if it contains all characters of A and B and order of all characters in individual strings is preserved.
For example:
'hotdog' is an interleaving of 'hot' and 'dog' (easy)
'superb' is an interleaving of 'up' and 'serb'
'heartache' is an interleaving of 'ear' and 'ache'
'chat' is an interleaving of 'hat' and 'cat'
'cheaters' is not an interleaving of 'chat' and 'seer', because while it contains all the letters from each, the letters from 'seer' do not appear in order
I find some solutions in net but below is my approach can somebody tell me am i missing something or my algo will work? thanks.
My Algo:
Traverse through a and c. While traversal we calculate two things first: whether the char is present or not and save the index i.e. f where the char is found. And as soon as we find the char we should put some special char in that place, so that we will not consider this char further.
For the next char in a search in the c from the index where you have found the previous char i.e. f. if we don't find than return.
Same you do for b as well.
If after doing the above step if we find false than repeat for first b than a and return the result.
e.g.
a = xxy, b = xxz and c = xxzxxxy
start with a:
for x in a, c = 0xzxxxy (i am putting 0 as special char)
for x in a, start from the index 0 onwards(because we have found the previous char at 0)c = 00zxxxy.
for y in a, c = 00zxxx0
for x in b, c = 00z0xx0
for x in b, c = 00z00x0
for z in b, we could not find z after the index 4 which was the index where we found the previous char for b.
as starting with a returns false so we will start with b now.
So start with b:
for x in b, c = 0xzxxxy
for x in b, c = 00zxxxy
for z in b, c = 000xxxy
for x in a, c = 0000xxy
for x in a, c = 00000xy
for y in a, c = 00000x0
hence true i.e.c is the interleaved string of a and b.
Your solution represents a greedy algorithm with a slight modification, because it counts a character in C as belonging to A on the first pass (or to B on the second pass) as soon as it finds a match. This will break for the following strings:
A = xxyxxy
B = xxzxxz
C = xxzxxyxxyxxz
The firs pass that counts a matching character as a member of A will turn C into
00zxx0000xxz
The second pass that counts a matching character as a member of B will turn C into
00000yxxyxx0
Here is a simple Java implementation of a memoized solution:
private static boolean checkOverlap(String a, String b, String c) {
Boolean[][][] memoize = new Boolean[a.length()+1][b.length()+1][c.length()+1];
return checkOverlap(a, b, c, 0, 0, 0, memoize);
}
private static boolean checkOverlap(
String a
, String b
, String c
, int pa
, int pb
, int pc
, Boolean[][][] memoize
) {
Boolean res = memoize[pa][pb][pc];
if (res != null) {
return (boolean)res;
}
if (pa == a.length() && pb == b.length() && pc == c.length()) {
res = true;
} else if (pc == c.length()) {
res = false;
} else {
res = false;
if (pa != a.length() && c.charAt(pc) == a.charAt(pa) && checkOverlap(a, b, c, pa+1, pb, pc+1, memoize)) {
res = true;
} else if (pb != b.length() && c.charAt(pc) == b.charAt(pb) && checkOverlap(a, b, c, pa, pb+1, pc+1, memoize)) {
res = true;
}
}
return (memoize[pa][pb][pc] = res);
}
Demo on ideone.
First, I'd check that the length of A and the length of B summed equal the length of C.
Next, check if the first character of A is equal to the first character of C.
If not, check if the first character of B is equal to the first character of C.
Check the other characters starting with either A or B, depending on which of the two conditions above was true.
Here's a method that will do the test:
public boolean isInterleaved(String a, String b, String c) {
int aIndex = 0;
int bIndex = 0;
int cIndex = 0;
while (cIndex < c.length()) {
if (aIndex < a.length()) {
if (a.charAt(aIndex) != c.charAt(cIndex)) { return false; }
cIndex++;
aIndex++;
}
if (bIndex < b.length()) {
if (b.charAt(bIndex) != c.charAt(cIndex)) { return false; }
cIndex++;
bIndex++;
}
}
return true;
}
You would call this method at most twice. The calls would be either
if (isInterleaved(a, b, c))
or
if (isInterleaved(b, a, c))
If the first character of A and the first character of B are equal, check the other characters starting with the A or B string you didn't start with in the previous step.
This way, you save the complicated testing for the strings that can possibly satisfy the conditions.
def isinterleave(a, b, c):
la = len(a)
lb = len(b)
lc = len(c)
if la + lb != lc: return False
if la == lb == lc == 0: return True
if (la > 0 and lb >0 and a[0] == b[0] == c[0]):
return isinterleave(a[1:], b, c[1:]) or isinterleave(a, b[1:], c[1:])
if (la > 0 and a[0] == c[0]):
return isinterleave(a[1:], b, c[1:])
if (lb > 0 and b[0] == c[0]):
return isinterleave(a, b[1:], c[1:])
return False

check if two integers sum to a third

Ok I'm doing this programming assignment and need a little help.
Here is the problem:
Given three ints, a b c, return true if it is possible to add two of the ints to get the third.
twoAsOne(1, 2, 3) → true
twoAsOne(3, 1, 2) → true
twoAsOne(3, 2, 2) → false
Here's the what I have gotten so far:
public boolean twoAsOne(int a, int b, int c) {
return a + b != c;
}
It keeps saying it is not fully correct and I do not know where I am going wrong.
The question asks if it is possible to add any two to get the remaining one. Your code tests only if the first two add to the third.
Thus, twoAsOne(3,1,2) should return true because 3 = 1 + 2; but you are only checking whether 3 + 1 = 2, which is false.
You're only checking one of the possibilities and, on top of that, you're checking it wrongly since you'll return false if a + b == c (because you're using the != operator).
I'm not going to do you homework for you, but the full list of possibilities is:
n1 = n2 + n3
n2 = n1 + n3
n3 = n1 + n2
It should be a simple matter: the result should be true if any of those is true. Otherwise the result should be false.
Or, to provide even a more obvious clue: it should be true if one or more of those conditions are met. Else it should be false.
I don't know how much more obvious I can make it without writing the code for you :-)
Update: And now that more than enough time has probably elapsed to make the homework point moot, here's my solution:
public boolean twoAsOne (int n1, int n2, int n3) {
if (n1 == n2 + n3) return true;
if (n2 == n1 + n3) return true;
if (n3 == n1 + n2) return true;
return false;
}
Although those last two lines could be replaced with:
return (n3 == n1 + n2);
I prefer the (to me, anyway) more readable version.
Besides the answers provided by itowlson and Pax, since you are dealing with ints, there is a possibility that they will overflow, e.g.
Integer.MAX_VALUE + 1 == Integer.MIN_VALUE
Which is not mathematically true
You may want to check this kind of scenarios to make your program complete.
Your code only takes into consideration the sum of int a and int b. The solution requires all possibilities to be covered i.e. "sum of int a and int c" and "sum of int b and int c". Refer to the code mentioned below, hope it helps!
public boolean twoAsOne(int a, int b, int c) {
return ((a + b == c) || (b + c == a) || (c + a == b));
}
Dude I hope you got the answer by now... if you haven't
public boolean twoAsOne(int a, int b, int c) {
return ((a+b==c) || (a+c==b) || (b+c==a));
}
I might be very late yet I have minimized it. twoAsOne
public boolean twoAsOne(integer a, integer b, integer c){
return ((a+b) == c ? true : (a+c) == b ? true : (b+c == a)? true : false);
}
package get_third;
public class Get_third {
int a , b ,c ;
boolean third_value(int a , int b , int c){
if(a+b==c||b+c==a||c+a==b)
{
return true;
}
else
return false ;
}
public static void main(String[] args) {
Get_third obj =new Get_third();
System.out.println(obj.third_value(1, 2, 3));
System.out.println(obj.third_value(3, 1, 2));
System.out.println(obj.third_value(3, 2, 2));
}
}
// start
public boolean twoAsOne(int a, int b, int c) {
if (a + b == c) {
return true;
}
else if (a + c == b) {
return true;
}
else if (b + c == a) {
return true;
}
else {
return false;
}
}
// end

Categories

Resources