There are 3 string arrays of different lengths. How to iterate through all 3 arrays after 1 cycle?
2 answers
String[] a = new String[10]; String[] b = new String[20]; String[] c = new String[30]; for (int i = 0; i < Math.max(a.length, Math.max(b.length, c.length)); i++) { if(i < a.length) { // ΠΎΠΏΠ΅ΡΠ°ΡΠΈΡ ΠΌΠ°ΡΡΠΈΠ²ΠΎΠΌ a } if(i < b.length) { // ΠΎΠΏΠ΅ΡΠ°ΡΠΈΡ ΠΌΠ°ΡΡΠΈΠ²ΠΎΠΌ b } if(i < c.length) { // ΠΎΠΏΠ΅ΡΠ°ΡΠΈΡ ΠΌΠ°ΡΡΠΈΠ²ΠΎΠΌ c } } - oneinstead of
maxyou can simply writei < a.length || i < b.length || i < c.lengthi < a.length || i < b.length || i < c.lengthi < a.length || i < b.length || i < c.lengthis likely to run faster. Well, either calculate the maximum once before the cycle, and not count at each iteration. - Alex Chermenin - @AlexChermenin who knows what array operations will be performed in the body of the loop? For example, if a certain condition is met, the following code can be executed:
a = new String(a.length*2);Of course, if this is excluded, then it is better to calculate the maximum value before the cycle or do as you wrote. - GreyGoblin
|
String arr1 = new String[]{"a"}; String arr2 = new String[]{"a", "b"}; String arr3 = new String[]{"a", "b", "c"}; for(int i = 0; i < arr1.length + arr2.length + arr3.length; i++) { String arr; int indexOfArr; if(i < arr1.length) { arr = arr1; indexOfArr = i; } else if (i < arr1.length + arr2.length) { arr = arr2; indexOfArr = i - arr1.length; } else { arr = arr3; indexOfArr = i - arr1.length - arr2.length; } System.out.println(arr[indexOfArr]); } - 2some complicated muddied) - Alexey Shimansky
- @ Alexey Shimansky, it's just the first thing that came to mind) It seems that it should work and it is relatively flexible - the array index is known) - YuriySPb β¦
- @Roman, I will not object to edits) - Yuriy SPb β¦
|