Jump to content

VEX custom data types: hash table


kiryha

Recommended Posts

I am discovering a Data Structures topic and implement a Hash Table in VEX as an exercise.
Despite it is totally useless in real production it still could be worthwhile as an example for similar tasks.

Create a library.h file and save it to any location, e.g. C:/library.h
The content of the library.h file:

// The library.h content
// VEX Hash Table implementation for {string:float} pairs
struct hash_table{
    int array_len;  // Limit array length
    float data[];  // Init data

    int build_index(string key){
        // Build and return index for array from string
        int index = random_shash(key) % this.array_len*10;

        return index;
    }

    void add_item(string key; float value){
        // Place item value in array at index position
        int index = this -> build_index(key);
        this.data[index] = value;
    }

    float get_item(string key){
        // Get item from array by position
        int index = this -> build_index(key);
        float value = this.data[index];

        return value;
    }
}

Now in Attribute Wrangle (Detail mode) you can build a shopping list:

#include "C/library.h"

// Initialize hash table
float data[];
int table_size = 10;
hash_table fruits_number = hash_table(table_size, data);

// Add elements to hash table
fruits_number->add_item('apple', 256);
fruits_number->add_item('banana', 1024);
fruits_number->add_item('strawberry', 512);

// Get element from hash table
float number_of_apples = fruits_number->get_item('apple');
printf('Amount = %s \n', number_of_apples); 

// Result: Amount = 256 

More on creating and importing custom modules with VEX

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...