1

I am programming a card game for fun to learn solidity. I have noticed that there seems to be a lack of data structures to use apart from dynamic/static arrays & mappings.

For example I have

struct Character { 
    bool engaged;
    string name;
    string charType;
    uint dna;
    uint weaponCounter;
    uint armourCounter;
    uint battleCounter;
    uint16 level;
    CharacterStatistics charStats;  
    mapping (uint => WeaponStats) weapons;  
    mapping (uint => ArmourStats) armour;              
    mapping (uint => BattleStatistics) battleStats;  
}
/// @notice An array(vector) of Characters. 
Character[] public characters;

/// @notice Dictionaries that get the owners total characters & get a character owner from the characters id.
mapping (uint => address) public characterToOwner;
mapping (address => uint) public ownerCharacterCount;

I can build a data structure that is essentially a vector of characters and some mappings.

But what would be required to introduce a binary tree in solidity, or any other type of tree structure?

1

You'd build a tree like in any other language. Just keep track of child nodes. Here's a simple tree that allows adding nodes but not deleting them:

pragma solidity ^0.4.21;

contract Tree {
    struct Node {
        bytes data;
        uint256 parent;
        uint256[] children;
    }

    Node[] nodes;

    function Tree() public {
        // root node
        nodes.push(Node("", 0, new uint256[](0)));
    }

    function appendChild(uint256 parentID, bytes data) public returns (uint256 newID) {
        newID = nodes.length;

        nodes.push(Node({
            data: data,
            parent: parentID,
            children: new uint256[](0)
        }));

        nodes[parentID].children.push(newID);

        return newID;
    }
}

(To support deletion, you might want to use a linked list for the children instead of a simple array.)

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.