如何使这个Java for循环更易读?

huangapple go评论73阅读模式
英文:

How Can This Java For Loop Be More Readable?

问题

我正在尝试找到一种方法来减少这种重复,我尝试过使用更多的for循环,但由于每个数组的遍历方式都不同,我感到困难。

for (int i = 0; i < size; i++) {
  warray[i][0] = narray[i][0] * pcarray[i][0];
  warray[i][1] = narray[i][0] * pcarray[i][1];
  warray[i][2] = narray[i][1] * pcarray[i][0];
  warray[i][3] = narray[i][1] * pcarray[i][1];
  warray[i][4] = narray[i][2] * pcarray[i][0];
  warray[i][5] = narray[i][2] * pcarray[i][1];
  warray[i][6] = narray[i][3] * pcarray[i][0];
  warray[i][7] = narray[i][3] * pcarray[i][1];
  warray[i][8] = narray[i][4] * pcarray[i][0];
  warray[i][9] = narray[i][4] * pcarray[i][1];
  warray[i][10] = narray[i][5] * pcarray[i][0];
  warray[i][11] = narray[i][5] * pcarray[i][1];
  warray[i][12] = narray[i][6] * pcarray[i][0];
  warray[i][13] = narray[i][6] * pcarray[i][1];
  warray[i][14] = narray[i][7] * pcarray[i][0];
  warray[i][15] = narray[i][7] * pcarray[i][1];
  warray[i][16] = narray[i][8] * pcarray[i][0];
  warray[i][17] = narray[i][8] * pcarray[i][1];
  warray[i][18] = narray[i][9] * pcarray[i][0];
  warray[i][19] = narray[i][9] * pcarray[i][1];
}
英文:

I am trying to figure out a way to achieve this without so much repetition, I have tried using more for loops, but since each array has to been looped through so differently I am struggling.

for (int i = 0; i &lt; size; i++) {
  warray[i][0] = narray[i][0] * pcarray[i][0];
  warray[i][1] = narray[i][0] * pcarray[i][1];
  warray[i][2] = narray[i][1] * pcarray[i][0];
  warray[i][3] = narray[i][1] * pcarray[i][1];
  warray[i][4] = narray[i][2] * pcarray[i][0];
  warray[i][5] = narray[i][2] * pcarray[i][1];
  warray[i][6] = narray[i][3] * pcarray[i][0];
  warray[i][7] = narray[i][3] * pcarray[i][1];
  warray[i][8] = narray[i][4] * pcarray[i][0];
  warray[i][9] = narray[i][4] * pcarray[i][1];
  warray[i][10] = narray[i][5] * pcarray[i][0];
  warray[i][11] = narray[i][5] * pcarray[i][1];
  warray[i][12] = narray[i][6] * pcarray[i][0];
  warray[i][13] = narray[i][6] * pcarray[i][1];
  warray[i][14] = narray[i][7] * pcarray[i][0];
  warray[i][15] = narray[i][7] * pcarray[i][1];
  warray[i][16] = narray[i][8] * pcarray[i][0];
  warray[i][17] = narray[i][8] * pcarray[i][1];
  warray[i][18] = narray[i][9] * pcarray[i][0];
  warray[i][19] = narray[i][9] * pcarray[i][1];
}

答案1

得分: 4

虽然不同,但它们确实遵循一种模式:

for (int i = 0; i < size; i++)
    for (int j = 0; j < 20; j++)
        warray[i][j] = narray[i][j/2] * pcarray[i][j%2];
英文:

While different, they do follow a pattern:

for (int i = 0; i &lt; size; i++) 
for (int j = 0; j &lt; 20; j++ ) 
warray [i][j] = narray [i][j/2] * pcarray[i][j%2];

huangapple
  • 本文由 发表于 2020年8月5日 06:24:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63255882.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定