# Creating arrays with dynamic sizes at runtime

I am translating this Crystal code to Go

``````def gen_pg_parameters(prime)
# Create prime generator parameters for given Pn
puts "using Prime Generator parameters for P#{prime}"
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23]
modpg, res_0 = 1, 0
primes.each { |prm| res_0 = prm; break if prm > prime; modpg *= prm }

restwins = [] of Int32
inverses = Array.new(modpg + 2, 0)
pc, inc, res = 5, 2, 0
while pc < modpg // 2
if gcd(pc, modpg) == 1
pc_mc = modpg - pc
inv_r = modinv(pc, modpg)
inverses[pc] = inv_r
inverses[inv_r] = pc
inv_r = modinv(pc_mc, modpg)
inverses[pc_mc] = inv_r
inverses[inv_r] = pc_mc
if res + 2 == pc; restwins << pc; restwins << (pc_mc + 2) end
res = pc
end
pc += inc; inc ^= 0b110
end
restwins.sort!;          restwins << (modpg + 1)
inverses[modpg + 1] = 1; inverses[modpg - 1] = modpg - 1
{modpg, res_0, restwins.size, restwins, inverses}
end
``````

Here’s the go translation.

``````func gen_pg_parameters(prime int) (int, int, int, []int, []int) {
// Create prime generator parameters for given Pn
fmt.Println("using Prime Generator parameters for P",prime)
primes := []int{2, 3, 5, 7, 11, 13, 17, 19, 23}
modpg, res_0 := 1, 0
for _, prm := range primes { res_0 = prm; if prm > prime { break }; modpg *= prm }

restwins := []int{}
inverses := [modpg + 2]int{}
pc, inc, res := 5, 2, 0
for pc < modpg / 2 {
if gcd(pc, modpg) == 1 {
var pc_mc = modpg - pc
var inv_r = modinv(pc, modpg)
inverses[pc] = inv_r
inverses[inv_r] = pc
inv_r = modinv(pc_mc, modpg)
inverses[pc_mc] = inv_r
inverses[inv_r] = pc_mc
if res + 2 == pc { restwins = append(restwins, pc, pc_mc + 2) }
res = pc
}
pc += inc; inc ^= 0b110
}
sort.Ints(restwins); restwins = append(restwins, modpg + 1)
inverses[modpg + 1] = 1; inverses[modpg - 1] = modpg - 1
pairscnt := len(restwins)
return modpg, res_0, pairscnt, restwins, inverses
}
``````

Go won’t create the `inverses` array at runtime with `[modpg + 2 ]int` for its size.
So how do you do that in go, or do you have to use a hash|associative array?

You can not create dynamically sized arrays. You can use unsized slices instead.

You can pre-allocate them using `make([]int, size, capacity)`.

Thank you, that worked like a charm.

I ended up doing: ` inverses := make([]int, modpg + 2)`

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.