2024-09-12

 12 Sep 2024

Determine the number of times a Flip operation needs to be run

Taken from DailyCodingProblem

You are given a string consisting of the letters x and y, such as xyxxxyxyy. In addition, you have an operation called flip, which changes a single x to y or vice versa.

Determine how many times you would need to apply this operation to ensure that all x’s come before all y’s. In the preceding example, it suffices to flip the second and sixth characters, so you should return 2.

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

Testing

Solution tested in JavaScript REPL:

https://www.typescriptlang.org/play/?filetype=js#code/DYUwLgBAzmBOEF4ICIAeBPVXPvcgUKJDLAPqIoa4ZWoH4D0AVE-hExAAIAOAhrLwC2EAN4kAlgDsA5gF9ocKdLYdOscAFdYkqKMkbBAIxCxZKhvnwAzDZIDGYcQHtJEK8HHcAFBJkBKUTYIYKIIOydbSCQABiCQ8Ah+eCQAQVgBdAA6K1gnQR9FfziIYqsneC9Q1ApogG4IaoAeRPTM0BkwAAt61ABqXoCRYuDg8SsILySAbVQAXUQEJGQ8CAAyVZbYGYheiABGecWlukHhkfPwyJ2kPbPgs3OzYvUwLVdLyTB8J-CdJ1A2k5pF5Sh5vCQ-AAaCAMBgQABMoM8BTIAVhEAAzPg-PggA

Solution tested in Ruby REPL:

https://try.ruby-lang.org/playground/#code=str+%3D+%22xyxxxyxyy%22%0Astr_+%3D+%22xyyyxyxyyx%22%0A%0Adef+flip(string)%0A++count+%3D+0%0A++arr+%3D+Array.new(string.chars)%0A++%0A++arr.each_with_index+do+%7Celement%2C+index%7C%0A++++if+arr%5Bindex%5D+%3D%3D+%22y%22+%26%26+arr%5Bindex+%2B+1%5D+%3D%3D+%22x%22%0A++++++count+%2B%3D+1%0A++++end%0A++end%0A%0A++return+count%0Aend%0A%0Aputs+flip(str)+%23+2%0Aputs+flip(str_)+%23+3&engine=cruby-3.2.0

Copyright © Paramdeo Singh · All Rights Reserved · Built with Jekyll

This node last updated October 9, 2024 and is permanently morphing...

Paramdeo Singh Guyana

Generalist. Edgerunner. Riding the wave of consciousness in this treacherous mortal sea.

Technology Design Strategy Literature Personal Blogs
Search Site

Results are from Blog, Link Dumps, and #99Problems