Taken from DailyCodingProblem
You are given a string consisting of the letters
x
andy
, such asxyxxxyxyy
. In addition, you have an operation calledflip
, which changes a singlex
toy
or vice versa.Determine how many times you would need to apply this operation to ensure that all
x
’s come before ally
’s. In the preceding example, it suffices to flip the second and sixth characters, so you should return2
.
Solution
This is the answer I came up with using JavaScript:
let str = "xyxxxyxyy"
let str_ = "xyyyxyxyyx"
/**
* @param {string} string
* @returns {number}
*/
function flip(string) {
let count = 0
let arr = Array.from(string)
for (let x = 0; x < arr.length; x++) {
if (arr[x] === "y" && arr[x + 1] === "x") {
count += 1
}
}
return count
}
console.log(
flip(str), // 2
flip(str_) // 3
)
And also implemented using Ruby:
str = "xyxxxyxyy"
str_ = "xyyyxyxyyx"
def flip(string)
count = 0
arr = Array.new(string.chars)
arr.each_with_index do |element, index|
if arr[index] == "y" && arr[index + 1] == "x"
count += 1
end
end
return count
end
puts flip(str) # 2
puts flip(str_) # 3