Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to get an elements opposite index in an array?

Tags:

algorithm

Say I have array

{0, 1, 2, 3, 4}
  • index 0 and 4 are opposites
  • index 1 and 3 are opposites
  • index 2's opposite is undefined

Or

 {0, 1, 2, 3, 4, 5}
  • index 0 and 5 are opposites
  • index 1 and 4 are opposites
  • index 2 and 3 are opposites

I remember seeing a really clever way to do this. Something like

i%array.length 
like image 638
user1873073 Avatar asked Aug 01 '13 15:08

user1873073


1 Answers

Try this one:

oppIndex = array.length - firstIndex - 1;
like image 126
beaker Avatar answered Sep 20 '22 01:09

beaker