Simple BASH solution that OJ hates


  • 15
    S

    My solution in BASH. It works fine on my computer and I think it's conceptually straightforward. OJ complains exceeding memory.

    ncol=`head -n1 file.txt | wc -w`
    
    for i in `seq 1 $ncol`
    do
        echo `cut -d' ' -f$i file.txt`
    done

  • 0
    P

    Memory Limit Exceeded!


  • 1
    C

    I think any solution using pipe or other command combaination tech won't pass.

    I have used a similar solution to yours. And I didn't use seq to iterate loop variable. Instead, I used c-style loop (so it should use less memory). But no luck, still memory limit exceeded.

    Only one-command solution (like awk) and pure bash solution seem to work.

    The real limit might be the number of subprocesses instead of memory. I don't think bash associative array (psuedo two-dimension array) use less memory, but it passed:

    declare -A matrix
    rowcount=0
    while read line; do
        colcount=0
        for word in $line; do
            matrix[$rowcount,$colcount]=$word
            let colcount++
        done
        let rowcount++
    done < file.txt
    
    for ((i=0; i<colcount; i++)); do
        echo -n ${matrix[0,$i]}
        for ((j=1; j<rowcount; j++)); do
            echo -n ' '${matrix[$j,$i]}
        done
        echo
    done
    

  • 0
    V
    a=`cat file.txt | awk '{ print $1 }' | paste -sd\ `
    b=`cat file.txt | awk '{ print $2 }' | paste -sd\ `
    
    echo $a
    echo $b
    

  • 1

    @slicer Still not sure why OJ printing Memory Limit Exceeded


  • 0
    J

    @slicer Solutions that don't use sed/awk seem to be universally reviled. My perfectly cromulent solution that's equivalent to yours with a marginal improvement on memory usage fails because the input of 'a' should get an output of 'a'... and my output was 'a'. (tl;dr, I think I'm done with the shell problems on here.)

    f=1; for col in head -1 words.txt; do cat words.txt | cut -d' ' -f$f | tr '\n' ' '; f=$(($f+1)); echo; done; echo works on my machine


Log in to reply
 

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