How to generate random words in solidity based on a string of letters

Viewed 61

I would like to make a word generation function based on the letters of the alphabet, but I don't know how to proceed. I would like to generate 12 words

string letters public = "abcdefghijklmnopqrstuvwxyz"

But I don't understand how I could proceed in solidity to generate

For numbers, I do this

pragma solidity ^0.8.0;
contract RandomNumbers{
    function random(uint number) public view returns(uint){
        return uint(keccak256(abi.encodePacked(block.timestamp,block.difficulty,  
        msg.sender))) % number;
    }
}   

But for words, I don't know how I could proceed

1 Answers
contract MiniTest {

    string public letters = "abcdefghijklmnopqrstuvwxyz";
    // I needed to add this to the random function to generate a different random number
    uint counter =1;

    // size is length of word
    function randomString(uint size) public  payable returns(string memory){
        bytes memory randomWord=new bytes(size);
        // since we have 26 letters
        bytes memory chars = new bytes(26);
        chars="abcdefghijklmnopqrstuvwxyz";
        for (uint i=0;i<size;i++){
            uint randomNumber=random(26);
            // Index access for string is not possible
            randomWord[i]=chars[randomNumber];
        }
        return string(randomWord);
    }

    function random(uint number) public payable returns(uint){
        counter++;
        return uint(keccak256(abi.encodePacked(block.timestamp,block.difficulty,  
        msg.sender,counter))) % number;
    }
}
  • I slightly changed the random function because it was generating the same random number so the result for 5 characters was like "jjjjj".

  • string in solidity has no index property. so we have to work with bytes and then convert it to string

Here is the proof of work:

enter image description here

Related