I have 2 string arrays in a class.
I have a TestNG class in which I need to compare the values of those arrays in a Test method. The idea is, I should loop my Test method for n number of times where n = {size of one of the arrays}
#Test(invocationCount = {fixedCount}) does not work for me, since size of the array varies.
Please let me know if I have to provide some more information.
How about to check first, if the size of the two arrays are equal? If they are not equal, then the two arrays won't be equal either.
Edit:
This is a thread about equality checking using Java. If I remember well, Arrays.equals(array1, array2) is the proper way for contained element checking, but I'm not a Java guy.
If you'd like to check the elements by hand, use iteration on the arrays (you can, since their size equals now).
bool validator(int[] array1, int[] array2)
{
if (array1 == null || array2 == null)
{
return false;
}
if (array1.length != array2.length)
{
return false;
}
for (int i = 0; i < array1.length; i++)
{
if (array1[i] != array2[i])
{
return false;
}
}
return true;
}
Related
I'm new to Java and still trying to wrap my head around recursion.The function below returns true at the very first intersection between the two sorted lists list x and list y.
public static boolean checkIntersection(List<Integer> x, List<Integer> y) {
int i = 0;
int j = 0;
while (i < x.size() && j < y.size()) {
if (x.get(i).equals(y.get(j))) {
return true;
} else if (x.get(i) < y.get(j)) {
i++;
} else {
j++;
}
}
return false;
}
Now I've been trying to implement it using recursion instead, and I know that there should be a base case which is an empty list in this case and then try to reduce the list by excluding one element at a time and feed it back to the same recursive function, but I can't work out how to check for intersection as I pass the rest of the list over and over.
public static boolean recursiveChecking(List<Integer> x,List<Integer> y) {
if(x.size() == 0){
return false;
}
else {
return recursiveChecking(x.subList(1, x.size()-1), y);
}
}
Any help would be highly appreciated. Thank you.
General approach to making something recursive is to think of two things:
When can I produce an answer trivially? - An answer to this question lets you code the base case. In your situation, you can produce the answer trivially when at least one of two lists is empty (the result would be false) or the initial elements of both non-empty lists are the same (the result would be true)
How do I reduce the problem when the answer is non-trivial? - An answer to this question lets you decide how to make your recursive call. In your case you could, for example, remove the initial element of one of the lists before making the recursive call*, or pass ListIterator<Integer> in place of List<Integer> for a non-destructive solution.
*Of course in this case you need to take care of either adding your numbers back after the call, or make a copy of two lists before starting the recursive chain.
As the lists are ordered, your recursion should remove the first element of the list with the smaller first value. Then you have to return true, if both lists start with the same number and false if any of the lists is empty. Otherwise you keep removing elements. This would look something like this (This code is untested):
public static boolean recursiveChecking(List<Integer> x,List<Integer> y) {
if(x.size() == 0 || y.size() == 0){
return false;
} else if (x.get(0).equals(y.get(0))) {
return true;
} else {
if (x.get(0) < y.get(0)) {
return recursiveChecking(x.subList(1, x.size()-1), y);
} else {
return recursiveChecking(x, y.subList(1, y.size()-1));
}
}
}
We have a Final exam that is coming up, it is proctored this is just a study question, but I am having issues with two arrays I wrote out when I put them into eclipse. I would like some insight that may help me on the test, thanks.
Write a Java function that accepts two one-dimensional arrays of integers and returns true if and only if all the integers in the first array are contained in the second, and all the integers in the second array are contained in the first
public class Two1dimensionalArraysMain
{
public boolean main(int []array1, int []array2)
{
for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
if(array1[i]==array2[j])
{
break;
}
else if (array1[i] != array2[j])
return false;
}
return true;
}
}
}
The problem is that you're returning false too early.
Here's what it looks like you're trying to do. You look at each element X in array1. Then you compare that one element to each element in array2. If X equals any element in array2, you're good (so far) and you can look at the next element in array1. But if X is different from every element in array2, then return false.
That's a good approach. The problem is that you return false if X is different from any element in array2, not if it's different from every element. This is because as soon as you see two elements that are different between the two arrays, you return false right away.
public boolean main(int []array1, int []array2)
{
for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
if(array1[i]==array2[j])
{
break;
}
else if (array1[i] != array2[j])
return false;
}
return true;
}
}
To fix this: You need to do the return false check outside the for (int j... loop. There are a number of ways to do this, but my favorite is this:
Declare a boolean variable found. You will initialize this to false before going through array2.
Before you break, set found = true;, to indicate that the element X in array1 was found in array2.
After you're done going through array2, check found. If it's false, then you know the whole function should return false.
Also, your return true is in the wrong place. If you fix those two things, your method should work.
EDIT: I missed that the equality has to be two ways. The above, with my suggestions, will return true if every element in array1 is in array2, but not vice versa. One simple update would be to write a helper method allElementsAreIn that uses two int[] arrays, and then call it twice, something like allElementsAreIn(array1,array2) && allElementsAreIn(array2,array1).
By the way, don't call your function main. That name should be used only for the main program, which must be void and take a String[] parameter.
P.S. I'm assuming that the purpose of the exercise is to learn the basics of loops and such. In an actual production environment, it would be much simpler to use a Set as in amit's answer.
Best solution in my opinion is to use set equality, if that's allowed.
public static boolean checkArraysContainSameElements(int[] array1, int[] array2) {
Set<Integer> set1 = new HashSet<Integer>();
for (int x : array1) set1.add(x);
Set<Integer> set2 = new HashSet<Integer>();
for (int x : array2) set2.add(x);
return set1.equals(set2);
}
Other than that, I refer to #ajb to see what's wrong with the solution you proposed.
You can sort the array and compare in the loop:
public boolean checkArrayEquality(int[] source, int[] target)
{
Arrays.sort(source);
Arrays.sort(target);
if(source.length == target.length)
{
for (int i = 0; i < target.length; i++)
{
if(source[i] != target[i])
{
return false;
}
}
}
else
{
return false;
}
return true;
}
I want to check to see if two arrays share at least one term in common for my program.
I'm not quite sure what the code is to compare two arrays, but here is what I have so far;
if ((modWikiKeyArray).equals(inputArray[0]))
{
StringBuilder hyperlinkBuilder = new StringBuilder();
for(int i = 0; i < modWikiKeyArray.length; i++)
{
hyperlinkBuilder.append(modWikiKeyArray[i]);
}
}
How would I compare the array modWikiKeyArray to inputArray just to check and see if inputArray[0] is equal to any term inside of modWikiKeyArray?
Arrays.asList lets you build a list backed by an arbitrary array and use convenient Java Collections Framework features like the contains method:
Arrays.asList(oneArray).contains(elementFromAnotherArray)
If you want to see if the arrays have at least one element in common, you could build a HashSet out of one and loop over the other to try to find a common element:
boolean arraysIntersect(Object[] array1, Object[] array2) {
Set array1AsSet = HashSet(Arrays.asList(array1));
for (Object o : array2) {
if (array1AsSet.contains(o)) {
return true;
}
}
return false;
}
You can do the following
for(int i=0;i<modWikiKeyArray.length;i++) {
if(modWikiKeyArray[i].equals(inputArray[0])) {
System.out.println("Match found");
}
}
Note you need to override the equals() method of whatever array you are creating(Class of which array you are creating) .
Going by your code snippet, it looks like you need to check the presence of inputArray[0] only, in which case the following is sufficient:
boolean exists = java.util.Arrays.asList(modWikiKeyArray).contains(inputArray[0]);
Alternatively, you might also want to use ArrayUtils from Apache commons-lang:
boolean exists = ArrayUtils.contains(modWikiKeyArray, inputArray[0]);
However, if I read the text of your question, it seems you want to find if modWikiKeyArray contains at least one item from inputArray. For this you may also use retainAll from the Collections API to perform a list intersecion and see if the intersection list is non-empty.
However, the most primitive is still Aniket's method. However, I will modify it to reduce unnecessary operations:
int i = modWikiKeyArray.length - 1;
MyObject inputElement = inputArray[0];
boolean found = false;
for(; i != 0; i--) {
if(modWikiKeyArray[i].equals(inputElement)) {
found = true;
break;
}
}
I will explain the title better for starters. My problem is very similar to the common: find all permutations of an integer array problem.
I am trying to find, given a list of integers and a target number, if it is possible to select any combination of the numbers from the list, so that their sum matches the target.
It must be done using functional programming practices, so that means all loops and mutations are out, clever recursion only. Full disclosure: this is a homework assignment, and the method header is set as is by the professor. This is what I've got:
public static Integer sum(final List<Integer> values) {
if(values.isEmpty() || values == null) {
return 0;
}
else {
return values.get(0) + sum(values.subList(1, values.size()));
}
}
public static boolean groupExists(final List<Integer> numbers, final int target) {
if(numbers == null || numbers.isEmpty()) {
return false;
}
if(numbers.contains(target)) {
return true;
}
if(sum(numbers) == target) {
return true;
}
else {
groupExists(numbers.subList(1, numbers.size()), target);
return false;
}
}
The sum method is tested and working, the groupExists method is the one I'm working on. I think it's pretty close, if given a list[1,2,3,4], it will return true for targets such as 3 and 10, but false for 6, which confuses me because 1,2,3 are right in order and add to 6. Clearly something is missing. Also, The main problem I am looking at is that it is not testing all possible combinations, for example, the first and last numbers are not being added together as a possibility.
UPDATE:
After working for a bit based on Simon's answer, this is what I'm looking at:
public static boolean groupExists(final List<Integer> numbers, final int target) {
if(numbers == null || numbers.isEmpty()) {
return false;
}
if(numbers.isEmpty()) {
return false;
}
if(numbers.contains(target)) {
return true;
}
if(sum(numbers.subList(1, numbers.size())) == (target - numbers.get(0))) {
return true; }
else {
return groupExists(numbers.subList(1, numbers.size()), target);
}
}
For convenience, declare
static Integer head(final List<Integer> is) {
return is == null || is.isEmpty()? null : is.get(0);
}
static List<Integer> tail(final List<Integer> is) {
return is.size() < 2? null : is.subList(1, is.size());
}
Then your function is this:
static boolean groupExists(final List<Integer> is, final int target) {
return target == 0 || target > 0 && head(is) != null &&
(groupExists(tail(is), target) || groupExists(tail(is), target-head(is)));
}
There are no surprises, really, regular checking of base cases plus the final line, where the left and right operands search for a "group" that does or does not, respectively, include the head.
The way I have written it makes it obvious at first sight that these are all pure functions, but, since this is Java and not an FP language, this way of writing it is quite suboptimal. It would be better to cache any function calls that occur more than once into final local vars. That would still be by the book, of course.
Suppose you have n numbers a[0], a[1], ..., a[n-1], and you want to find out if some subset sums to N.
Suppose you have such a subset. Now, either a[0] is included, or it isn't. If it's included, then there must exist a subset of a[1], ..., a[n] which sums to N - a[0]. If it isn't, then there exists a subset of a[1], ..., a[n] which sums to N.
This leads you to a recursive solution.
Checking all combinations is factorial (there's a bit missing on your implementation).
Why not try a different (dynamic) approach: see the Hitchhikers Guide to Programming Contests, page 1 (Subset Sum).
Your main method will be something like:
boolean canSum(numbers, target) {
return computeVector(numbers)[target]
}
computeVector return the vector with all numbers that can be summed with the set of numbers.
The method computeVector is a bit trickier to do recursively, but you can do something like:
boolean[] computeVector(numbers, vector) {
if numbers is empty:
return vector
addNumber(numbers[0], vector)
return computeVector(tail(numbers), vector);
}
addNumber will take vector and 'fill it' with the new 'doable' numbers (see hitchhikers for an explanation). addNumber can also be a bit tricky, and I'll leave it for you. Basically you need to write the following loop in recrusive way:
for(j=M; j>=a[i]; j--)
m[j] |= m[j-a[i]];
The lists of all possible combinations can be reached by asking a very simple decision at each recursion. Does this combination contain the head of my list? Either it does or it doesn't, so there are 2 paths at each stage. If either path leads to a solution then we want to return true.
boolean combination(targetList, sourceList, target)
{
if ( sourceList.isEmpty() ) {
return sum(targetList) == target;
} else {
head = sourceList.pop();
without = combination(targetList, sourceList, target); // without head
targetList.push(head);
with = combination(targetList, sourceList, target); // with head
return with || without;
}
}
how to compare value in an array?
I have array named list which contains 12 elements. I see if value in index 0 is equal or not equal to value in index 2.
I have tried this code but it doesnt seems to work.
if ((list.get(0)==list.get(2) && list.get(1)==list.get(3))
{
System.out.println("equal")
}
If it's really an array, you want:
if (list[0] == list[2] && list[1] == list[3])
Note that if the array is of reference types, that's comparing by reference identity rather than for equality. You might want:
if (list[0].equals(list[2])) && list[1].equals(list[3]))
Although that will then go bang if any of the values is null. You might want a helper method to cope with this:
public static objectsEqual(Object o1, Object o2)
{
if (o1 == o2)
{
return true;
}
if (o1 == null || o2 == null)
{
return false;
}
return o1.equals(o2);
}
Then:
if (objectsEqual(list[0], list[2]) && objectsEqual(list[1], list[3]))
If you've really got an ArrayList instead of an array then all of the above still holds, just using list.get(x) instead of list[x] in each place.
if(list[0] == list[2] && list[1] == list[3]){
System.out.println("equal");
}
If they are strings:
if(list[0].equals(list[2]) && list[1].equals(list[3])){
System.out.println("equal");
}
You are comparing object references, not objects themselves. You need to use a method call. All classes inherit equals() from the root Object class, so it might work:
if(list.get(0).equals(list.get(2)) && list.get(1).equals(list.get(3)))
{
System.out.println("equal");
}
This article seems to be a good summary of other comparison methods available.