-2

For example let assume that I defined set of 5 integers.

int a = 5;
int b = 7;
int c = 8;
int d = 9;
int e = 10;

Now on the fly i receive five values a1,b1,c1,d1,e1. These can have any values but not limited to the ones i defined.

I want to return true if at-least 3 values i received on fly matches with the ones i defined.

Public String atleastThreeMatches(){
(a1=a && b1 = b && c1 = c) || .....
}

Doing something like above wont be feasible, if i have to match large number of values.

Is there a function in Java or anything which can accomplish this?

Dumb_Shock
  • 1,050
  • 1
  • 13
  • 23
  • 1
    Use a counter. `if (something matches) count++`; `if (something else matches) count++`; etc. Then `if (count >= 3) ...`. If you can put all the things you're matching in an array, so that you can do this with a loop, that would be much better. – ajb Oct 16 '16 at 06:00
  • 2
    Did you mean *Java* or *Javascript*. I ask because of the `function` keyword. – selbie Oct 16 '16 at 06:01
  • 1
    It would be easier for you if you define the 5 integers in an array like `int[] ints = new int[] {5,7,8,9,10};` – c0der Oct 16 '16 at 06:07

2 Answers2

1

I'm not sure where you meant to declare your variables. Either in the class declaration, parameters to the method, or on the stack. But the general logic is this:

boolean atLeastThreeMatches()
{
    int count = 0;
    count += (a == a1)?1:0;
    count += (b == b1)?1:0;
    count += (c == c1)?1:0;
    count += (d == d1)?1:0;
    count += (e == e1)?1:0;
    return (count >= 3);
}
selbie
  • 100,020
  • 15
  • 103
  • 173
1

Intersection of Sets

Learn about the Java Collections framework. In particular, the Set interface and implementations such as HashSet.

You need an intersection of Set objects as discussed on this Question. You can work with the Set::retainAll method.

Or for convenience, look at adding the Google Guava library to your project. That library offers a handy set intersection method.

Look at the size of the resulting intersection to see if is more or less than three.

Of course you would have to use objects like Integer rather than the primitive int.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154