0
\$\begingroup\$

Say I have a canonized struct:

{ health: 100, items: ["apple", "knife"], name: "Bobby" } 

"Canonized" here means any 2 structs with the same key,value pairs are equal. {a:1, b:2} is the same as {b:2, a:1}. The given canonized struct's keys are in alphabetical order.

I want to make a dictionary where I can lookup if I have set a "state" in it or not. I am using structs to represent "state". These structs have string-keys, and string/number/array-values.

Currently, I am simply converting the canonized struct into a string via string(struct) and then hashing that via variable_get_hash(str). Then I am storing that hash into another struct called "hashmap" like so: struct_set_from_hash(hashmap, hash, struct). Here it is all together:

function put_into_hashmap (hashmap={}, struct_key={}, any_value) { var str = string(struct_key); // convert struct into string var hash = variable_get_hash(str); // get hash from string struct_set_from_hash(hashmap, hash, any_value); // map value with hash } 

But when I print out the value of hash, it is a relatively small number. And since my canonized struct string can be much longer than this hash number, I am afraid of 2 different structs being set at the same hash, which will break my program.

So how can I hash this struct efficiently and reliably so that it is not possible to set 2 different structs into the same hash? Also, is this the most efficient way to hash a struct in GML? Should I be looking at a different algorithm?

\$\endgroup\$
4
  • 2
    \$\begingroup\$ What does "canonized" mean in this context?, you say it has alphabetical order, I'm guessing that is about the elements of the array, is that correct? Is the array what you want to use as key? Is there a fixed set of possible elements the key can have? - I can't find enough information about the hash solution in game maker, but there would be some risk of collisions regardless of which solution you use (it might be that game maker handles this internally). The only hash based way to guarantee no collision would be perfect hashing which in practice is rarely viable. Is it a hard requirement? \$\endgroup\$ Commented Feb 4, 2024 at 17:36
  • \$\begingroup\$ @Theraot canonized here means that any 2 structs with the same data are equal... let me clarify in the question... \$\endgroup\$ Commented Feb 5, 2024 at 1:51
  • 1
    \$\begingroup\$ This question seems to fit a programing site such as "StackOverFlow" better than this "Game Development" site because this question is more about programming technique than game development technique. \$\endgroup\$ Commented Feb 5, 2024 at 10:11
  • \$\begingroup\$ Canonical form: en.m.wikipedia.org/wiki/…. \$\endgroup\$ Commented Feb 8, 2024 at 7:26

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.