2013-08-01 12 views
3

说我有阵列在数组中获取与索引相反元素的最佳方式是什么?

{0, 1, 2, 3, 4} 
  • 指数0和4是对立
  • 索引1和3是对立
  • 指数2的对面是未定义

或者

{0, 1, 2, 3, 4, 5} 
  • 指数在0和5是对立
  • 指数1和4是对立
  • 指数2和3是对立

我记得看到一个非常聪明的方式来做到这一点。喜欢的东西

i%array.length 
+0

嗯...是什么模式?双人项目如何相关? –

+0

没有模式,只是相反的指数 – user1873073

+3

第一个模式是有意义的(除了3将是它自己的“相反”)。第二个对我来说没有意义。为什么对(1,5),(2,4)和(3,6)? – asimes

回答

3

试试这个:

oppIndex = array.length - firstIndex - 1; 
+0

完美,谢谢! – user1873073

+0

@ user1873073 - 从问题“索引2的对面是不确定的”我想如果结果是相同的数字OP真的不想undefined –

0

按照你的第一个例子逻辑...

 if (array.length%2==0){ 
      for (int i =0; i<array.length/2; i++){ 
        syso("the opposite of "+ array[i] + " is " + array[array.length -1-i] 
      } 
     } 
     else { 
      for (int i =0; i<floor(array.length/2); i++){ 
        syso("the opposite of "+ array[i] + " is " + array[array.length -1-i] 
      } 
      i = i+1 
       syso("the opposite of "+ array[i] +" is undefined" 
     } 
+0

我觉得你是一个人。另外,我认为你只想每一次打印一次,而不是两次。 –

+0

这很好,但我认为我看到它在某处完成一行。 – user1873073

+0

现在应该会好点吗? (虽然不是很美丽) – Marc

1
array = {1, 2, 3, 4, 5} 
idx = 0 /* 0 is the first array position with value of 1 */ 

IF array.length - idx - 1 > idx 
    RETURN array[ array.length - idx - 1 ] /* returns array[4] == 5 */ 
ELSE 
    RETURN undefined 

array = {1, 2, 3, 4, 5} 
idx = 2 /* 2 is the third array position with value of 3 */ 

IF array.length - idx - 1 > idx /* 5 - 2 - 1 == 2 which is NOT greater than 2 */ 
    RETURN array[ array.length - idx - 1 ] 
ELSE 
    RETURN undefined 
相关问题