Skip to content

Commit beed923

Browse files
authored
Add Linear Search in Tcl (#5064)
1 parent 967ff63 commit beed923

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

archive/t/tcl/linear-search.tcl

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
proc usage {} {
2+
puts stderr {Usage: please provide a list of integers ("1, 4, 5, 11, 12") and the integer to find ("11")}
3+
exit 1
4+
}
5+
6+
proc parseList {s} {
7+
set tokens [split [string trim $s] ","]
8+
if {[llength $tokens] < 1} { usage }
9+
10+
set result {}
11+
12+
set result {}
13+
foreach token $tokens {
14+
set t [string trim $token]
15+
if {$t eq "" || [catch {expr {int($t)}} val]} usage
16+
lappend result $val
17+
}
18+
return $result
19+
}
20+
21+
22+
proc parseInt {s} {
23+
set s [string trim $s]
24+
if {$s eq "" || [catch {expr {int($s)}} val]} {
25+
usage
26+
}
27+
return $val
28+
}
29+
30+
proc linearSearch {nums value} {
31+
expr {[lsearch -integer -exact $nums $value] != -1}
32+
}
33+
34+
if {$argc != 2} { usage }
35+
36+
set numbers [parseList [lindex $argv 0]]
37+
set key [parseInt [lindex $argv 1]]
38+
39+
set found [linearSearch $numbers $key]
40+
puts [expr {$found ? "true" : "false"}]
41+

0 commit comments

Comments
 (0)