Is there something wrong with the code I made? - java

So our project is all about sets and it should display the union, intersection, difference and I am having doubts on my code because in the example given to us by our teacher, the elements of the set was already given and in the output there is no "null" result in the union and intersection BUT our challenge is to have the elements to be user input AND in my code there is a "null" result in my union and intersection. Is that okay?
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Set<Integer> a = new HashSet<Integer>();
a.addAll(Arrays.asList(new Integer[5]));
for () {
//scan code...
}
Set<Integer> b = new HashSet<Integer>();
b.addAll(Arrays.asList(new Integer[5]));
for () {
//scan code...
}
// UNION
Set<Integer> union = new HashSet<Integer>(a);
union.addAll(b);
System.out.print("\nUnion of the two Set: ");
System.out.println(union);
// INTERSECTION
Set<Integer> intersection = new HashSet<Integer>(a);
intersection.retainAll(b);
System.out.print("Intersection of the two Set: ");
System.out.println(intersection);
// DIFFERENCE
Set<Integer> difference = new HashSet<Integer>(a);
difference.removeAll(b);
System.out.print("Difference of the two Set: ");
System.out.println(difference);
}
OUTPUT: (TEACHER'S GIVEN CODE!)
Union of the two Set[0, 1, 2, 3, 4, 5, 7, 8, 9]
Intersection of the two Set[0, 1, 3, 4]
Difference of the two Set[2, 8, 9]
MY OUTPUT:
Set A :
3 4 2 1 0
Set B :
7 4 1 9 8
Union of the two Set: [null, 0, 1, 2, 3, 4, 7, 8, 9]
Intersection of the two Set: [null, 1, 4]
Difference of the two Set: [0, 2, 3]

You have the null because of these two lines in your code :
a.addAll(Arrays.asList(new Integer[5]));
b.addAll(Arrays.asList(new Integer[5]));
Just remove these two lines and your code should work.

I agree with #theincrediblethor, but as an explanation...
You are initializing a Set as if it were an array. Initially a Set is empty, and an array is uninitialized. You don't want to put "empty" Integers [null, null, null, null, null] in the Set, they will just stay there even when you add the real Integers on input.
Since Sets don't allow duplicates, 4 of the empty Integers are dropped upon add.
So you are left with 1 null and all of your input.

In your line
a.addAll(Arrays.asList(new Integer[5]));
new Integer[5] is creating an array of 5 null values [ null,null,null,null,null ]
Arrays.asList() just turns it into a Collection(List) of 5 null values
a.addAll() adds all the elements of your Collection into your Set and, as the values are unique, you only add one null
So you just have to remove that line, same for Set b
Try this code and you will see the step by step
import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;
public class Main
{
public static void main(String[] args) {
Integer[] arr = new Integer[5];
System.out.println(Arrays.toString(arr));
Set<Integer> a = new HashSet<Integer>();
a.addAll(Arrays.asList(arr));
System.out.println(a);
a.add(1);
System.out.println(a);
}
}
it prints

Related

Java take range from array

Does Java have a method of Array drop? In Scala we have: Array.drop(10).take(16) or maybe to take a range of members of an array?
In Java I can only do array[10] for example.
There is Arrays::copyOfRange:
It has three parameters:
original: the source array
from: the starting index, inclusive
to: the end index, exclusive
Not that it returns a new array, meaning that if you change the values of the resulting array, the original array does not change.
The method is overloaded to work for all primitive types and for objects.
Here's an example use:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
final int[] source = IntStream.range(0, 10).toArray()
System.out.println(Arrays.toString(source));
final int[] result = Arrays.copyOfRange(source, 3, 8);
System.out.println(Arrays.toString(result));
}
}
Which prints:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5, 6, 7]
For more information, see the docs
I think it's easiest to achieve such semantics by streaming the array:
SomeClass[] sourceArray = /* something */;
SomeClass[] result =
Arrays.stream(sourceArray).skip(10L).limit(16L).toArray(SomeClass[]::new);

How to count a no in array without loop?

Let's assume we have an array of 10 elements a[] = {2, 3, 4, 5, 3, 2, 3, 3, 3, 2}; and if have to check the number of occurrences of an specific element say 3 . Then how I will able to count it without loop? Because the number of elements may be so many. My question is: is there any Java method to find it?
Without writing a traditional for loop:
List<Integer> list = Arrays.asList(2, 3, 4, 5, 3, 2, 3, 3, 3, 2);
long occurences = list.stream().filter(n -> n == 3).count();
System.out.print(occurences);
With an array which is an object where you you have to iterate over elements to know each one, a loop is unavoidable.
My question is: is there any Java method to find it?
Yes but you should use a structure more suitable to your need such as a Map for example.
The idea is to use a Map to initialize values and the associated frequency. In this way, you didn't need any longer to perform loop when you want to know the frequency of a integer value.
public Map<Integer,Integer> createWithElements(int... values) {
Map<Integer,Integer> nbOccurencesByValue = new HashMap<>();
for (int value : values){
Integer actualNbOccurence = nbOccurencesByValue.get(value);
if (actualNbOccurence==null){
actualNbOccurence=0;
}
nbOccurencesByValue.put(value, ++actualNbOccurence);
}
return nbOccurencesByValue;
}
How to use it :
Map<Integer,Integer> nbOccurencesByValue = createWithElements(2, 3, 4, 5, 3, 2, 3, 3, 3, 2);
Integer nbOccurenceFor3Number = nbOccurencesByValue.get(3);

Write a program that determines if two groups of numbers can be formed in such a way that their sums are equal

Example:
Input: 3, 6, 3
Output: True (since 3 + 3 = 6)
Input: 3, 2, 6, 4
Output: False (since no combination will result in equality)
Input: 4, 7, 3, 6
Output: True (since 4 + 6 = 7 + 3)
can you guys give me an idea on how to code this?
i've started on how to code this but i'm confused on how I can add the numbers and compair them
I'll explain how a person could work on this without knowing magic words (like "partition problem", "dynamic programming", etc.) with which to consult some big book of answers (like Wikipedia).
If you take one instance of the largest not-yet-used number from the input and assign it to one of your two groups, then you have reduced the problem to a smaller instance of (a generalized version of) the same problem.
The generalized problem is, can you divide the input numbers into two groups such that the difference between the two groups' sums is a particular non-negative integer?
Let's say our input numbers are 4, 3, 2, 1 and we need to make two groups so that the difference between the groups' sums is 0.
We assign 4 to one of the groups, and in this particular case it doesn't matter which group.
Now our remaining input numbers are 3, 2, 1 and, ignoring the 4 that we already dealt with, we need to make these three numbers into two groups so that the difference between the groups' sums is 4. (That will balance out the difference between the two groups that we created by assigning the 4 to one of the groups.) As promised, this is a smaller instance of the original type of problem.
The difficulty is that sometimes, such as with 5, 5, 4, 3, 3 (example found in Wikipedia "Partition problem"), it's not obvious which group the next number needs to go into. If you keep track of what you've done, then when you find out your latest attempt didn't work, you can come back ("backtrack") and try the other way.
5, 5, 4, 3, 3 {} {}
5, 4, 3, 3 {5} {}
4, 3, 3 {5} {5}
3, 3 {5, 4} {5}
3 {5, 4} {5, 3}
{5, 4} {5, 3, 3} NO - backtrack
{5, 4, 3} {5, 3} NO - backtrack
3 {5, 4, 3} {5}
{5, 4, 3} {5, 3} NO - already tried - backtrack
{5, 4, 3, 3} {3} NO - backtrack
3, 3 {5} {5, 4} NO - symmetric to what we already tried - backtrack
4, 3, 3 {5, 5} {}
3, 3 {5, 5} {4}
3 {5, 5} {4, 3}
{5, 5} {4, 3, 3} YES
Will we be able to get the answer quickly? Well, this isn't the question that was asked, but in light of the complexity of backtracking, it's natural to ask. And the answer turns out to be, no, not even if we have the smartest person in the history of the world working for us. No one has ever found a method that is guaranteed to perform quickly no matter what instance of this kind of problem we give it. Maybe we can do pretty well for many instances of these problems, but in general and on average, a program to do this sort of thing is destined to be slow.
This is the partition problem, which is NP-complete. Despite that, there's a dynamic programming solution that you can use. See the Wikipedia article.
http://en.wikipedia.org/wiki/Partition_problem
public class Weirdie {
private boolean calculate(int[] array) {
boolean match = false;
List<Integer> list = new ArrayList<Integer>();
int length = array.length;
for(int i=0;i<length;i++) {
for(int j=i+1;j<length;j++) {
int sum = array[i] + array[j];
if(list.contains(sum)) {
match = true;
break;
} else {
list.add(sum);
}
}
if(match) {
break;
}
}
return match;
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] array = { 3, 6, 3, 4, 8};
int[] array2 = { 3, 2, 6, 4};
int[] array3 = { 4, 7, 3, 6 };
Weirdie w = new Weirdie();
System.out.println(w.calculate(array));
System.out.println(w.calculate(array2));
System.out.println(w.calculate(array3));
}
}
Actually I still confusing with your requirement.As your description,number group 1 {3,6,3} will output true because of 3+3=6.And you said number group 2 {3,2,6,4} will output false,but appearently 2+4=6 is also match your condition.With your third number group,I think the reason why number group 1 output true is 3+6=6+3.
To determine is a array can be divided into two equal summed arrays, we can also find a subset which has half the sum of the whole array.
For e.g: Input: 4, 7, 3, 6
We should find a sub set whose sum == 10, which is a simple DP prob.
public static boolean isSubset(int[] a, int sum, int n) {
if(sum == 0)
return true;
if(n<0)
return false;
return isSubset(a, sum-a[n], n-1) || isSubset(a, sum, n-1);
}
OK! just use brute force calculation, my checking every possible option
int[] numbersArray = new int[10];
int sum = 0;
for(int j = 0; j < numbersArray.lenght;j++) // sum
sum += numbersArray[j];
for(int i = 0; i < numbersArray.lenght;i++)
{
int numChecking = numbersArray[i]; // right half ..
if((sum-numChecking) == numChecking)
return true;
}
return false;
// i haven't tested it but, this will check all possibility's for 1 value..

Trouble understanding Multidimensional Arrays

So i am trying to understand multidimensional arrays a little better. So far, I understand there are 2 way to construct these arrays. One is
int[][] b = { { 1, 2 }, { 3, 4, 5 } };
The first array constructs row 0 with 2 columns ( column 0 and column 1). What i don't understand is why are these numbers chosen. Does it always have to be in numerical order, or do the numbers mean something more? If i were to create a new row would it start with 6? Would it just be better for me to construct it this way?
int[][] b = new int [2][];
b[0] = new int [2];
b[1] = new int [3];
Thanks for your help.
Those numbers are meant to be examples. You need not start your next row with "6" if it's not what your solution demands.
Either manner of construction is acceptable. You'd use the second one if you had to compute the values and didn't know them beforehand.
1, 2, 3, 4, and 5 are just data that got entered in this new array.
The array would look like this:
[
[1, 2]
[3, 4, 5]
]
so [0][0] = 1; [1][0] = 3, [1][2] = 5 etc
Those values are just chosen as example.
First: there is no multi-dimensional arrays in Java. There are only arrays containing arrays. Arrays of arrays if you prefer.
int[][] b = { { 1, 2 }, { 3, 4, 5 } };
constructs an array containing 2 arrays of int. The first array contains the numbers 1 and 2, and the second contains the numbers 3, 4 and 5. These numbers could be anything you want. The line declares and populates the array at the same time.
int[][] b = new int [2][];
b[0] = new int [2];
b[1] = new int [3];
constructs an array of arrays of ints, containing two null elements. Then, the first element of the outer array is initialized with an array of 2 ints, and the second element of the outer array is initialized with an array of 3 ints. All the ints are initialized to their default value: 0.

permute/scramble arraylist elements in java

suppose I have arraylist of integers...is there a way that I can generate a random permutation/arrangement of the elements in the arraylist
so if the list is {1,2,3,4,5,6}
calling some method randomPermute() would change it to something random like
{1,3,2,6,5,4}
Collections.shuffle() does the job:
public static void shuffle(List<?> list) -
Randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood.
http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle(java.util.List)
For example
ArrayList<Integer>anArrayList = new ArrayList<Integer>();
anArrayList.add(1);
anArrayList.add(2);
anArrayList.add(3);
anArrayList.add(4);
anArrayList.add(5);
System.out.println(anArrayList);
Collections.shuffle(anArrayList);
System.out.println(anArrayList);
Sample Output
[1, 2, 3, 4, 5]
[3, 5, 1, 2, 4]
You can use the Knuth shuffle: go through the positions 1 through n−1, and for each position i swap the element currently there with an arbitrarily chosen element from positions i through n, inclusive.
Edit: The answer by hooch is better. :)
A simple example:
ArrayList<MyObject> myObjects = new ArrayList<MyObject>();
//code -- load myObjects...
Collections.shuffle(myObjects);

Categories