Question

Java code for percolation, code compiles correctly but when it takes values for Input10.txt , the...

Java code for percolation, code compiles correctly but when it takes values for Input10.txt , the code is suppose to comeback that the system percolates but instead it comes back with the exception. Photos below show the exception. I belive there may be an issue with my logic in the for loop for when to throw the exception. also, i have put the values of Input10.txt at the bottom to try and use to see the exception.

The exception i get is: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 10
   at Percolation.isOpen(Percolation.java:83)
   at Percolation.open(Percolation.java:45)
   at Percolation.main(Percolation.java:121)

// Models an N-by-N percolation system.
public class Percolation {
private int N;
private int virtualTop;
private int virtualBottom;
private boolean[][] sites; // N-by-N grid
// Used for determining whether the system is percolate
private WeightedQuickUnionUF weightedQuickUnionUF1;
// Used for opening sites
private WeightedQuickUnionUF weightedQuickUnionUF2;
private int openSiteNumber;
  
// Creates an N-by-N grid, with all sites blocked.
public Percolation(int N) {
if (N <= 0) {
throw new IllegalArgumentException("N must be greater than 0.");
}
this.N = N;
sites = new boolean[N][N];
// Has both virtualTop and virtualBottom
weightedQuickUnionUF1 = new WeightedQuickUnionUF(N * N + 2);
// Has only virtualTop
weightedQuickUnionUF2 = new WeightedQuickUnionUF(N * N + 1);
  
virtualTop = N * N;
virtualBottom = N * N + 1;
openSiteNumber = 0;
}
  
  
// throw an exception for invalid indices
private void validateIndex(int i, int j) {
// col and row are range of 1 ~ N
if (i < 0 || i > N)
throw new IndexOutOfBoundsException("Row must be range of 0 ~ N.");
if (j < 0 || j > N)
throw new IndexOutOfBoundsException("Col must be range of 0 ~ N.");
}
  
// Opens site (i, j) if it is not open already.
public void open(int i, int j) {
validateIndex(i, j);
  
if (!isOpen(i, j)) {
  
int idx = encode(i, j);
sites[i - 1][j - 1] = true;
openSiteNumber++;
if (i == 1) {
weightedQuickUnionUF1.union(idx, virtualTop);
weightedQuickUnionUF2.union(idx, virtualTop);
}
  
if (i == N)
weightedQuickUnionUF1.union(idx, virtualBottom);
  
if (i > 1 && isOpen(i - 1, j)) {
weightedQuickUnionUF1.union(idx, encode(i - 1, j));
weightedQuickUnionUF2.union(idx, encode(i - 1, j));
}
  
if (i < N && isOpen(i + 1, j)) {
weightedQuickUnionUF1.union(idx, encode(i + 1, j));
weightedQuickUnionUF2.union(idx, encode(i + 1, j));
}
  
if (j > 1 && isOpen(i, j - 1)) {
weightedQuickUnionUF1.union(idx, encode(i, j - 1));
weightedQuickUnionUF2.union(idx, encode(i, j - 1));
}
  
if (j < N && isOpen(i, j + 1)) {
weightedQuickUnionUF1.union(idx, encode(i, j + 1));
weightedQuickUnionUF2.union(idx, encode(i, j + 1));
}
}
}

// Checks if site (i, j) is open.
public boolean isOpen(int i, int j) {
validateIndex(i, j);
return sites[i - 1][j - 1];
}

// Checks if site (i, j) is full.
public boolean isFull(int i, int j) {
boolean isfull = false;
validateIndex(i, j);
if (isOpen(i, j)) {
isfull = weightedQuickUnionUF2.connected(encode(i, j), virtualTop);
}
return isfull;
}

// Returns the number of open sites.
public int numberOfOpenSites() {
return openSiteNumber;
}

// Checks if the system percolates.
public boolean percolates() {
return weightedQuickUnionUF1.connected(virtualBottom, virtualTop);
}

// Returns an integer ID (1...N) for site (i, j).
private int encode(int i, int j) {
return (i - 1) * N + j - 1;
  
}

// Test client. [DO NOT EDIT]
public static void main(String[] args) {
String filename = args[0];
In in = new In(filename);
int N = in.readInt();
Percolation perc = new Percolation(N);
while (!in.isEmpty()) {
int i = in.readInt();
int j = in.readInt();
perc.open(i, j);
}
StdOut.println(perc.numberOfOpenSites() + " open sites");
if (perc.percolates()) {
StdOut.println("percolates");
}
else {
StdOut.println("does not percolate");
}
  
// Check if site (i, j) optionally specified on the command line
// is full.
if (args.length == 3) {
int i = Integer.parseInt(args[1]);
int j = Integer.parseInt(args[2]);
StdOut.println(perc.isFull(i, j));
}
}
}

these are the values in Input10.txt:

10
9 1
1 9
5 7
1 5
0 3
7 3
9 0
3 1
3 7
8 2
1 1
8 0
3 2
4 4
4 6
1 7
5 3
6 4
8 5
2 6
3 6
6 0
8 3
2 9
0 9
9 9
8 6
0 4
8 7
5 0
1 4
2 3
5 8
4 7
2 1
3 5
0 6
6 8
2 8
3 3
3 9
2 4
2 7
0 7
2 0
5 6
1 2
6 3
8 9
6 5
4 1
7 2
9 7
6 9
3 4
7 9

0 0
Add a comment Improve this question Transcribed image text
Answer #1

// Checks if site (i, j) is open.
public boolean isOpen(int i, int j) {
validateIndex(i, j);
return sites[i - 1][j - 1];
}

In the above function you checked the validity of indexes i and j, but you are using i-1 and j-1 in the return statement. Therefore, you should check the validity if i-1 and j-1 instead if i and i. Your method should be like this:

