Don't say so much, just coding...
In this simple Kata your task is to create a function that turns a string into a Mexican Wave. You will be passed a string and you must return that string in an array where an uppercase letter is a person standing up.
Rules:
Examples:
wave("hello") => ["Hello", "hEllo", "heLlo", "helLo", "hellO"]
def wave(str)
# ...
end
result = ["Hello", "hEllo", "heLlo", "helLo", "hellO"];
Test.assertDeepEquals(wave("hello"),result, "Should return: '"+result+"'");
result = ["Codewars", "cOdewars", "coDewars", "codEwars", "codeWars", "codewArs", "codewaRs", "codewarS"];
Test.assertDeepEquals(wave("codewars"), result, "Should return: '"+result+"'");
result = [];
Test.assertDeepEquals(wave(""), result, "Should return: '"+result+"'");
result = ["Two words", "tWo words", "twO words", "two Words", "two wOrds", "two woRds", "two worDs", "two wordS"];
Test.assertDeepEquals(wave("two words"), result, "Should return: '"+result+"'");
result = [" Gap ", " gAp ", " gaP "];
Test.assertDeepEquals(wave(" gap "), result, "Should return: '"+result+"'");
function wave(str){
// Code here
}
result = ["Hello", "hEllo", "heLlo", "helLo", "hellO"];
Test.assertDeepEquals(wave("hello"),result, "Should return: '"+result+"'");
result = ["Codewars", "cOdewars", "coDewars", "codEwars", "codeWars", "codewArs", "codewaRs", "codewarS"];
Test.assertDeepEquals(wave("codewars"), result, "Should return: '"+result+"'");
result = [];
Test.assertDeepEquals(wave(""), result, "Should return: '"+result+"'");
result = ["Two words", "tWo words", "twO words", "two Words", "two wOrds", "two woRds", "two worDs", "two wordS"];
Test.assertDeepEquals(wave("two words"), result, "Should return: '"+result+"'");
result = [" Gap ", " gAp ", " gaP "];
Test.assertDeepEquals(wave(" gap "), result, "Should return: '"+result+"'");
想法(1): 將所有字都先轉為小寫,在透過跑迴圈來看第幾個字為大寫 + 其餘小寫
想法(2): 複製原本傳入的值出來後,再將大寫的字 assign 回複製出來的值
圖片來源:Unsplash C D-X
# Solution 1
def wave(str)
result = []
chars = str.downcase.chars
chars.each_with_index do |char, index|
next if char == " "
result << str[0...index] + char.upcase + str[index+1..-1]
end
result
end
# Solution 2
def wave(str)
result = []
str.size.times do |index|
next if str[index] == ' '
result << str.dup
result[-1][index] = result[-1][index].upcase
end
result
end
// Solution 1
function wave(str){
var result = [];
for (i = 0; i < str.length; i++) {
if (str[i] != ' ')
result.push(str.slice(0, i) + str[i].toUpperCase() + str.slice(i + 1))
}
return result;
}