How to resolve the algorithm Determine if a string has all the same characters step by step in the Tcl programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Determine if a string has all the same characters step by step in the Tcl programming language

Table of Contents

Problem Statement

Given a character string   (which may be empty, or have a length of zero characters):

Use (at least) these seven test values   (strings):

Show all output here on this page.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Determine if a string has all the same characters step by step in the Tcl programming language

Source code in the tcl programming language

package require Tcl 8.6 ; # For binary encode

array set yesno {1 Yes 0 No}

set test {
    {}
    {   }
    {2}
    {333}
    {.55}
    {tttTTT}
    {4444 444k}
    {jjjjjjj}
}

# Loop through test strings
foreach str $test {
    set chars [dict create] ; # init dictionary
    set same 1
    set prev {}
    # Loop through characters in string
    for {set i 0} {$i < [string length $str]} {incr i} {
        set c [string index $str $i] ; # get char at index
        if {$prev == {}} {
            set prev $c ; # initialize prev if it doesn't exist
        }
        if {$c != $prev} {
            set same 0
            break ; # Found a different char, break out of the loop
        }
    }

    # Handle Output
    puts [format "Tested: %12s (len: %2d). All Same? %3s. " \
              "'$str'" [string length $str] $yesno($same)]
    if {! $same} {
        puts [format " --> Different character '%s' (hex: 0x%s) appears at index: %s." \
                  $c [binary encode hex $c] $i]
    }
}


  

You may also check:How to resolve the algorithm Equal prime and composite sums step by step in the F# programming language
You may also check:How to resolve the algorithm Probabilistic choice step by step in the Quackery programming language
You may also check:How to resolve the algorithm Atomic updates step by step in the Oz programming language
You may also check:How to resolve the algorithm Date format step by step in the 11l programming language
You may also check:How to resolve the algorithm Read entire file step by step in the ALGOL 68 programming language