2015-07-02 32 views
-1
def num_repeats(string) 
    letters = string.chars 
    idx = 0 
    n = 1 
    arr = [] 
    lettercount = 0 
    while idx < letters.length 
     lettercount = 0 
     while n < letters.length 
      if letters[idx] == letters[n] 
       lettercount = 1 
      end 
      n+=1 
     end 
     if lettercount > 0 
      arr.push(idx) 
     end 
     idx += 1 
    end 
    return arr.length 
end 

puts(num_repeats("abdbccc")) 
# == 2 since 2 letters are repeated across the string of characters 

我一直收到0,雖然我看到它,如果重複一個數字,numbercount的值應該從零移到一個,然後允許一些值被推入數組,然後我得到所述數組的長度確定重複字符的數量。我的循環有問題嗎?如何獲得某個字符串中重複的所有字符的數值?

+0

我不明白你想要做什麼。也許發佈一些預期的輸入/輸出? – Adrian

+0

我希望這個評論澄清一點 – Chris

回答

0

沒明白你要做的,也許你可以使用哈希來幫助:

def num_repeats(string) 
    letters = string.chars 
    counter_hash = Hash.new(0) 
    letters.each { |l| counter_hash[l] += 1 } 
    counter_hash 
end 
2

UPDATE

如果你真的想用同一種代碼算法做到這一點,那麼這裏是它的問題:

在你的第二個while循環中,變量n應該從idx+1開始,consid因此,您正在嘗試提取索引,然後查找該索引處的字符是否在索引之後的某處重複。

但即使您修復,您將得到3abdbccc。這有點表明你的算法是錯誤的。當重複字符出現超過2次時,就像我在上面的段落中所說的過程一樣,除了最後一個字符以外,您都會這樣做,而不檢查字符是否已被檢測到重複。插圖:

str = 'aaa' 
When idx = 0, you get str[idx] == str[n=1], adds it to the result. 
When idx = 1, you get str[idx] == str[n=2], adds it to the result. 

現在你計算了a兩次重複。我想你可以單獨解決這個問題。


我認爲你只是試圖做同樣的,因爲這(假設你需要檢查只有小寫字母):

str = "abdbccc" 
('a'..'z').count { |x| str.count(x) > 1 } 
# => 2 

或者,如果你需要檢查重複的字符數任何字符:

str = "12233aabc" 
str.chars.group_by(&:to_s).count do |k, v| 
    v.size > 1 
end 
# => 3 

這是我們正在談論的Ruby。在Ruby中編寫這樣的代碼並不是一個好主意,我的意思是你使用了很多while循環並手動追蹤它們的計數器,而在Ruby中,通常不必處理這些,考慮到所有方便,少Ruby提供的更容易出錯和更短的替代方案。我認爲你有一個類似C的背景,我建議你更多地學習Ruby和Ruby的做事方式。

0

你有這樣的內環

while n < letters.length 
     if letters[idx] == letters[n] 
      lettercount = 1 
     end 
     n+=1 

但無處你重新n,所以這個循環已掃描一次後,它會跳過以後每一次

可以主要解決的是通過設置n到這裏idx + 1

while idx < letters.length 
    lettercount = 0 
    n = idx + 1 
    while n < letters.length 

你仍然會得到結果,因爲你沒有檢測到c已經算

你可以用一對夫婦解決這個最後的問題更多的調整

def num_repeats(string) 
    letters = string.chars 
    idx = 0 
    arr = [] 
    lettercount = 0 
    while idx < letters.length 
     lettercount = 0 
     n = idx + 1     # <== start looking after idx char 
     while n < letters.length 
      if letters[idx] == letters[n] 
       lettercount += 1 # <== incrementing here 
      end 
      n+=1 
     end 
     if lettercount == 1   # <== check for exactly one 
      arr.push(idx) 
     end 
     idx += 1 
    end 
    return arr.length 
end 

這工作,因爲現在lettercount == 2第一個c如此重複不計,直到你得到第二個c其中lettercount == 1

這仍然被認爲是一個糟糕的解決方案,因爲它具有O(n ** 2)的複雜性。有解決方案 - 例如使用Hash哪些是O(n)

相關問題