2021-01-26

Binary Substrings

You are given a binary string $B and an integer $S. Write a script to split the binary string $B of size $S and then find the minimum number of flips required to make it all the same.

使用 string range 分組,再比對字串。使用好幾個 for 迴圈,所以效率會不太好。

#!/usr/bin/env tclsh
#
# You are given a binary string $B and an integer $S.
# Write a script to split the binary string $B of size $S and
# then find the minimum number of flips required to make it all
# the same.
#
# Input: $B = “101100101”, $S = 3
# Output: 1
#

if {$argc >= 2} {
    set orgstring [lindex $argv 0]
    set number [lindex $argv 1]

    if {![string is integer $number]} {
        puts "S should be a number."
        exit
    }
    
    if {$number <= 0} {
        puts "S should be > 0."
        exit
    }
} else {
    exit
}

set len [string length $orgstring]
if {[expr $len % $number] != 0} {
    puts "Invalid input."
    exit
}

set stringlist {}
set max [expr $len / $number]
for {set i 0} {$i < $max} {incr i} {
   set mystring [string range $orgstring [expr $number * $i] [expr $number * $i + ($number - 1)]]
   lappend stringlist $mystring
}

set results {}
for {set i 0} {$i < $max} {incr i} {
    set count 0
    for {set j 0} {$j < $max} {incr j} {
        if {$i != $j} {
            set first [lindex $stringlist $i]
            set second [lindex $stringlist $j]
            for {set k 0} {$k < $number} {incr k} {
                if {[string index $first $k] != [string index $second $k]} {
                    incr count
                }
            }
        }
    }

    lappend results $count
}

puts "Input: \$B = \“$orgstring\”, \$S = $number"
puts "Output: [::tcl::mathfunc::min {*}$results]"

沒有留言: