2013-04-05 4 views
1

Ada에서 문자열을 사용하고 정수를 반환하는 해시 함수를 만들어야합니다. 내가 무슨 짓을했는지 지금까지입니다 : 나는 R은 단어 ","나는 단어의 세 번째 문자를 원한다 "라고하는 방법 에이다에서 문자를 선택하는 방법을 모른다문자열의 문자 선택

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; 

. 당신의 도움에 대한

감사합니다,

T.

답변

1

는 말했다, 당신 WI Word의 내용을 보려면 Ada.Strings.Unbounded을 사용해야합니다.

다른 두 당신이 해결해야 할 문제가 있습니다 에이다에서

  • , Unbounded_String에는 종료 문자가 없습니다 (또는 String에, 그에게 와서). 대신 루프를 for J in 1 .. (length of Word) loop으로 작성하십시오.
  • 당신이 J 번째의 문자를 추출하면, 그것은 여전히 ​​Character 그리고 당신이 h에 추가 할 수 없습니다 (I는 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