tore
tore

Reputation: 313

I need help making an if statement with many logical operators easier

I've tried searching for it, but I don't really now how to formulate the question correctly...

I have an if-statement with many logical operators. How do I do this easier ?

If (n == 1 ||n == 2 ||n == 3  ||n == 5 ||n == 9 ||n == 8 ||n == 7 ||n == 551 ||n == 17 ||n == 81 || etc etc)
{ //Stuff
}

I'm thinking in pseudo-code I want something like this:

List list = {1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, or 36 }

if n is in list, then {}

As you understand, I'm a beginner and I have problems formulating what I need.

Upvotes: 5

Views: 185

Answers (5)

Bohemian
Bohemian

Reputation: 424993

Try this:

 static private Set<Integer> set = new HashSet<Integer>(
     Arrays.asList(1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36));

then to test:

if (set.contains(n))

Using a HashSet will make it perform pretty well.

Upvotes: 2

premananth
premananth

Reputation: 179

function arrayinside(n, listofn) {
    var length = listofn.length;
    for(var i = 0; i < length; i++) {
        if(listofn[i] == n) return true;
    }
    return false;
}

Try this

Upvotes: 1

Aleks G
Aleks G

Reputation: 57316

Your List approach is correct. You can do something like this:

int[] values = {1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36 };
List<Integer> list = new ArrayList<Integer>();
if(values.asList(list).contains(n)) {
   ...
}

Upvotes: 1

npinti
npinti

Reputation: 52185

Yes, throw everything in an ArrayList and then use the .contains(Object obj) method:

List<Integer> numbers = new ArrayList<Integer>();
number.add(...;

if(numbers.contains(n))
{
    ...
}

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500155

How about:

int[] validOptions = { 1, 2, 3, 5, 7, 8, 9, 17, 81, 551 };

if (Arrays.binarySearch(validOptions, n) >= 0)
{
    // Yup, found it
}

Note that I reordered your original check (which had 551 before 17 for example) so that the array is sorted. A binary search will only work with sorted data.

I'm only suggesting an array here on the grounds that it's slightly easier to specify, particularly as you're dealing with a primitive type. If you want these to be dynamic, a List<Integer> or a HashSet<Integer> would be more appropriate.

Note that while it almost certainly doesn't matter while the set is small, it's worth considering the performance characteristics of different lookups:

  • HashSet.contains - O(1)
  • Arrays.binarySearch - O(log N)
  • ArrayList.contains - O(N)

Upvotes: 13

Related Questions