# Код на ruby 2.2.3p173
def zadanie(line, time)
line = line.gsub(/[^MD]/, "")
time.times { |i|
k = 0
while k < line.size - 1 do
if line[k..k + 1] == "MD"
line[k], line[k + 1] = line[k + 1], line[k]
k+=1
end
k+=1
end
p [i+1,line]
}
return line
end
# # Примеры применения
p zadanie("MDDDMMDMDDDMMMMMMDDM", 10)
# p zadanie("MMDMDDDDDMMDDDMDDDMD", 10)
# p zadanie("MMDDDDMDMM", 5)
Вывод
[1, "DMDDMDMDMDDMMMMMDMDM"]
[2, "DDMDDMDMDMDMMMMDMDMM"]
[3, "DDDMDDMDMDMMMMDMDMMM"]
[4, "DDDDMDDMDMMMMDMDMMMM"]
[5, "DDDDDMDDMMMMDMDMMMMM"]
[6, "DDDDDDMDMMMDMDMMMMMM"]
[7, "DDDDDDDMMMDMDMMMMMMM"]
[8, "DDDDDDDMMDMDMMMMMMMM"]
[9, "DDDDDDDMDMDMMMMMMMMM"]
[10, "DDDDDDDDMDMMMMMMMMMM"]
"DDDDDDDDMDMMMMMMMMMM"