2013-04-05 69 views
1

我需要在Ada中創建一個採用字符串並返回整數的散列函數。 我做了什麼至今:選擇字符串中的一個字母

function hash(Word: unbounded string) return Integer is 
    h := 5381 
    c := (first charater of "Word") 
begin 
    while c /= (end of "Word") loop 
     h := h*33 + c; 
     c := (next character of "Word"); 
    end while; 
return h mod 20; 
end hash; 

我不知道如何選擇的Ada,怎麼說「我想這個詞的第三個字符‘字’,這是爲r的字符

感謝您的幫助,

T.

回答

1

正如馬克說,你的Wi您需要使用Ada.Strings.Unbounded來獲取Word的內容。

有你需要解決其他兩個問題:

  • 在阿達,有在Unbounded_String沒有終止字符(或在String,走到那)。相反,將該循環寫爲for J in 1 .. (length of Word) loop
  • 一旦你提取了J'字符,它仍然是Character,你不能將它添加到h(我假設h是不可或缺的)。 Character'Pos (Ch)返回字符的數字等值,並且您可以可以加
1
function hash(Word: Ada.Strings.Unbounded.Unbounded_String) return Integer is 
-- First, because there's no manipulation of the string's 
-- contents, doing the work on an unbounded-string is 
-- rather pointless... so let's do our work on a regular --' fix for formatting 
-- [static-length] string. 
Working : String := Ada.Strings.Unbounded.To_String(Word); 
-- Second, you need types in your declarations. 
h : Integer := 5381; 
c : Character := 'e'; --(first charater of "Word"); 
begin 
-- Why use a 'while' loop here? Also, what if the 'word' is 
-- abracadabra, in that case c [the first letter] is the 
-- same as the last letter... I suspect you want an index. 

    for Index in Working'Range loop -- Was: while c /= EOW loop --' 
    declare 
    -- This is where that 'c' should actually be. 
    This : Character renames Working(Index); 
    -- Also, in Ada characters are NOT an integer. 
    Value : constant Integer := Character'Pos(This); --' 
    begin 
    h := h*33 + value; -- PS: why 33? That should be commented. 
    -- We don't need the following line at all anymore. --' 
    --c := (next character of "Word"); 
    end;   
    end loop; 
return h mod 20; 
end hash; 

當然,這也可以被重寫,以利用新的環結構的阿達2012

function hash_2012(Word: Ada.Strings.Unbounded.Unbounded_String) return Integer is 
    -- Default should be explained. 
    Default : Constant Integer := 5381; 
    Use Ada.Strings.Unbounded; 
begin 
    -- Using Ada 2005's extended return, because it's a bit cleaner. 
    Return Result : Integer:= Default do 
     For Ch of To_String(Word) loop 
      Result:= Result * 33 + Character'Pos(Ch); --' 
     end loop; 

     Result:= Result mod 20; 
    End return; 
end hash_2012; 

...我一定要問,是什麼格式化程序發生了什麼?這只是可怕的。

+0

哦,是的......你可能想要解決溢出問題。對於任何超過幾個字符的字符串,它會溢出整數,因爲每次乘以33。 2^31 /(33 + 65)= 21913098 ...這並沒有考慮到每個角色都將它的價值加入其中。 – Shark8 2013-04-05 18:31:00