id/email
password
forgot password | create account
about | help | code help+videos | done | prefs
CodingBat code practice

 

orion.a.smith@gmail.com apcsa-encryption > apcsaHashStringToArray
prev  |  next  |  chance

Given an input String with length n, create an output array of n+1 ints representing the components of the hash code of the String, with the last entry being the actual completed hash code. In essence, you are implementing a version of Java's built-in hashCode() method, which is part of the Object class (and thus part of every reference object), but overridden in more interesting ways in many classes such as String. Java's hashing algorithm for a String s of length n is defined as:

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
So, the element at index 0 of your output will represent the value s[0]*31^(n-1) (the numeric value of the character at index 0 of s, times 31 raised to the power n-1), the element at index 1 (assuming the String has length > 1) is s[1]*31^(n-2), until the element at index n-1 is just the numeric value of s[n-1]. At index n, your output array should store the sum of all the other indexes using integer addition.

Notes: an empty String will have one element of output with the value 0.  Also look at the outputs: some Strings with different characters will produce the same output which is known as a collision.

HINT

Integer overflow is almost a given in this algorithm, which is why you will see so many negative numbers in the output.  Math.pow is probably not your friend, given that it produces double output which is only an approximation, and when using large numbers does not convert nicely to int values.

apcsaHashStringToArray("A") → [65, 65]
apcsaHashStringToArray("BA") → [2046, 65, 2111]
apcsaHashStringToArray("Aa") → [2015, 97, 2112]

...Save, Compile, Run (ctrl-enter)

public int[] apcsaHashStringToArray(String str) { }

Editor font size %:
Shorter output


Forget It! -- delete my code for this problem

Progress graphs:
 Your progress graph for this problem
 Random user progress graph for this problem
 Random Epic Progress Graph

Java Help

Misc Code Practice

Difficulty: 230

Copyright Nick Parlante 2017 - privacy