0

i have one array with the following values [1,2,3,4,5]

i want to print a message when my array hold the values 1,2,3. How do I do this? :)

int[] myarray = new int[] {1,2,3,4,5};
if ( ... ) {
    System.out.println("This array is on fire!");

I suppose you could do like this:

if (myarray[0]==1 && myarray[1]==2 && myarray[2]==3) {
     .....
    }

but if it's possible, i will avoid this. I wish to avoid the position in the array being a factor.

user1014224
  • 13
  • 3
  • 5

9 Answers9

3

Unluckily Arrays.asList(myarray) doesnt work for int, as noted in the comments, i forgot... So use Integer as Array-Type or convert first in an Integer-List:

   List<Integer> intList = new ArrayList<Integer>();
    for (int index = 0; index < myarray.length; index++)
    {
        intList.add(myarray[index]);
    }

as pointed out here, then follow the old solution with this list:

if (intList.contains(1)  && intList.contains(2) && intList.contains(3)) {
...
}
Community
  • 1
  • 1
jk2
  • 79
  • 7
2

You could write a utility method as follows (assumes the array is sorted before hand please see the update if it's not the case):

public static boolean checkIfOnFire(int[] arr, int... nums) {
    for(int n : nums) {
        if(Arrays.binarySearch(arr, n) < 0) {
            return false;
        }
    }
    return true;
}

Test with:

int[] myarray = new int[] {1,2,3,4,5};

System.out.println(checkIfOnFire(myarray, 1, 2, 3));
System.out.println(checkIfOnFire(myarray, 1, 2, 7));

Prints:

true
false

Update:

Since I am using the Arrays.binarySearch. The input array to the checkIfOnFire method has to be sorted as it is in your example.

But if your array might not be sorted then checkIfOnFire has to be modified as follows:

public static boolean checkIfOnFire(int[] arr, int... nums) {
    //make a copy of the original array
    int[] copyArr = new int[arr.length];
    System.arraycopy(arr, 0, copyArr, 0, arr.length);
    //sort the copy
    Arrays.sort(copyArr);
    for(int n : nums) {
        if(Arrays.binarySearch(copyArr, n) < 0) {
            return false;
        }
    }
    return true;
}
Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
  • 2
    This assumes the initial array is sorted. – Greg Case Dec 08 '11 at 16:55
  • 1
    +1 even with sort, this way is still faster then the asList() than 3x contains. with QuickSort/mergeSort, checking 3 candidates in this way is O(nlogn)+3 x O(logn), with list, is 3x O(n). and during the binarySearch, there is still room to optimize, e.g. found 1, then next search for (2), just taking the subarray after element 1 (assuming ascending sorted). of course, it depends if performance is critical for OP. – Kent Dec 08 '11 at 17:11
1

It ain't pretty, but if you wrote something like this:

public static boolean containsAll(int[] arrayToTest, int... values) {
    return asList(arrayToTest).containsAll(asList(values));     
}

public static List<Integer> asList(int[] values) {
    List<Integer> asList = new ArrayList<Integer>(values.length);
    for (int intVal : values) {
        asList.add(intVal);
    }
    return asList;
}

You can then call it like this:

int[] myarray = new int[] {1,2,3,4,5};
boolean result = containsAll(myarray, 1, 2, 3);
Greg Case
  • 3,200
  • 1
  • 19
  • 17
0

Longer solution, but requires only one pass. Can be easily customized to check for any number of items.

public boolean onFire(int array[])
{
    boolean found1 = false;
    boolean found2 = false;
    boolean found3 = false;
    for (int i : array) {
        if(i==1)
        {
            found1= true;
            continue;
        }
        if(i==2)
        {
            found2= true;
            continue;
        }
        if(i==3)
        {
            found3= true;
            continue;
        }
        if(found1&&found2&&found3)
            return true;
    }
    if(found1&&found2&&found3)
         return true;
    return false;       
}
ruhsuzbaykus
  • 13,240
  • 2
  • 20
  • 21
  • Wow. This is a smorgasboard of code smells. Strange method names, overspecialization, unnecessary use of `continue` when `else` would work, redundant success checks, checking for a boolean instead of returning a boolean value. Did I miss any? – Mike Samuel Dec 08 '11 at 17:04
0

If your wanted ints are non-negative, small, and dense; and you don't care about the order they appear in ints, then:

BitSet wanted = new BitSet();
wanted.set(1);
wanted.set(2);
wanted.set(3);

for (int i : ints) {
  wanted.clear(i);
}

boolean hasAll = wanted.cardinality() == 0;

If you do care about order, then you probably want to test whether one array is a sub-sequence of another: Get the list of index in subsequence matching

Community
  • 1
  • 1
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
0

To find the elements in any order in the array, first add the elements you're interested to a hash map. Then see if they are in the array.

Runtime: O(m) to add to map, to iterate over array O(n), m < n. Total O(n).

In the code below, call main() to run the sample I wrote.

 Map<Integer,Boolean> lookFor = new HashMap<Integer,Boolean>();

 void main(){
    int[] array = new int[] {1,2,3,4,5};
    addMeaningfulValues();
    System.out.println( arrayHasValues(lookFor, array) );
 }

 void addMeaningfulValues(){
    lookFor.put(1,false);
    lookFor.put(2,false);
    lookFor.put(3,false);
 }

 boolean arrayHasValues(Map<Integer,Boolean> values, int [] array){
    //mark entries found in array
    for (int i=0; i<array.length; i++){
        if (values.containsKey(array[i])){
            values.put(array[i], true);
        }
    }

    //go over map entries and see if they have all been found in the array
    for (Boolean crtValue: values.values()){
        if (!crtValue){
            return false;
        }
    }

    return true;
 }
Adrian
  • 5,603
  • 8
  • 53
  • 85
0

Put it in a Collection or List and do a contains for each item you are looking for.

Integer[] myarray = {1,2,3,4,5};
List<Integer> intList = Arrays.asList(myArray);

if (intList.contains(1) && intList.contains(2) && intList.contains(3))
    // print your message
Robin
  • 24,062
  • 5
  • 49
  • 58
  • I tried this: Integer[] myarray={0,0,0,0,0,0,0,0}; List myarray2 = Arrays.asList(myarray); It did not work, any ideas? I get error lines under "List" and Arrays". I forgot to import something? – user1014224 Dec 08 '11 at 16:49
0

Make use of the containsAll method in the Collection interface.

Collection<Integer> coll = new ArrayList<Integer>();
Collection<Integer> test = new ArrayList<Integer>();

for( int i=1; i<=5; i++)
    coll.add(i);

test.add(1);
test.add(2);
test.add(3);

System.out.println(coll.containsAll(test));
Gowtham
  • 1,465
  • 1
  • 15
  • 26
0

Due to wide use of collections java considered as collection is a framework and each collections consisting of a method contains(Object o) to check whether an element is existing or not in a collection.

  1. so first we can convert the int[] array to a List

    List<Integer> list=new ArrayList<Integer>();
            int[] myarray = new int[] {1,2,3,4,5};
            for(int i=0;i<myarray.length;i++)
            {
                list.add(myarray[i]);           
            }
    
  2. please use list.contains(Object o) to check whether its existing or not

     for(Integer i:list)
            {
                if(list.contains(1)&&list.contains(2)&&list.contains(3))
                {
                    flag=true;
                    break;
                }
    
            }
    

and check the complete code below

import java.io.IOException;
import java.util.ArrayList;

import java.util.List;



public class Test {


    public static void main(String[] args) throws IOException {
        boolean flag=false;
        List<Integer> list=new ArrayList<Integer>();
        int[] myarray = new int[] {1,2,3,4,5};
        for(int i=0;i<myarray.length;i++)
        {
            list.add(myarray[i]);           
        }
        for(Integer i:list)
        {
            if(list.contains(1)&&list.contains(2)&&list.contains(3))
            {
                flag=true;
                break;
            }

        }

        if(flag)
        {
            System.out.println("yes contain");

        }
        else
            System.out.println("NO");

    }

}
Noufal Panolan
  • 1,357
  • 2
  • 14
  • 27