2021-06-14

Missing Row

You are given text file with rows numbered 1-15 in random order but there is a catch one row in missing in the file.

11, Line Eleven
1, Line one
9, Line Nine
13, Line Thirteen
2, Line two
6, Line Six
8, Line Eight
10, Line Ten
7, Line Seven
4, Line Four
14, Line Fourteen
3, Line three
15, Line Fifteen
5, Line Five

Write a script to find the missing row number.

這裡使用 tclcsv 讀取檔案內容,跟著再排序以後印出結果。

package require tclcsv

proc mysortproc {x y} {
    set len1 [lindex $x 0]
    set len2 [lindex $y 0]

    if {$len1 > $len2} {
        return 1
    } elseif {$len1 < $len2} {
        return -1
    } else {
        return 0
    }
}

set infile [open "input.dat" r]
set filedata [tclcsv::csv_read $infile]
close $infile
set tmpList [lsort -command mysortproc $filedata]
set len [llength $tmpList]
for {set i 0} {$i < $len} {incr i} {
     set mylist [lindex $tmpList $i]
     if {[lindex $mylist 0] != [expr $i + 1]} {
         puts "Mising row number: [expr $i + 1]"
         break
     }
}

沒有留言: