# UVA 101 – The Blocks Problem

Basic simulation. Just need to follow the instructions in the question.

```import java.awt.Point;
import java.util.ArrayList;
import java.util.Scanner;

/**
*
* @author Sanchit M. Bhatnagar
* @see http://uhunt.felix-halim.net/id/74004
*
*/
public class P101 {

public static void main(String args[]) // entry point from OS
{
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
@SuppressWarnings("unchecked")
ArrayList<Integer>[] blocks = new ArrayList[size];
for (int i = 0; i < size; i++) {
blocks[i] = new ArrayList<Integer>();
}

// System.out.println(Arrays.deepToString(blocks));

while (sc.hasNext()) {
String t = sc.next();
if (t.equals("quit")) {
break;
} else {
int a = sc.nextInt();
String x = sc.next();
int b = sc.nextInt();

if (a == b)
continue;

Point posA = findBlock(a, blocks);
Point posB = findBlock(b, blocks);

if (posA.x == posB.x)
continue;

if (t.equals("move")) {
moveBack(posA, blocks);
if (x.equals("onto")) {
moveBack(posB, blocks);
blocks[posA.x].remove(posA.y);
} else {
blocks[posA.x].remove(posA.y);
}
} else if (t.equals("pile")) {
if (x.equals("onto")) {
moveBack(posB, blocks);
int removed = 0;
int tSize = blocks[posA.x].size();
for (int i = posA.y; i < tSize; i++) {
removed++;
}
} else {
int removed = 0;
int tSize = blocks[posA.x].size();
for (int i = posA.y; i < tSize; i++) {
removed++;
}
}
}
}
// System.out.println(Arrays.deepToString(blocks));
}

// System.out.println(Arrays.deepToString(blocks));

for (int i = 0; i < size; i++) {
System.out.print(i + ":");
int tSize = blocks[i].size();
for (int j = 0; j < tSize; j++) {
System.out.print(" " + blocks[i].remove(0));
}
System.out.println();
}
sc.close();
}

private static void moveBack(Point posA, ArrayList<Integer>[] blocks) {
int removed = 0;
int tSize = blocks[posA.x].size();
for (int i = posA.y + 1; i < tSize; i++) {
int x = (Integer) blocks[posA.x].remove(i - removed);
removed++;
}
}

private static Point findBlock(int a, ArrayList<Integer>[] blocks) {
for (int i = 0; i < blocks.length; i++) {
for (int j = 0; j < blocks[i].size(); j++) {
if ((Integer) blocks[i].get(j) == a) {
return new Point(i, j);
}
}
}
return null;
}
}
```

This site uses Akismet to reduce spam. Learn how your comment data is processed.