2017-01-02 73 views
0

我正在對應用程序學院的練習題進行一個問題。Ruby插入方法將元素插入錯誤的索引

編寫一個方法,它接受字符串和 字符串中的索引數組。產生一個新的字符串,其中包含來自輸​​入 字符串的字母,由索引數組的索引指定。

我試圖使用Ruby的插入方法來解決這個問題:

def scramble_string(string, positions) 

    arr = [] 
    indx = 0 
    positions.each do |x| 
    arr.insert(x,string[indx]) 
    indx += 1 
    end 
    return arr.join("") 
end 
puts scramble_string("abcd", [3, 1, 2, 0]) # for testing 
puts scramble_string("markov", [5, 3, 1, 4, 2, 0]) # for testing 

# These are tests to check that your code is working. After writing 
# your solution, they should all print true. 

puts("\nTests for #scramble_string") 
puts("===============================================") 
    puts(
     'scramble_string("abcd", [3, 1, 2, 0]) == "dbca": ' + 
     (scramble_string("abcd", [3, 1, 2, 0]) == "dbca").to_s 
    ) 
    puts(
     'scramble_string("markov", [5, 3, 1, 4, 2, 0]) == "vkaorm"): ' + 
     (scramble_string("markov", [5, 3, 1, 4, 2, 0]) == "vkaorm").to_s 
    ) 
puts("===============================================") 

對於第一次檢查「ABCD」,它輸出的正確答案「DBCA」,但是,當第二測試跑,我得到一個錯誤的答案「vrokam」。正確答案應該是「vkaorm」。我無法弄清楚爲什麼我的代碼不適用於第二次檢查。任何幫助表示讚賞。

編輯:

我在我的代碼中發現了錯誤。代替

arr.insert(x,string[indx]) 

正確的代碼應該是

arr.insert(indx,string[x]) 

回答

1

方法刀片陣列的變化大小。

您可以瞭解使用此代碼發生了什麼:

def debug_array(arrr) 
    puts "---------------- #{arrr.size}, #{arrr.join('.')}" 
end 

def scramble_string(string, positions) 

    arr = Array.new(string.size) 
    indx = 0 
    positions.each do |x| 
    puts "#{indx} >> #{string[indx]}" 
    arr.insert(x,string[indx]) 
    indx += 1 
    debug_array arr 
    end 
    return arr.join("") 
end 
puts scramble_string("abcd", [3, 1, 2, 0]) # for testing 
puts scramble_string("markov", [5, 3, 1, 4, 2, 0]) # for testing 
+0

我明白了。謝謝。有沒有一種方法可以像插入一樣工作而不改變數組的大小? – JimmyW

+0

juste do'arr [x] = string [indx]' – djothefou