【问题标题】:Converting a list of integers to a map of vertices containing the elements coordinates将整数列表转换为包含元素坐标的顶点映射
【发布时间】:2021-10-08 16:38:03
【问题描述】:

这是我目前拥有的

(string -> int list)
let read filename = ....  

这是按预期工作的,从文本文件中返回一个整数列表,如下所示:

530070000
600195000
098000060
800600003
400803001
700020006
060000280
000419005
000080079

是的,你是对的,它是一个数独板。这是我必须处理的:


     type vertex = int * int (*Cells in the sudoku board*)
     type gamma = int (*representing colors 1-9*)
    
    (* [Vertex = Map.Make(Vertex)] *)
    
             module Vertex = Map.Make(struct 
                 type t = vertex
                 let compare = Stdlib.compare
                 end) 

     (* [Gamma = Set.Make(Gamma)] *)
             module Gamma = Set.Make(struct
                 type t = gamma
                 let compare = Stdlib.compare
                 end)
    

伽玛集用于使用图形着色解决数独板。我需要帮助了解如何将整数列表转换为适合此类任务的映射。根据我提供的结构,我可以使用坐标(x,y)访问地图中的每个元素。希望您能理解,否则我将尝试提供更多信息。我真的不擅长 OCaml,但正在努力学习。我很抱歉身体错误等,第一次在这里发帖。

【问题讨论】:

    标签: functional-programming ocaml sudoku


    【解决方案1】:

    据我了解您的任务,文本文件包含一个数字网格,其中包含数独的初始配置。因此,您不应将文件中的一行解释为单个整数,而应将其解释为整数列表。您可以更改read 函数,使其返回int list list 而不是int list,然后在列表上使用List.fold_left,这也将计算列表中元素的位置,但这很乏味。直接从文件中读取网格要容易得多,例如,

    let read_matrix chan =
      let rec loop i j grid =
        match input_char chan with
        | exception End_of_file -> grid
        | '\n' -> loop (i+1) 0 grid
        | '0'..'9' as c ->
          loop i (j+1) @@
          Vertex.add (i,j) (ascii_digit c) grid
        | _ -> invalid_arg "invalid input" in
      loop 0 0 Vertex.empty
    

    ascii_digit 定义为,

    let ascii_digit c = Char.code c - Char.code '0'
    

    read_matrix 函数将通道作为输入,以便从您可以定义的文件中读取网格,

    let matrix_from_file file =
      let chan = open_in file in
      let r = read_matrix chan in
      close_in chan;
      r
    

    提示:您可能也不希望在网格中包含带有0 的职位。这很容易实现,只需在 loop 函数中的模式中添加另一个 case 即可跳过它,例如,

    ...
    | '0' -> loop i (j+1) grid
    ...
    

    【讨论】:

    • 这可能是一个奇怪的问题,但我怎样才能递归迭代地图并用值 1-9 替换“零”?在不违反数独规则的情况下?有什么想法/提示吗? ?
    猜你喜欢
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    • 2023-02-25
    相关资源
    最近更新 更多