簡體   English   中英

Minizinc,如何創建地圖或字典數據結構

[英]Minizinc, how to create a map or a dictionary datastructure

關於Minizinc的語法,我有一個簡單的問題。 我的輸入.dzn文件包含一組2維數組(大約最多30個數組),聲明如下:

rates_index_0 = array2d(1..3, 1..501, [ 15, 20, 23, ....
rates_index_12 = array2d(1..3, 1..501, [ 21, 24, 27, ....
...

注意:索引號中有間隙(例如,12 - > 20)

在我的模型中,我需要根據變量的值使用其中一個數組。 在通用編程語言中,我將使用地圖或字典數據結構來解決它。 但是在Minizinc中,我用以下方式對此進行了硬編碼:

function var int: get_rate(int: index, var int: load, int: dc_size) =

        if index == 0 then
          rates_index_0[dc_size, load]
        else if index == 12 then
          rates_index_12[dc_size, load]
        else if index == 16 then
          rates_index_16[dc_size, load]
        else if index == 20 then
          rates_index_20[dc_size, load]
        else
          assert(false, "unknown index", 0)
        endif endif endif endif;

這段代碼的一個明顯問題是我每次更改輸入時都需要更改模型。 有一種更好的方法可以用通用的方式對它進行編碼嗎?

謝謝!

以更抽象的方式,地圖結構只不過是將某種類型的輸入映射到數組的函數。 因此,映射可以由數組和函數替換。 (不同之處在於您必須自己定義功能)

在我開始其余的工作之前,我想指出,如果你的模型編譯速度通常很快,你可能想嘗試一個沒有函數的三元數組, rates_index = array3d(0..60, 1..3, 1..501, [ 15, 20, 23, ....這將花費更多的內存,但會使模型更加靈活。

使用map-structure的一般方法是定義一個函數map_index ,它將輸入(在本例中為整數)映射到數組的索引,也是整數。 這意味着我們可以定義一個額外的級別數組以指向正確的數組: rates_index = array3d(0..nr_arrays, 1..3, 1..501, ....這意味着get_rates的內容可以然后是: rates_index[map_index(index), dc_size, load]

最簡單形式的函數map_index本身將包含if-then-else語句的另一個版本:

function int: map_index(int: index) =  
    if index == 0 then
        0
    else if index == 12 then
        1
    else if index == 16 then
        2
    else if index == 20 then
        3
    else
        assert(false, "unknown index", 0)
    endif endif endif endif;

但是,您可以通過生成包含每個索引的數組編號的額外數組來使其動態化,為所有不可用的數組添加-1。 對於您的示例,映射將如下所示: array[0..20] of int: mapping = [0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, 2, -1, -1, -1, 3]; 然后可以動態地將map_index函數定義為:

function int: map_index(int: index) =  
    mapping[index];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM