Solution using associative array - Transpose File


  • 2
    V
    # Read from the file file.txt and print its transposed content to stdout.
    #!/bin/bash
    
    declare -A matrix
    col=1
    row=1
    
    while read line; do
        col=1
        for word in $line; do
                matrix[$row,$col]=$word
                ((col++))
        done
        ((row++))
    done < file.txt
    
    for ((i=1;i<col;i++)) do
        echo -n ${matrix[1,$i]} 
        for((j=2;j<row;j++)) do
                echo -n ' '${matrix[$j,$i]}
        done
        echo
    done

  • 0
    C

    Wow, I have exactly the same solution


  • 1

    I have one line code as:

    NF=$(head -n 1 file.txt|wc -w);for((i=1;i<=NF;i++)); do cut -d' ' -f $i file.txt |tr '\n' ' '|sed 's/ $//g'; echo; done

    I can process the files in my linux box and failed in LeetCode. I have Memory Limit Exceeded issue.
    I just don't know how small the memory for this server is. Or, what is requirement for the memory usage?


  • 0
    V

    Great! This is I guess a most common and easy to understand solution.


  • 0
    V

    Hey Hongtao,

    Your solution seems a complicated and hard to understand to me. If I were in your place, I will try to brake it into pieces and will find out where exactly the real output differs than your expected output. And there you got ur bug and solution both!

    Hope that helps to you :)


  • 0
    H

    This is rather slow, but pretty human readable!


Log in to reply
 

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