5.2 vector: Creates and uses various variants of vector, 5.2 vector
Clojure exercise-5. combined data types
"Using 100 functions to operate a data structure is much better than using 10 functions to operate 10 data structures. Based on a unified data structure, we can build a series of small functions that can be combined to form a powerful system. Writing different functions for different data structures fundamentally reduces the possibility of reuse ." -- [Alan Perlis]
- Clojure exercise-5 combined data types
- Combined data type
- 2. Create and use various variants of vector
- Known
- Solution 1
- Test
- Solution 2
- Test
5. combined data type 5.2 vector: create and use various variants of vector
Implement a function: a two-dimensional matrix is known,
Input: Point Location
Return: All adjacent locations of a point (excluding the diagonal line ).
Known
(Def matrix "two-dimensional square matrix" [[1 2 3] [4 5 6] [7 8 9]) (doc matrix ); value (get-in matrix [1 2]); => 6; Value-traversal value (map # (get-in matrix %) '([1 2]); => (6) (map # (get-in matrix %) '([1 0] [0 1]); => (4 2); x, y are respectively added (map + [0 0] [-1 0]); => (-1 0); x, y respectively add-Traverse (def △[ [-1 0] [1 0] [0-1] [0 1]) (map # (map + [0 0] %) △); => (-1 0) (1 0) (0-1) (0 1 )); use filter (doc filter) (filter # (<% 3) (range 10); => (0 1 2)
Solution 1
; Version 1 (defn neighbors "searches for a vertex's adjacent position in a two-dimensional square matrix input: size indicates the side length xy of the two squares indicates that a vertex Delta represents the distance returned from xy: for example (1 0) (0 1 )) "([size xy] (neighbors [[-1 0] [1 0] [0-1] [0 1] size xy )) ([△size xy] (filter (fn [an-xy] (every? # (<-1% size) an-xy); filter parameter 1' (-1 0) (1 0) (0-1) (0 1 )); (2 )))
Test
; Test (neighbors 3 [0 0]); => (1 0) (0 1 ))
Solution 2
; Version 2 (defn neighbors "searches for a vertex's adjacent position in a two-dimensional square matrix. Input: size indicates the edge length of the two squares. xy indicates a vertex. △indicates the return distance from xy: for example (1 0) (0 1 )) "([size xy] (neighbors [[-1 0] [1 0] [0-1] [0 1] size xy )) ([△size xy] (filter (fn [an-xy] (every? # (<-1% size) an-xy); filter real parameter 1 (map # (map + [0 0] %) △); filter real parameter 2 )))
Test
; Test (neighbors 3 [0 0]); => (1 0) (0 1) (map # (get-in matrix %) (neighbors 3 [0 0]); => (4 2)