0

I am trying to create hashing function the algorithm requires me to take each letter of the string and converting it to ascii, multiply it by a number based on its position in the string (for example Input is STACK; ascii for S would be 344 multiply that value by 9^9 then ascii for T would be 347 multiply that value by 8^8.. etc), and then add the values together.

I understand how to access the values in the array to create the sum and can convert to ASCII. I don't understand how i would access the array to perform the calculations in-between.

my code is below :

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string input ;
    int finalanswer = 0;

    cout << "Enter your first name please : " ;

    cin >> input;

    cout << "Your name is " << input ;


    for (int x=0; x < input.size(); x++)
    {   
        finalanswer += input[x];

        cout << finalanswer ;
    }


    cin.get();
    return 0;



}
2
Contributors
2
Replies
19
Views
4 Years
Discussion Span
Last Post by tinstaafl
0

With this code using your example("STACK") the out put is

Enter your first name please : STACK
Your name is STACK
19571



int main()
{
    string input ;
    long finalanswer = 0;
    cout << "Enter your first name please : " ;
    cin >> input;
    cout << "Your name is " << input << endl;
    for (int x=0; x < input.size(); x++)
    {
        //This sets the number to multiply by itself, starting at 9 and decreasing by 1 for character in the string.
        long Powr = (x * -1) + 9;
        finalanswer += input[x] * (Powr * Powr);
    }
    cout << finalanswer ;        
    cin.ignore();
    cin.get();
    return 0;
}

Edited by tinstaafl

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.