Kotch
Kotch

Reputation: 334

Retrieving 2 closest numbers among 3

I'm looking for an algorithm to retrieve the two closest out of 3. I don't have any variable to get close to, just the three of this. For example, if i have 31, 52 and 84, i'd like the function to return 31 and 52.

I've tried some methods with array sorting, but fact is the three numbers are variables (X, Y and Z). When I sort my [X, Y, Z] array, i lose the order of vars.

I'm sure there's a very simple solution, i'm feeling quite silly right now... This is actually a MAXScript project so I'd like to avoid specific language functions, but any kind of information would be greatly appreciated.

Upvotes: 0

Views: 667

Answers (2)

Vlad
Vlad

Reputation: 35594

For just 3 variables, you need to compare the distances between them and choose the closest two (see David's answer). For n variables, you can do this trick:

  1. sort the values (O(n log n))
  2. go through the sorted list and find the smallest difference between the adjacent variables (O(n))
  3. result is the pair of variables with the smallest difference

Upvotes: 3

David Schwartz
David Schwartz

Reputation: 182779

Call the three numbers A, B, and C.

Compute three variables:

AB = (A - B)^2
BC = (B - C)^2
CA = (C - A)^2

Then compare AB, BC, and CA. If AB is smallest, output A and B. If BC is smallest, output B and C. If CA is smallest, output C and A.

If you want to make it a bit more elegant, create a structure that consists of three numbers and create three such structures as follows:

S1 = (A-B)^2, A, B
S2 = (B-C)^2, B, C
S3 = (C-A)^2, C, A

Then sort S1,S2,S3 based on the first number. For the entry that sorts first, output its second two numbers.

Upvotes: 4

Related Questions