Reputation: 9
I wanted to create an anagram solver. Here's my code:
def permut(word)
for i in 1..$laenge
if i != $laenge
word[$laenge-i], word[$laenge-i-1] = word[$laenge-i-1], word[$laenge-i]
$output.push word
$y += 1
end
end
end
I shouldn't be using global variables, and the for
-loop in get_input
will get stuck, but it's just for learning purposes, my focus is just on the array problem and I'm debugging it with rdebug.
When I push the value of the mixed word to an array, it overwrites all values of it. I tried it by giving an index like Array[y]
and incrementing y
every time I go through the for
-loop, or just by using Array.push
, followed by the word as a string.
Upvotes: 0
Views: 525
Reputation: 80065
You are mutating the very same string over and over.
ar = []
word = "abc"
ar.push(word)
word[0], word[1] = word[1], word[0]
p ar # => ["bac"]
Try saving duplicates of the mutated string in the array:
ar.push(word.dup)
Upvotes: 1