Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* An attempt to make Percolation.java more functional but possibly not the best example as Array is preferred here over other immutable collections
- Scala code remains very imperative...some conciseness gained but that's it */
- import edu.princeton.cs.algs4.WeightedQuickUnionUF
- /* primary constructor shorthand, n parameter without val or var
- are private values so not accessible from the
- outside and immutable*/
- class PercoScala(n: Int) {
- // default member visibility is public
- val grid_size: Int = n * n
- val wquf: WeightedQuickUnionUF = new WeightedQuickUnionUF(grid_size + 2)
- val top = 0
- val bottom: Int = grid_size + 1
- // Arrays as size is fixed and fast random access important
- val isSiteOpen: Array[Boolean] = new Array[Boolean](grid_size + 2)
- // top is always open
- isSiteOpen(top) = true
- isSiteOpen(bottom) = true
- // var are just simple enough for a global counter
- var openSites: Int = 0
- def validate(i: Int, j: Int) =
- if (i <= 0 || i > n || j <= 0 || j > n) throw new IllegalArgumentException(
- "indices (" + i + "," + j + ") are not between 1 and " + n)
- def xyTo1D(i: Int, j: Int) = j + n * (i - 1)
- def open(i: Int, j: Int) = {
- validate(i, j)
- val site = xyTo1D(i, j)
- if (!isSiteOpen(site)) {
- isSiteOpen(site) = true
- openSites += 1
- connectAdjacentSites(i, j)
- }
- }
- def connectAdjacentSites(i: Int, j: Int): Unit = {
- val site = xyTo1D(i, j)
- // connect to top sites on the first row
- if (i == 1) wquf.union(site, top)
- // above site exits only if i>1
- if (i > 1) {
- val adjacent = xyTo1D(i - 1, j)
- if (isSiteOpen(adjacent)) wquf.union(site, adjacent)
- }
- // left site
- if (j > 1 && j <= n) {
- val adjacent = xyTo1D(i, j - 1)
- if (isSiteOpen(adjacent)) wquf.union(site, adjacent)
- }
- // right site
- if (j >= 1 && j < n) {
- val adjacent = xyTo1D(i, j + 1)
- if (isSiteOpen(adjacent)) wquf.union(site, adjacent)
- }
- // below site exists only if i<n
- if (i != n) {
- val adjacent = xyTo1D(i + 1, j)
- if (isSiteOpen(adjacent)) wquf.union(site, adjacent)
- }
- // all bottom sites are connected to bottom !
- if (i == n) wquf.union(site, bottom);
- }
- def isOpen(i: Int, j: Int) = isSiteOpen(xyTo1D(i, j))
- def isFull(i: Int, j: Int) = wquf.connected(xyTo1D(i, j), 0)
- def numberOfOpenSites = openSites
- def percolates = wquf.connected(top, bottom)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement