-2

出力要件が変更されたため、以前の質問を言い換えています。

2つのリスト

fruit_type={apple, apple, orange, orange, pineapple, pineapple, pineapple}
num_type = {2, 1, 1, 2, 3, 1, 2}

期待される出力

apple 2
apple 1
orange 1 2
pineapple 3
pineapple 1 2
4

1 に答える 1

0
proc debugityourself-or-maybe-even-port-to-tcl8.4 {fruit_type num_type} {
    foreach fruit $fruit_type num $num_type {
        if {[info exists result]&&
            ([lindex $result end-1 0] eq $fruit)&&
            ([lindex $result end end] <= $num)} {
            lset result end [list {*}[lindex $result end] $num] 
        } else {
            lappend result [list $fruit] [list $num]
        }
    }
    if {[info exists result]} {
        return [concat {*}$result]
    }
}

UPD: 要件が再び変更されたため、新しいバージョンを次に示します。

proc fruits-of-labour-for-new-requirements {fruit_type num_type} {
    foreach fruit $fruit_type num $num_type {
        if {[info exists resultF]&&
            ([lindex $resultF end] eq $fruit)&&
            ([lindex $resultN end end] <= $num)} {
            lset resultN end [list {*}[lindex $resultN end] $num]
        } else {
            lappend resultF $fruit
            lappend resultN [list $num]
        }
    }
    if {[info exists resultF]} {
        # $resultF is a list of fruits, $resultN is a list of
        # lists with corresponding numbers.
        return [list $resultF $resultN]
    }
}
于 2013-01-09T22:13:53.280 に答える