问题
I have a set of recursive if statements written in Java and I tried taking it to clojure syntax but got the ArrayOutOfBound error. The functions accepts row = 0, col = 0 and a multidimensional array of characters.
This is the Java Code:
public static boolean solveMaze(int r, int c, char[][] maze) {
//check for boundaries
if(r < 0 || c < 0 || r >= maze.length || c >= maze[0].length)
return false;
//base case, did i reach the finish?
if(maze[r][c] == '@')
return true;
//check if I'm at a valid point
if(maze[r][c] != '-')
//I have hit a wall, not a valid solution
return false;
//must be on a path, may be the right path
//leave a bread crumb
maze[r][c] = '!';
//check above
if(solveMaze(r-1,c, maze)) {
maze[r][c] = '+';
return true;
}
//check below
if(solveMaze(r+1,c, maze)) {
maze[r][c] = '+';
return true;
}
//check left
if(solveMaze(r,c-1, maze)) {
maze[r][c] = '+';
return true;
}
//check right
if(solveMaze(r,c+1, maze)) {
maze[r][c] = '+';
return true;
}
//if I reach this point...
return false;
}
This is my code in clojure that provides the Index out of bound error:
(defn solveMaze [r c m]
(def tt true)
;(def che false)
;check to verify boundaries
(if (or (or (or (< r 0) (< c 0)) (>= r (count m))) (>= c (count (str (m 0)))))
false
true
)
;Check to know if the @ symbol has been found
(if (= (get-in m[r c]) "@")
true
false
)
;Checking if current index is a valid one
(if (not= (get-in m[r c]) "-")
;Wall hit
false
true
)
;found a path, leave a breadcrumb
(def temp_map (assoc-in m[r c] "!"))
;Check North
(if (= (solveMaze (dec r) c m) true)
(def temp_map (assoc-in m [r c] "+"))
true
;false
)
;Check South
(if (= (solveMaze (inc r) c m) true)
(def temp_map (assoc-in m[r c] "+"))
true
;false
)
;Check East
(if (= (solveMaze r (dec c) m) true)
(def temp_map (assoc-in m[r c] "+"))
true
;false
)
;Check West
(if (= (solveMaze r (inc c) m) true)
(def temp_map (assoc-in m[r c] "+"))
true
;false
)
;If code gets here
(= tt false)
)
Please is there something I am doing wrongly??? I have tried several if constructs using clojure but it doesn't work.
回答1:
You need to read up on the basics of Clojure:
- Brave Clojure (online & book)
- Getting Clojure book
- Clojure CheatSheet book
回答2:
Use a cond to solve this instead of if. The way the code executes now is that first if is evaluated and then it goes to the next line to execute rest of code. With cond, if an expression is evaluated to be true, it returns the value and won't evaluate other expressions.
Refer :https://clojuredocs.org/clojure.core/cond
来源:https://stackoverflow.com/questions/56353990/rewriting-java-if-statements-in-clojure-syntax