- Home /
How to check if the difference between any pair of numbers in an array is less than some value?
Hello guys!!
EXPLANATION: So I have an array of Speed values and I want to check if the difference between any pair of numbers is less than 1. If so, bool = true. This is what I have so far:
 public float[] speedArray;
 public bool changeSpeed;
 
 void Update()
     {
         for (int i = 0; i < speedArray.Length; i++)
         {
             for (int j = i + 1; j < speedArray.Length; j++)
             {
                 if (Mathf.Abs(speedArray[i] - speedArray[j]) < 1f)
                     changeSpeed = true;
                 else
                     changeSpeed = false;
             }
         }
     }
PROBLEM: The problem is that with this code it doesnt immediately set changeSpeed = false, because some differences can be > 1... For example: if i have {0.5, 0.75, 2} it will return changeSpeed = true (between 0.75 and 0.5) and changeSpeed = false (between 0.5 and 2 / between 0.75 and 2).
ANSWER?: I think that the answer is to introduce a WHILE loop instead of the IF loop. However, I dont know how to do it, I have never used WHILE loops because once I used them and Unity crashed...
Thanks in advance!!
 changeSpeed |= $$anonymous$$athf.Abs(speedArray[i] - speedArray[j]) < 1f;
or
 if( $$anonymous$$athf.Abs(speedArray[i] - speedArray[j]) < 1f )
 {
     changeSpeed = true;
     break;// stops this for loop
 }
Follow this Question
Related Questions
If statement seeming to give false positive 2 Answers
How to change a large number of booleans as fast as possible without sacrificing framerate? 1 Answer
Make player move to location and stop within a certain distance 1 Answer
Rerun a script after it finishes, when it already has multiple Coroutines? 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                