I need help simplifying an if statement with lots of logical operators

I tried to look for it, but now I do not know how to correctly formulate the question ...

I have if-statementwith many logical operators. How do I make 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 think in pseudocode 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 know, I am a beginner, and I have problems with the wording of what I need.

+5
source share
5 answers

What 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 initial check (which had, for example, 551 to 17) to sort the array. Binary search will only work with sorted data.

, , . , , List<Integer> HashSet<Integer>.

, , , :

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

, ArrayList, .contains(Object obj):

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

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

Try the following:

 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 check:

if (set.contains(n))

Using it HashSetwill do it very well.

+2
source

Your approach to the list 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)) {
   ...
}
+1
source
function arrayinside(n, listofn) {
    var length = listofn.length;
    for(var i = 0; i < length; i++) {
        if(listofn[i] == n) return true;
    }
    return false;
}

try it

+1
source

All Articles