My humble solution here.
May have lots of potential bugs.
package amdocs;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class FallingBricks {
private int[][] board = new int[8][6];
public void fall(Brick brick, int pos) {
int[][] brickPos = brick.getPoint();
for (int j = board[0].length - 1; j >= 0; j--) {
int putPosition = 0;
for (int i = pos; i < pos + brick.getWidth(); i++) {
if (board[i][j] == 1) {
putPosition = j + 1;
break;
}
}
if (j != 0 && putPosition == 0) {
continue;
}
for (int m = 0; m < brickPos.length; m++) {
for (int n = 0; n < brickPos[m].length; n++) {
int line = putPosition + n;
if (brickPos[m][n] == 1) {
board[pos + m][line] = brickPos[m][n];
}
}
}
clearFullLine();
break;
}
}
private void clearFullLine() {
List<Integer> lines = new ArrayList<Integer>();
for (int j = 0; j < board[0].length; j++) {
boolean isFull = true;
for (int i = 0; i < board.length; i++) {
if (board[i][j] == 0) {
isFull = false;
break;
}
}
if (isFull) {
lines.add(j);
}
}
if (lines.size() == 0)
return;
Collections.sort(lines);
for (int i = 0; i < board.length; i++) {
for (Integer l : lines) {
board[i][l] = 0;
}
}
for (int m = 0; m < board.length; m++) {
for (int n = lines.get(0); n < board[m].length; n++) {
if (n + lines.size() < board[m].length)
board[m][n] = board[m][n + lines.size()];
}
}
}
public void printBoard() {
for (int j = board[0].length - 1; j >= 0; j--) {
for (int i = 0; i < board.length; i++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
FallingBricks fb = new FallingBricks();
fb.testCase4(fb);
fb.printBoard();
}
public void testCase1(FallingBricks fb ) {
fb.fall(Brick.B, 2);
fb.fall(Brick.A, 0);
fb.fall(Brick.A, 0);
fb.fall(Brick.E, 2);
fb.fall(Brick.A, 5);
fb.fall(Brick.G, 4);
}
public void testCase2(FallingBricks fb ) {
fb.fall(Brick.D, 0);
fb.fall(Brick.B, 1);
fb.fall(Brick.D, 2);
}
public void testCase3(FallingBricks fb ) {
fb.fall(Brick.F, 0);
fb.fall(Brick.F, 1);
fb.fall(Brick.F, 2);
fb.fall(Brick.F, 3);
fb.fall(Brick.F, 4);
fb.fall(Brick.F, 5);
fb.fall(Brick.F, 6);
fb.fall(Brick.F, 7);
}
public void testCase4(FallingBricks fb ) {
fb.fall(Brick.G, 4);
fb.fall(Brick.G, 0);
}
}
enum Brick {
A(new int[][] { { 1, 1 }, { 1, 1 } }, 2),
B(new int[][] { { 1, 1 }, { 1, 0 } }, 2),
C(new int[][] { { 0, 1 }, { 1, 1 } }, 2),
D(new int[][] { { 1, 1 }, { 0, 1 } }, 2),
E(new int[][] { { 1, 0 }, { 1, 1 } }, 2),
F(new int[][] { { 1, 1, 1, 1 }, { 0, 0, 0, 0 },{ 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, 1),
G(new int[][] { { 1, 0, 0, 0 }, { 1, 0, 0, 0 }, { 1, 0, 0, 0 }, { 1, 0, 0, 0 } }, 4);
private int[][] point;
private int width;
private Brick(int[][] point, int width) {
this.point = point;
this.width = width;
}
public int getWidth() {
return width;
}
public int[][] getPoint() {
return point;
}
}
Thanks,
Seabook