Got 2 solutions - why are they not accepted?


  • 0
    A

    Hi there,

    I got 2 solutions to the Shell Word Frequency #192:

    Without pipes:

    inputfile="words.txt" 
    out="/var/tmp/output"
    
    linecount=`cat ${inputfile} |wc -l |awk '{ print $1 }'` 
    wordcount=`cat ${inputfile} |wc -w |awk '{ print $1 }'`
    
    if [ -f $out ] 
    then
             rm $out 
    fi
        
    if [ $linecount > 0 ] then
            cat $inputfile | while read line
            do
                    for word in $line
                    do
                            count=`grep -o ${word} ${inputfile}|wc -w|awk '{print $1}'`
                            echo "${word} ${count}" >> /var/tmp/output
                    done
            done
    fi
    
    cat $out|sort -k 2 -r|uniq 
    rm $out
    

    That also works fine when I test it but submitting will result in "Runtime Error".

    Runtime Error Message: Line 18: 0: restricted: cannot redirect output
    Last executed input: a

    With pipes:

    cat words.txt |tr -s ' ' '\n'|sort|uniq -c|sort -r|awk -F" " '{print $2, $1}'
    

    So this definitely works when I run it in Shell but submitting it here always says it produces the wrong output:

    Input: how many cans can a canner can if a canner can can cans\na
    canner can can as many cans as a canner can if a canner can can a
    can\na canner can can as many cans as a canner can cans Output: a
    8\ncanner 7\ncans 5\nas 4\nmany 3\nif 2\nhow 1\ncan 13 Expected: can
    13\na 8\ncanner 7\ncans 5\nas 4\nmany 3\nif 2\nhow 1

    I ran it through the same test case in it does definitely produce the right order. Any suggestions?


  • 0
    E

    The last sort result is incorrect, should sort by number instead of string.


  • 0
    A

    Thanks, got it.

    Final Accepted Solution:

    cat words.txt |tr -s ' ' '\n'|sort|uniq -c|sort -k1 -r -n|awk -F" " '{print $2, $1}'

    -n (numeric sort) in the second sort did the trick.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.