저는 루비를 배우는 데 새로운 경험이 있습니다. 저는 Chris Pine의 Learn to Program을 배우고 있습니다. 그가 시도한 연습 중 하나는 셔플 메서드를 작성하는 것입니다 (저는 #shuffle
메서드를 알고 있습니다). 지금까지 나는이 코드를 생각해 냈다.이 코드는 작업을 수행하는 것으로 보인다 :루블에 셔플 메서드 작성하기
array_to_shuffle = []
puts "Give me a list of words to shuffle, press enter on an empty line for the result."
input = gets.chomp
while input != ""
array_to_shuffle = array_to_shuffle.push(input)
input = gets.chomp
end
def recursive_shuffle(array_to_shuffle, shuffled_array = [])
return shuffled_array unless array_to_shuffle.size > 0
array_size = array_to_shuffle.size()
random_number = rand(1..array_size)-1
element_transfered = array_to_shuffle [random_number]
shuffled_array = shuffled_array.push(element_transfered)
array_to_shuffle.delete(element_transfered)
recursive_shuffle(array_to_shuffle, shuffled_array)
end
puts recursive_shuffle(array_to_shuffle)
그러나 실제로 무엇을 고려하면 꽤 오래간만이다. 이 문제를 개선 할 수있는 방법이 있습니까?
흠이 더 적합한 것 같다 http://codereview.stackexchange.com/ – niceman
에 대한 당신이 원하는 수행 이 정확한 알고리즘을 구현하거나 어떻게 든 뒤섞고 싶다면'# shuffle'을 사용하지 말라. – ndn
@niceman faire enough! 정보 주셔서 감사합니다! – Heisenmali