// Checks if site (i, j) is open.
public boolean isOpen(int i, int j) {
validateIndex(i-1, j-1);
return sites[i - 1][j - 1];
}

N.B.

I hope your problem will be solve if you change the code accordingly. If you face problem then share with me in the comment section.I'll help you.

Add a comment
Know the answer?
Add Answer to:
Java code for percolation, code compiles correctly but when it takes values for Input10.txt , the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • *JAVA* Can somebody take a look at my current challenge? I need to throw a different...

    *JAVA* Can somebody take a look at my current challenge? I need to throw a different exception when a)(b is entered. It should throw "Correct number of parenthesis but incorrect syntax" The code is as follows. Stack class: public class ArrayStack<E> {    private int top, size;    private E arrS[];    private static final int MAX_STACK_SIZE = 10;    public ArrayStack() {        this.arrS = (E[]) new Object[MAX_STACK_SIZE];        this.top = size;        this.size = 0;...

  • How can I change the following program and Implement a print() method for Percolation that prints...

    How can I change the following program and Implement a print() method for Percolation that prints 1 for blocked site, 0 for open sites and * for full sites? public class Visualizeheimadaemi { public static void main(String[] args) { int N = Integer.parseInt(args[0]); double p = Double.parseDouble(args[1]); int M = Integer.parseInt(args[2]); // repeatedly created N-by-N matrices and display them using standard draw for (int i = 0; i < M; i++) { boolean[][] open = Percolation.random(N, p); StdDraw.clear(); StdDraw.setPenColor(StdDraw.BLACK); Percolation.show(open,...

  • 2. Write MinheapPriorityQueue constructor, which takes an array of data, and construct the max heap priority...

    2. Write MinheapPriorityQueue constructor, which takes an array of data, and construct the max heap priority queue using bottom-up algorithm. The expected run time should be O(n), where n is the total number of data. BubbleDown method is provided. You may test it in this minHeap public class MinHeapPriorityQueue<E extends Comparable<? super E>>{ private E data[]; private int size; public MinHeapPriorityQueue(){ this(100); } public MinHeapPriorityQueue(int cap){ size = 0; data = (E[]) new Comparable[cap]; } public MinHeapPriorityQueue(int[] a){ } public...

  • Java: Return an array of booleans in a directed graph. Please complete the TODO section in...

    Java: Return an array of booleans in a directed graph. Please complete the TODO section in the mark(int s) function import algs13.Bag; import java.util.HashSet; // See instructions below public class MyDigraph { static class Node { private String key; private Bag<Node> adj; public Node (String key) { this.key = key; this.adj = new Bag<> (); } public String toString () { return key; } public void addEdgeTo (Node n) { adj.add (n); } public Bag<Node> adj () { return adj;...

  • JAVA TIC TAC TOE - please help me correct my code Write a program that will...

    JAVA TIC TAC TOE - please help me correct my code Write a program that will allow two players to play a game of TIC TAC TOE. When the program starts, it will display a tic tac toe board as below |    1       |   2        |   3 |    4       |   5        |   6                 |    7      |   8        |   9 The program will assign X to Player 1, and O to Player    The program will ask Player 1, to...

  • package algs24; import stdlib.StdIn; import stdlib.StdOut; /** * The <tt>PtrHeap</tt> class is the priorityQ class from...

    package algs24; import stdlib.StdIn; import stdlib.StdOut; /** * The <tt>PtrHeap</tt> class is the priorityQ class from Question 2.4.24. * It represents a priority queue of generic keys. *   * It supports the usual <em>insert</em> and <em>delete-the-maximum</em> * operations, along with methods for peeking at the maximum key, * testing if the priority queue is empty, and iterating through * the keys. * For additional documentation, see <a href="http://algs4.cs.princeton.edu/24pq">Section 2.4</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne....

  • Design and implement a class Q that uses Q.java as a code base. The queue ADT...

    Design and implement a class Q that uses Q.java as a code base. The queue ADT must use class LinkedList from Oracle's Java class library and its underlying data structure (i.e. every Q object has-a (contains) class LinkedList object. class Q is not allowed to extend class LinkedList. The methods that are to be implemented are documented in Q.java. Method comment blocks are used to document the functionality of the class Q instance methods. The output of your program must...

  • software testing without making any changes to the java classes provided below, come up with some...

    software testing without making any changes to the java classes provided below, come up with some junit test cases to test the code. To get you started, here are four test cases you must implement: • Use the setString() function in MyCustomStringInterface to set the value to “H3y, l3t'5 put s0me d161ts in this 5tr1n6!11!!”. Then test to see if the CountNumbers() function is equal to the number of sequential digits in the original string (in this case, 9). •...

  • in java Write a class named Palindrome.java and Write a method isPalindrome that takes an IntQueue...

    in java Write a class named Palindrome.java and Write a method isPalindrome that takes an IntQueue as a parameter and that returns whether or not the numbers in the queue represent a palindrome (true if they do, false otherwise). A sequence of numbers is considered a palindrome if it is the same in reverse order. For example, suppose a Queue called q stores this sequence of values: front [3, 8, 17, 9, 17, 8, 3] back Then the following call:...

  • My Question is: I have to modify this program, even a small modification is fine. Can...

    My Question is: I have to modify this program, even a small modification is fine. Can anyone give any suggestion and solution? Thanks in Advanced. import java.util.*; class arrayQueue { protected int Queue[]; protected int front, rear, size, len; public arrayQueue(int n) { size = n; len = 0; Queue = new int[size]; front = -1; rear = -1; } public boolean isEmpty() { return front == -1; } public boolean isFull() { return front == 0 && rear ==size...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT