i need help figuring out how to use contain properly [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 months ago.
Improve this question
hello i wanted to know why contain is not working and how to make it work. my Goal is to be able to print out false if it has 2 or 3. i am not sure if i am doing it correctly or if i'm on the right track.
public class Assignment7 {
public static void main(String[] args) {
int[] array0 = {3, 5, 6};
System.out.println("Your implementation of no23 method printed out: " + no23(array0) );
}
public static void no23(boolean array0){
int number = 2;
int numberB = 3;
int theNumbers = number & numberB;
boolean statemnt = array0.contains(theNumbers);
}
}

You have multiple problems.
Arrays have no contains method
array0.contains(theNumbers)
You cannot call contains on an array. Arrays have no such method.
There are several ways to search an array in Java. If your array is sorted, use Arrays.binarySearch.
Ampersand (&) flips bits
Your use of & is not doing what you think. That operator manipulates bits. See The Java Tutorials by Oracle.com, free of cost.
What you meant to do was create a collection of int values. To do that use an array or use a Collection object such as List or Set. See The Java Tutorials by Oracle to learn about the Java Collections Framework.
Solution
Use a pair of vertical bars for a logical OR operator. Returns true if either or both conditions are true. See The Java Tutorials by Oracle.
int[] arr = { 3, 5, 6 } ;
int x = 2 ;
int y = 3 ;
boolean arrayContainsEitherNumber =
( Arrays.binarySearch( arr , x ) < 0 )
||
( Arrays.binarySearch( arr , y ) < 0 )
;
Get fancy with streams.
int[] arr = { 3 , 5 , 6 };
boolean hit =
Arrays
.stream( arr ) // Returns an `IntStream`, a series of each `int` value in the array.
.filter( i -> ( i == 2 ) || ( i == 3 ) ) // Skips any elements not meeting our criteria.
.findAny() // Halts the stream when first element reaches this point.
.isPresent(); // Returns true if the payload of this optional exists, false if no payload.
System.out.println( "hit = " + hit );
hit = true
Declare a return type
As commented by Dawood ibn Kareem, your method neglected to return the result to the calling code.
Change the void:
public static void no23( boolean array0 ) { … }
… to boolean and return your result:
public static boolean no23( boolean array0 ) {
…
return statemnt ;
}
You may detect a theme in this Answer: Study The Java Tutorials by Oracle before posting here.

I don't understand your question very well, but theNumbers is always equal to 00000010 & 00000011 = 00000010 = 2.
& operator is not the same as the && operator. The first one takes two numbers in binary form, and performs an AND operation like shown above.
2 in binary = 00000010
3 in binary = 00000011
2 & 3 is 00000010 & 00000011 which is 00000010
The second takes two booleans, and returns true if both are true, else returns false.
Effectively, your function is just checking if your array contains the number 2. If you want to check if there is either the number one (1) or the number two (2), you need to do :
public static void no23(int[] array0){ // Also, should be an array
boolean containsTwoOrThree = array0.contains(2) || array0.contains(3);
System.out.println(containsTwoOrThree); // Will print either true or false
if(containsTwoOrThree) System.out.println("Contains two or three");
else System.out.println("Doesn't contain");
// Simple java arrays do not have a "contain" method.
// Either use Java Lists, or use a for loop to check for values in.
}
EDIT: Arrays in java don't have a contains function. Check this answer:
How do I determine whether an array contains a particular value in Java?

Related

Check whether an specific index has been already used - Bitwise?

I wanna say that I appreciate every contribution on the following problem;
I am currently programming an array shuffler that is shuffling the elements of an array to different randomized positions without changing the instance, so there is no need for revaluating the array field with the returning created array instance (the invocation of that shuffling). I want to create an alternative to other already existing shuffle algorithms like the Fisher-Yates shuffle algorithm, as an experiment. So I tried several operations but I think I am stuck. I could create an array that stores already used indicies and create a random index that has not been used yet (during the iteration of every element within the array that I want to shuffle). But I want to make this way more cleaner. As the bitwise operations could help me, but just with 2^x hexadecimals.
Here is an example on what I want to achieve and what I've already tried, but simplified:
//Integer that holds information on what indices are being used
int used = 0;
//Some indices being used
used |= 3;
used |= 4;
used |= 6;
//Check whether the 2, 4 are used
boolean isUsed2 = (used & 2) != 0; //=> false as 2 is not used?
boolean isUsed4 = (used & 4) != 0; //=> true as 4 is used?
So basically what I do not understand is how I can create an integer, that contains information on what specific values have been used and which have not. So to determine if the index 2 or 0 or 8 have been used yet.
Hope my english was understandable.
Sincerly
You have to right-shift your bitMask by index and bitwise and it with 0x1.
public boolean getBitState(int bitIndex, int bitMask) {
return (bitMask >> bitIndex & 0x1) == 0x1;
}
true = 1, false = 0
Setting a bit...
// returns new bitmask value
public int setBitState(int bitIndex, boolean value, int bitMask) {
if (value) {
return bitMask |= (0x1 << bitIndex);
} else {
return bitMask &= ~(0x1 << bitIndex);
}
}

How do I return multiple integers when the return type is simply int? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have to implement the following function:
public int solution(int[] A) {
// smth
}
However, this function may have zero or more solutions, I mean no solution (then should return -1), one solution, two solutions, etc. As you see the function just has int as return type (not an array) and I cannot change it. What should I do, if for example this function should return two values (5 and 9) or three values (1, 10, and 7)? How can I return them?
I thought about tuples, but I believe there is a better way to solve it.
Why don't you use crypting? This only works, if your solutions and numbers of solutions are small and you know two upper limits (number of solutions and biggest size of solution), but you can put more information in one int. Here mult is a number greater than the greatest expected solution:
public int solution(int[] A) {
int returnValue = 0;
//solution is an array of your solutions
for(i=0; i<solution.length; i++){
returnValue=returnValue*mult;
returnValue+=solution[i];
}
return returnValue;
}
public List<Integer> retrieveSolutions(int solution){
List<Integer> decryptedSolutions = new ArrayList<>();
while(solution>mult){
decryptedSolutions.add(solution%mult);
solution = (int) solution/mult;
}
return decryptedSolutions;
}
Just beware the case solution=0 is ignored here and you might get bigger values than the max-Value of Integer (hence you have to make sure, your upperBound+1 (=mult) power the biggest number of solutions+1 is smaller than the max-Value of Integer). Also negative solutions would break this (you can avoid this, if you know the lower bound of the solutions). An alternative would be (as mentioned in the comments) to put the solutions in an mutable Object given in the arguments:
Either in the array as Peter stated in his answer (works only, if the argument array has more elements, than your solutions) and now you have the solutions in the given array and the return value tells how many solutions you got:
public int solution(int[] A) {
int numberSolutions = solutions.length;
for(int i=0; i<solutions.length; i++){
A[i]=solutions[i];
}
return numberSolutions;
}
or in an extra "bag"
public int solution(int[] A, NumberBag putTheSolutionsHere) {
// puts solutions in your NumberBag, whatever Object you might want to use here (preferable List implementation)
}
If you cannot change the signature, you only option is to change the input. While that would be the worst possible solution, it might be your only one. You could return the number of solutions. e.g.
// return all the positive numbers
public int solution(int[] array) {
// put all the positive numbers at the start.
return numOfPositives;
}
A better solution would be to return an array of results
public int[] solution(int[] input)
If you can't change the function, overload it - write the same function with different signature.
more on overloading
If you can add one argument to the signature, add any Collection and the method will populate the Collection (trivial).
If you cannot change the signature and cannot change the return type : is it for a good reason? Discuss with the one who asked you to do it.
If there is a good reason for that (or if it is a sort of algorithmic exercise), you can use some bit masking. In java, an int is encoded on 32 bits. If the possible solution are smalls, you can divide those 32 bits in small groups and store each solution in a group.
Here is a solution which shows how you could store up to 8 solutions in [0; 15] by using groups of 4 bits:
public static void main(String[] args) throws Exception {
List<Integer> values = Arrays.asList(5, 7, 3, 8, 9);
String collect = values.stream().map(Object::toString).collect(Collectors.joining(", "));
System.out.println("Values to encode : "+collect);
int _1111 = (2 << 3) - 1;
System.out.println("\nMasks : ");
for (int i = 0; i < values.size(); i++) {
System.out.println(padWith0(Integer.toString(_1111 << 4 * i, 2)));
}
System.out.println("\nEncoding : ");
int result = 0;
for (int i = 0; i< values.size() ; i++) {
int partial = values.get(i) << (4 * i);
System.out.println(values.get(i) +" => " + padWith0(Integer.toString(partial, 2)));
result += partial;
}
System.out.println(" => "+Integer.toString(result, 2));
System.out.println("\nRestitution : ");
for(int i = 0; i< values.size(); i++) {
int mask = _1111 << (4 * i);
int partial = (result & mask) >> (4 * i);
System.out.println(Integer.toString(partial, 2) +" => " + partial);
}
}
public static String padWith0(String s) {
return ("00000000000000000000000000000000" + s).substring(s.length());
}
Output :
Values to encode : 5, 7, 3, 8, 9
Masks :
00000000000000000000000000001111
00000000000000000000000011110000
00000000000000000000111100000000
00000000000000001111000000000000
00000000000011110000000000000000
Encoding :
5 => 00000000000000000000000000000101
7 => 00000000000000000000000001110000
3 => 00000000000000000000001100000000
8 => 00000000000000001000000000000000
9 => 00000000000010010000000000000000
=> 00000000000010011000001101110101
Restitution :
101 => 5
111 => 7
11 => 3
1000 => 8
1001 => 9

Finding all Logical Combinations of a Set

I am writing to ask if anyone knows how to go about this. I do not need the code, I would just like the logic behind doing this. So I have a set {A,B,C,D,E}. Now I want to find all combinations of and or OR operators amongst the values in the set.
Some examples below.
A and B and C and D and E
A and B and C and D or E
A and B and C or D and E
From what I know there is 2^n-1 possibilities in the case above. So in the specific example above we would have 8 combinations.
In addition to the Above the values in the set can have two possibilities. For simplicities sake lets say A can be True or False. Likewise B,C,D and E. So what we would potentially have is something like the following :
A=True and B=True and C=True and D=True and E=True
A=True and B=True and C=True and D=True and E=False
A=True and B=True and C=True and D=True or E=True
and so on. So taking this into account we would have 2^(2 * n-1) combinations. So in our specific example above again we would have 16 combinations for a set of 4.
Is there an algorithm that already does this? If not would anyone have some logic to implement this in Java
Thanks,
I think you're saying you want to enumerate (perhaps print) all the distinct expressions of the forms you have described, for some set size n. Since each one can be characterized by a set of flags (=True vs =False at positions 1 ... n, and And vs Or at positions 1 ... n - 1), you can represent each expression as an integer, with each flag corresponding to one (binary) bit. If n has a value for which you could hope to explicitly enumerate all the possibilities, such an integer will be well within the range of a Java long. For comfortably being able to enumerate all the possibilities, such an integer will be within the range of a Java int.
One way to proceed, therefore, would be to write a method to decode in-range integers into expressions according to their bit patterns. You can then iterate over all the appropriate integers (i.e. 0 ... (1 << (2 * n)) - 1), and decode each one into the corresponding expression.
If you have to get possible combination of five boolean values, you can do one thing -
Iterate a loop from zero to binary value "11111".
In each iteration you will get a unique combination of 0 and 1.
Convert 1 to true and 0 to false.
I hope below code will be helpful :
import java.util.ArrayList;
public class Test{
public static void main (String[] args)
{
ArrayList<boolean[]> result = new ArrayList<boolean[]>();
int max_num = Integer.parseInt("11111", 2);
for(int i=max_num; i>=0; i--)
{
String val = String.format("%5s", Integer.toBinaryString(i)).replace(' ', '0');
boolean[] arr = new boolean[5];
char[] charArray = val.toCharArray();
for(int j=0; j<charArray.length;j++)
{
if(charArray[j]=='1')
{
arr[j]=true;
}
else
{
arr[j]=false;
}
}
result.add(arr);
arr=null;
val=null;
}
for(int i=0;i<result.size();i++)
{
for(boolean b: result.get(i))
{
System.out.print(b+" ");
}
System.out.println();
}
}
}
To change the variable count :
Replace same count of 1 with "11111". e.g. if variable count is 6, it should be "111111"
Change "%5s" accordingly. e.g. if variable count is 6, it should be "%6s".
Initialize array "arr" with same count.

How to compare ints stored in linked lists - Java

I'm looking for some advice on a Java assignment. What I'm asked to do is perform different operations on numbers that are stored in a linked list, with each digit in a separate node. The point is to write a program that can do arithmetic on numbers that are very very large.
The particular problem that I'm looking for help on is for writing a method that compares two numbers, similar to regular compareTo() method for ints. It should return -1 if this.num < num, +1 if this.num > num, and 0 if they are equal.
What's making this difficult for me is the fact that the assignment specifies that the linked lists should store the numbers in reverse order. For example, the linked list for the number 145 would look like:
5 => 4 => 1 => null
This makes it easier to add numbers together but it's making it a headache for me when trying to compare. Here's what I've come up with, the comments explain how it's supposed to work.
public int compareTo(LLNum list)
{ // Compares two numbers.
// If the two numbers are of a different length, clearly the shortest is the smallest.
// If the two numbers are of equal length, call traverseToCompare to do the comparison.
if (this.len > list.len)
{
compareResult = 1;
}
else if (this.len < list.len)
{
compareResult = -1;
}
else if (this.len == list.len)
{
traverseToCompare(this.head, list.head);
}
return compareResult;
}
public void traverseToCompare(ListNode node1, ListNode node2)
{ // In the case that both numbers are of the same length, recursively traverse the list.
// compare each digit individually while unwinding the stack.
// Once two digits are found to be different, break out of the unwinding (Note: I could not find a way of breaking out)
// Since the dominant digit is at the tail end, this ensures the least number of comparisons.
if (node1 == null || node2 == null)
{ // Base case. Handles the case where both numbers are identical.
compareResult = 0;
return;
}
traverseToCompare(node1.getNext(), node2.getNext());
if (node1.getItem() > node2.getItem())
{
compareResult = 1;
}
if (node1.getItem() < node2.getItem())
{
compareResult = -1;
}
return;
}
The numbers being in reverse order is what pulled me towards recursion. I thought I would recursively traverse the list and then compare each digit on the way out, and somehow break out of the recursion at the first digits that are not the same. I realize this is not a usual way to use recursion but I wasn't sure how else to do it. Is there a way I could break without just throwing an exception? I think that might be a little too sloppy. Or any suggestions on how to do this without recursion?
Please don't just give me some code to copy and paste. I'm just looking to be pointed in the right direction. Thanks!
If I had to do this I would first check the lengths of both lists (like you did). If they're equal, a better way to do the comparison would be to create an iterator for each list. You can then increment the iterators at the same time and compare the values at that position in the linked lists. Doing it this way, you can simply stop comparing the lists once you have determined that one contains a larger number than the other.
In traverseToCompare you will need to take care of some cases.
It will be better and clean if you do not use the recursion.
Following can be a solution
boolean areSame = true;
boolean digitDiffer = false;
int compareResult = 0;
int length = node1.length
for(int i=0; i<length; i++)
{
if(!digitDiffer && ((node1.getItem() == node2.getItem()))
{
continue
}
else
{
digitDiffer = true;
if(node1.getItem() >= node2.getItem())
{
compareResult = 1
}
else
{
compareResult = -1;
}
}
}
return compareResult;
The best way to do it is to traverse the list for each number and construct the number and then compare the 2 numbers.
The way to construct a number from the list would be
int i = 0
int f = 1
Do while GetNext() <> Null
i = i + GetCurrentItem() * f
f = f * 10
End Do
For eg. if the number is 145, then the list would have 5->4->1
So running the above code
i = 0
f = 1
i = i + 5*1 = 5
f = f * 10 = 10
i = i + 4*10 = 45
f = f * 10 = 100
i = i + 1*100 = 145
f = f * 10 = 1000
So it comes out with i = 145.
It would have been much easier to do using plain String; as you could store data of any length. But anyway the requirement is for LinkedList :
Now as the data is stored in revers order; this means you can't decide response of compareTo method until you go through the complete list, as most significant data is stored at last position.
5 --> 4 --> 1 == 145
1 --> 4 --> 5 == 541
So read through the whole least; then you can store the value in a String and then decide compareTo method result.
traverseToCompare method is called for same length items. So you can write your own algorithm to compare two numbers stored in String.
Edit
If String is not allowed
Then will suggest you to do the same thing manually; iterate through the whole list compare the last node, if last node is same then compare the previous node and so on...

combination of combination java

I need to find combination of combination in JAVA.
I have for instance 6 students in class. Out of them, I need to create combination of 4 people in group, and for each group I can choose an intimate group of 2.
I have to make sure that there are no doubles (order does not matter).! and need to print the 4 people group.
However, this is the hard part:
So defining students with numbers:
If I print out 1234 as one of the combinations, I can't print out1256 as well, since 12 appears both in 1234 and in 1256.
How can I write it in Java?
EDITED
output of ([1,2,3,4,5],3,2) will be:
Combinations without repetition (n=5, r=3)
{1,2,3} {1,2,4} {1,2,5} {1,3,4} {1,3,5} {1,4,5} {2,3,4} {2,3,5} {2,4,5} {3,4,5}
deleting repeating groups of 2 elements, will leave me only:
{1,2,3} {1,4,5} (i deleted groups that have combinations of 12,13,23,45,14,15 since they already appear in the first two that I have found.
Ok, here's the simple emulation of the process you described. But I use binary numbers to present set, it makes manipulations easier. For example, number 19 is 10011 in binary form: it means students 0, 3 and 4 are selected (there're 1's in those positions).
A little helper first.
// return all subsets of 'set', having size 'subsetSize'
Set<Integer> allSubsets(int set, int subsetSize) {
Set<Integer> result = new HashSet<Integer>();
if (subsetSize == 0) {
result.add(0);
return result;
}
if (set == 0) {
return result;
}
// check if 1st element is present
if (set % 2 == 1) {
// use 1st element, one less element to collect
for (Integer i : allSubsets(set / 2, subsetSize - 1)) {
result.add(i * 2 + 1);
}
}
// not use 1st element
for (Integer i : allSubsets(set / 2, subsetSize)) {
result.add(i * 2);
}
return result;
}
And main program. Suggestions are welcome.
int N = 5;
int M = 3;
int Z = 2;
List<Integer> result = new ArrayList<Integer>();
// get all groups of M elements from 'wholeSet'
int wholeSet = (1 << N) - 1;
for (int s : allSubsets(wholeSet, M)) {
// Check all subsets of 'Z' elements from set 's'
boolean valid = true;
for (int t : allSubsets(s, Z)) {
// check if this Z-element subset already was used
for (int past : result) {
// check if 't' is subset of 'past' set
if ((past|t) == past) {
valid = false;
break;
}
}
if (!valid) {
break;
}
}
if (valid) {
// none of Z-element subsets of 's' were used before
result.add(s);
}
}
But it may require improvements (like memoization) for big inputs. But for now, since you don't say what kind of input you expect, I assume this is good enough.
Imagine you have a Student object with an equals comparing their Primarykey. In your example, student 1 will return 1, 2 will return 2 and so on.
Put them all in the set, this will ensure that there will be no double.
Iterate though the set by 4 then by 2 and will return you your desired result.

Categories