如何在Julia中创建结构的随机数据?

时间:2019-05-30 10:46:18

标签: struct julia

我创建了一个结构txn:

struct txn
    txn_id::Int64
    bank::String
    branch::String
    teller::String
    customer::String
    account::String
    timestamp::DateTime
    dr_cr::String
    amount::Float64
end

请指导我为该结构创建随机数据!

更新1:

参考BogumiłKamiński教授的建议,添加如下字段域:

a) txn_id is a unique integer(auto incrementing)
b) bank is a 20 character Legal Entity Identifier
c) branch is a 8 or 11 character Business Identifier Codes(SWIFT-BIC)
d) teller is a 9 digit Social Security Number
e) customer is a 9 digit Social Security Number or a 20 character Legal Entity Identifier
f) account is an 34 character International Bank Account Number(IBAN)
g) timestamp is a iso8601 date-time.
h) dr_cr is in (dr, cr)
i) amount > 0.0000

1 个答案:

答案 0 :(得分:4)

由于“随机”是一个不明确的术语,因此对这个问题的定义不够精确。因此,您要的问题没有一个单一的解决方案。

通常,如果您说“随机”,则应指定域以及该域的分布。为此,这里提供了一种解决方案,可以自动检测结构的字段类型,并使用来自预定域的统一伪随机样本填充这些字段。

using Dates

domains = Dict(Int => 1:10,
               String => string.('a':'z'),
               DateTime => DateTime("2019-01-01"):Day(1):DateTime("2019-05-30"))

struct Txn
    txn_id::Int64
    bank::String
    branch::String
    teller::String
    customer::String
    account::String
    timestamp::DateTime
    dr_cr::String
    amount::Int64
end

Txn_rand() = Txn(map(t -> rand(domains[t]), fieldtypes(Txn))...)

现在您可以编写:

julia> Txn_rand()
Txn(3, "q", "f", "j", "m", "z", 2019-03-10T00:00:00, "c", 1)

julia> Txn_rand()
Txn(8, "e", "o", "m", "l", "z", 2019-04-05T00:00:00, "p", 5)

julia> Txn_rand()
Txn(3, "k", "u", "c", "z", "y", 2019-03-13T00:00:00, "x", 1)

编辑

鉴于这里的评论是我如何处理Txn结构的生成方式(您可能更具体,例如,给出bankbranch值的封闭列表等。如您所愿-然后使用上面建议的方法):

using Dates, Random

global TXN_ID_COUNTER = 1

function Txn_rand()
    global TXN_ID_COUNTER += 1
    Txn(TXN_ID_COUNTER,
        randstring('A':'Z', 20),
        randstring('A':'Z', rand(Bool) ? 8 : 11),
        rand(Bool) ? randstring('1':'9', 9) : randstring('A':'Z', 20),
        randstring('1':'9', 9),
        randstring('A':'Z', 2) * randstring('1':'9', 32),
        rand(DateTime("2019-01-01"):Second(1):DateTime("2019-05-30")),
        rand(["dr", "cr"]),
        rand(1:100000) / 10000
       )
end

我还省略了对生成字段的验证(通常您可以这样做,因为其中一些字段具有验证规则)。