2014-01-12 30 views
1

我想知道是否有更有效的方法來選擇循環中的變量。下面的代碼我已經工作,但我想有一個更好的方法來做到這一點,如果可能的話。Java在循環中選擇變量

Map<Character, Character> axes = new HashMap<Character, Character>(); 

(...) 

for (int w = 0; w < image.getWidth(); w++) { 
    for (int h = 0; h < image.getHeight(); h++) { 
     for (int d = 0; d < depth; d++) { 
      int x = axes.get('x') == 'w' ? w : (axes.get('x') == 'h' ? h : d); 
      int y = axes.get('y') == 'w' ? w : (axes.get('y') == 'h' ? h : d); 
      int z = axes.get('z') == 'w' ? w : (axes.get('z') == 'h' ? h : d); 

      (...) 

     } 
    } 
} 

在上面我所我需要一個圖像的某些座標分配到的3D深度,但雙方協調,它使用的變化取決於它朝的方向。有沒有更快的方法來執行代碼,而不必獨立循環?

回答

1

你可以試一下:

int[] coords = new int[3]; 
int width = image.getWidth(); 
int height = image.getHeight(); 
for (coords[0] = 0; coords[0] < width; ++coords[0]) 
{ 
    for (coords[1] = 0; coords[1] < height; ++coords[1]) 
    { 
     for (coords[2] = 0; coords[2] < depth; ++coords[2]) 
     { 
      int x = coords[x_idx]; 
      int y = coords[y_idx]; 
      int z = coords[z_idx]; 
      … 
     } 
    } 
} 
+0

+1,我在這裏寫的是相同的解決方案(你只是忘了告訴'x_idx = axes.get('x')=='w'?0:(axes.get('x')== 'h'?1:2);'在循環之前 –

+0

這些是很多額外的數組訪問,這可能是事實上放緩整個事情,因爲索引限制檢查必須始終進行。 – Ingo

+0

真棒,這造成了顯着的速度差異,謝謝! –

0

您可以將axes.get(...)調用移出循環。那應該夠快了。如果仍然太慢,也做環外的邏輯,並在內環做一個開關:像下面

final char xaxis = axes.get('x'); 
final char yaxis = axes.get('y'); 
final char zaxis = axes.get('z'); 
final int mode = xaxis == 'x' && yaxix == 'y' ? 1 : .... 

然後

  switch (mode) { 
      case 1: x = w; y = h; z = d; break; 
      case 2: ... 
      } 
      // work with x,y,z