简体   繁体   中英

How can I find the cells adjacent to a cell in a matrix in OCaml?

For example, I am given a list [3;5;6;2;10;4;9;1;3] that maps out to a matrix like this:

3 5 6
2 10 4
9 1 3

I have already coded a function "find_size" that will find the size of the matrix given a list (for this example, it would give me the int 3)

as well a function "find_position" that will tell me where in the matrix 10 is (so here, it would give me the tuple (1, 1) because it is in the second row and second column)

I think the best way to approach this would be to iterate over the list using a fold function that applies a given function to each element and keeps track of the results. Therefore, my goal is to create a function that will tell me if a certain element in the matrix is adjacent to 10 in OCaml (if it is, I would tell the fold function add that element to the answer list).

The final answer for this would be [5;2;4;1] because those elements are adjacent to 10.

You can fairly easily translate your size and position values into a list of the adjacent positions as tuples. You can translate the size and a tuple into a single list index. With a sorted list of indices, you can fold over the list and extract the elements at the given indices.

This would probably be a lot easier if you used an array of numbers, for what it's worth.

Without seeing some code you've tried, and hearing how it did or didn't work for you, it's difficult to say more than this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM