2021-01-07

Group Anagrams

You are given an array of strings. Write a script to group Anagrams together in any random order.

下面是我試著解的結果:

#!/usr/bin/tclsh
#
# You are given an array of strings @S. Write a script to 
# group Anagrams together in any random order.
#
if {$argc == 0} {
    puts "Please input a string"
    exit
}

set len [llength $argv]
set inlist $argv
set result [dict create]
for {set index 0} {$index < $len} {incr index} {
    set tmpstring [lindex $inlist $index]
    set tmplist [lsort [split $tmpstring ""]]
    set key [join $tmplist ""]
    if {[dict exists $result $key]} {
        set value [dict get $result $key]
        lappend value $tmpstring
        dict set result $key $value
    } else {
        set value [list]
        lappend value $tmpstring
        dict set result $key $value
    }
}

puts "Output:"
foreach {key value} $result {
    puts $value
}

也可以使用 array:

#!/usr/bin/tclsh
#
# You are given an array of strings @S. Write a script to 
# group Anagrams together in any random order.
#
if {$argc == 0} {
    puts "Please input a string"
    exit
}

set len [llength $argv]
set inlist $argv
array set result {}
for {set index 0} {$index < $len} {incr index} {
    set tmpstring [lindex $inlist $index]
    set tmplist [lsort [split $tmpstring ""]]
    set key [join $tmplist ""]

    # If arrayName is not the name of an array variable, 
    # or if the array contains no elements, 
    # then an empty list is returned. 
    set value [lindex [array get result $key] 1]
    lappend value $tmpstring
    array set result [list $key $value]
}

puts "Output:"
foreach {key value} [array get result] {
    puts $value
}

沒有留言: