3
\$\begingroup\$

I want to hash an array of strings into one hash as shown on scheme on the image below. But I do not want to implement some class based Merkle tree. It's just a simple function. Is this a good implementation or are there any possible improvements?

enter image description here

public static String hashStrings(@NotNull String [] strs)
{
    if (strs.length == 1) return hashString(strs[0]);

    List<String> hashes = new ArrayList<>();

    for (int i = 0; i < strs.length; i++)
    {
        hashes.add(hashString(strs[i]));
    }

    while(hashes.size() > 1)
    {
        int currentSize = hashes.size();
        int nextSize = currentSize % 2 == 0 ? currentSize / 2 : (currentSize + 1) / 2;

        for (int i = 0; i < currentSize - 1; i += 2)
        {
            hashes.set(i / 2, hashString(hashes.get(i) + hashes.get(i + 1)));
        }

        if (currentSize % 2 == 1)
        {
            hashes.set(nextSize - 1, hashString(hashes.get(currentSize - 1)));
        }

        hashes = hashes.subList(0, nextSize);
    }

    return hashes.get(0);
}
\$\endgroup\$
1
\$\begingroup\$

In my opinion this statement is quite complicated to read, compared to what you want achieve:

int nextSize = currentSize % 2 == 0 ? currentSize / 2 : (currentSize + 1) / 2;

You could consider using some brackets:

int nextSize = (currentSize % 2 == 0) ? (currentSize / 2) : ((currentSize + 1) / 2);

Or just use Math.ceil():

int nextSize = (int) Math.ceil(currentSize / 2.0))

Furthermore you are computing hashes.size() twice per loop:

while(hashes.size() > 1)
{
    int currentSize = hashes.size();
    // ...

you could write:

int currentSize = hashes.size();
while(currentSize > 1)
{
    currentSize = hashes.size();
    // ....

instead.

Other than that your code looks fine to me, besides strs is not the best name for a parameter. You could rename it to improve readability and usability.

\$\endgroup\$

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.