Suppose there is a array :- uint8[4][4] public array
Now I have to generated a random number in it for example :-
[[0,1,1,1],[0,2,2,1],[1,1,1,1],[3,0,0,1]]
[[1,1,1,1],[2,0,1,1],[0,2,1,1],[1,1,1,1]]
[[1,1,0,1],[0,0,4,1],[2,1,0,1],[1,2,0,1]]
But the generated random number should follow these rules:-
1) Number can be range from 0 to 4.
2) The total sum of each subarray should not be greater than 5 and less than 3
For eg :- [0,1,1,1] -> Sum =3
3) The first subarray can not have a sum of 5 or more than 5
So do anybody have idea how to achieve this in y smart contract without running out of gas?
Oct 15, 2023, 8:04 PM
Anyone?
Oct 15, 2023, 8:07 PM
Maybe look into EnumerableSet, it might hold the key to an easier way of doing whatever you trying to accomplish
You can do a fifth array with summed values, and do arithmetic everytime you update, instead of looping all values
Oct 15, 2023, 11:17 PM
things that are gonna use a lot of gas in potential implementations are looping, index checking, memory usage, conditional/branching logic
as you only have 16 items and they are in a known memory layout you can avoid all loops by just mirroring the structure of the arrays in the structure of your code, and use assembly to avoid index checks
just keep hashing some value from a seed in memory position 0 repeatedly to avoid expanding memory just to produce randomness
Oct 15, 2023, 11:37 PM
Given the max constraints, there probably aren't many permutations (maybe less than 100). You might even be able to hard-code a lookup table in the contract. Values of 0-4 would require 3 bits, so one permutation requires 4x3=12 bits. A 256 bit value can hold 21 permutations. So you'd have 0000,0001,0002,0003,0004,0010,0011,0012,0013,0014*,0020,0021,0022,0023*,0030,0031,0032*,0040,0041*,0100,0101... all that could fit in just one 32 byte value. And since there's a ceiling, it very much limits the number of permutations. You could probably even finish going through it by hand. Keep in mind you'd have to sort the sum=5 permutations out. Now, instead of generating 64 random numbers and doing a bunch of constraint checking, you simply produce 16 random indexes for the permutations you'll put into the 4x4 array.
Oct 16, 2023, 1:59 AM
Can you code it?
Oct 16, 2023, 2:03 AM
Of course, but I'd estimate a full day's work.
Oct 16, 2023, 2:04 AM