我有一段代码,但我想避免使用java流,因为android不支持流。这是我的代码:
import java.util.Arrays;
import static java.util.Arrays.stream;
import java.util.concurrent.*;
public class VogelsApproximationMethod {
final static int[] demand = {30, 20, 70, 30, 60};
final static int[] supply = {50, 60, 50, 50};
final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15},
{19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}};
final static int nRows = supply.length;
final static int nCols = demand.length;
static boolean[] rowDone = new boolean[nRows];
static boolean[] colDone = new boolean[nCols];
static int[][] result = new int[nRows][nCols];
static ExecutorService es = Executors.newFixedThreadPool(2);
public static void main(String[] args) throws Exception {
int supplyLeft = stream(supply).sum();
int totalCost = 0;
while (supplyLeft > 0) {
int[] cell = nextCell();
int r = cell[0];
int c = cell[1];
int quantity = Math.min(demand[c], supply[r]);
demand[c] -= quantity;
if (demand[c] == 0)
colDone[c] = true;
supply[r] -= quantity;
if (supply[r] == 0)
rowDone[r] = true;
result[r][c] = quantity;
supplyLeft -= quantity;
totalCost += quantity * costs[r][c];
}
stream(result).forEach(a -> System.out.println(Arrays.toString(a)));
System.out.println("Total cost: " + totalCost);
es.shutdown();
}
如果有人能帮我,我将不胜感激,因为我不明白stream是如何工作的。
这很容易,你可以像Mike M在他的评论中建议的那样使用for循环,见下面的例子:
int supplyLeft = 0;
int[] supply = {50, 60, 50, 50};
for (int i : supply) {
supplyLeft += i;
}
System.out.println(supplyLeft);
取代
int supplyLeft = stream(supply).sum();
如果你也不想要foreach,那么
int supplyLeft = 0;
for (int i = 0; i < supply.length; i++) {
supplyLeft += supply[i];
}
System.out.println(sum);
至于在2D数组中迭代并替换如下所示的java-8流,则涉及
stream(result).forEach(a -> System.out.println(Arrays.toString(a)));
您可以根据需要使用for loop
或Arrays.deepToString()
,请参阅以下示例:
//assume your array is below, you can replace it with results everywhere
int[][] costs= { { 16, 16, 13, 22, 17 }, { 14, 14, 13, 19, 15 },
{ 19, 19, 20, 23, 50 }, { 50, 12, 50, 15, 11 } };
for (int i = 0; i < costs.length; i++) {
System.out.println(Arrays.toString(costs[i]));
}
以上for loop
将以以下方式打印阵列
[16, 16, 13, 22, 17]
[14, 14, 13, 19, 15]
[19, 19, 20, 23, 50]
[50, 12, 50, 15, 11]
如果使用Arrays.deepToString(costs)
,则会得到如下所示的输出:
[[16, 16, 13, 22, 17], [14, 14, 13, 19, 15], [19, 19, 20, 23, 50], [50, 12, 50, 15, 11]]
以上替换