如何在Java中使用fill(int [] a,int from_Index,int to_Index,int val)?

时间:2018-04-11 09:34:53

标签: java fill

我想编写一个程序来计算不同窗口在屏幕上覆盖的区域。我有窗口的数量和每个窗口的x1,y1,x2,y2作为输入。我想在java中使用fill函数。我想创建一个桌面大小的矩阵,充满零。对于每个窗口,我想取窗口的宽度并将其输入到矩阵中,与窗口高度一样多行,并对所有窗口执行此操作,然后通过计算得到的矩阵对结果矩阵进行汇总,给出区域覆盖在屏幕上,无需处理重叠的窗口。 但我不知道如何使用填充矩阵。

2 个答案:

答案 0 :(得分:0)

假设您有一个像matrix[WIDTH][HEIGHT]这样的2-dim数组 您可以使用Arrays.fill()方法通过一次调用填充整个列。但是,您仍需要迭代列。

我创建了一个小程序来说明。希望它有所帮助:

import java.util.*;

public class TestArray
{
  public static final int SCREEN_WIDTH = 100;
  public static final int SCREEN_HEIGHT = 100;

  class WindowCoords
  {
    public int top;
    public int left;
    public int bottom;
    public int right;

    public WindowCoords(int top,
                        int left,
                        int bottom,
                        int right)
    {
      this.top = top;
      this.left = left;
      this.bottom = bottom;
      this.right = right;
    }
  } // class WindowCoords

  public List<WindowCoords> getWindows()
  {
    List<WindowCoords> result;
    result = new ArrayList<WindowCoords>();
    result.add(new WindowCoords(4, 67, 23, 89));
    result.add(new WindowCoords(18, 12, 65, 30));
    result.add(new WindowCoords(45, 3, 95, 15));
    result.add(new WindowCoords(67, 40, 93, 59));
    return (result);
  }

  public void run()
  {
    // Initialize matrix
    // Setting its contents to 0 not strictly necessary though I prefer to do so
    int[][] matrix;
    int     column;
    matrix = new int[SCREEN_WIDTH][SCREEN_HEIGHT];
    //for (column = 0; column < SCREEN_WIDTH; column++)
    //  Arrays.fill(matrix[column], 0);

    // Get windows
    List<WindowCoords> windows;
    windows = getWindows();

    // Fill covered screen
    Iterator<WindowCoords> it;
    WindowCoords           window;
    it = windows.iterator();
    while (it.hasNext())
    {
      window = it.next();
      for (column = window.left; column <= window.right; column++)
        Arrays.fill(matrix[column], window.top, window.bottom, 1);
    }

    // Show result
    int row;
    for (row = 0; row < SCREEN_HEIGHT; row++)
    {
      for (column = 0; column < SCREEN_WIDTH; column++)
        System.out.print(matrix[column][row]);
      System.out.println();
    }

  } // run

  public static void main(String[] args)
  {
    TestArray test;
    test = new TestArray();
    test.run();
  }

} // class TestArray

答案 1 :(得分:0)

只需一个简单的嵌套循环即可:

public static void main(String[] args) {
    int[][] matrix = new int[10][10];
    fill(matrix, 2, 2, 4, 4);

    System.out.println(Arrays.deepToString(matrix));
}

private static void fill(int[][] matrix, int x1, int y1, int x2, int y2) {
    for (int y = y1; y <= y2; y++) {
        for (int x = x1; x <= x2; x++) {
            matrix[y][x] = 1;
        }
    }
}