Search code examples
arrayslinuxshellsedgalois-field

C-shell: How to create multiple arrays from a single line of standard input?


I need to find a way to complete the following task using C-shell (I can't use a different shell):

There is a program that outputs polynomial factors from a larger polynomial, using Galois Field calculations. The output is a single line, and looks something like this (don't pay attention to the actual value of the numbers; I randomly chose them and they don't mathematically work out):

(0 1 4 6 7 8 11 12 13) = (0 1)^3 * (0 4 5) * (0 2 4 6)^4 * (0 2 3)^2

The way polynomial math works, if a factor is raised to an even number, then that factor is superfluous to the value of the polynomial. Sort of like multiplying by 1. What I need to do is extract the polynomial factors and eliminate the superfluous factors.

Using sed, I have been able to alter the above expression into the form of

(0 1) ^ 3 * (0 4 5) * (0 2 4 6) ^ 4 * (0 2 3) ^ 2

but I am unsure of how to proceed.

I want to take the above, input it into a C-shell script, and make the following array assignments:

Array A = (0 1)
Array B = (0 4 5)

I think the best route would be to first separate the polynomial factors into separate lines, like this:

(0 1) ^ 3
(0 4 5)
(0 2 4 6) ^ 4 
(0 2 3) ^ 2

but I am uncertain as to how to do this.

Can anyone provide any useful help or hints? Be aware that the number of polynomial factors will change, but I don't expect to ever have any more than 8. The exponent values aren't significant; I only need to determine whether they are even or odd. I can easily do that if they are assigned to a variable or an array. A maximum possible size of a single factor is probably around 50 individuals numbers inside the parentheses.


Solution

  • You probably want something like next:

    #!/bin/tcsh
    
    set str="(0 1) ^ 3 * (0 4 5) * (0 2 4 6) ^ 4 * (0 2 3) ^ 2"
    
    echo "My string: ===$str==="
    set arrnum = 0
    foreach line ( "`echo '$str' | grep -oP '\([^)]*\)'`" )
        @ arrnum++
        set eval_line = "set array$arrnum = $line"
        eval "$eval_line"
    end
    
    echo "created $arrnum arrays (array1 .. array$arrnum)"
    foreach i (`seq $arrnum`)
        set arrname = "array$i"
        echo "The content of $arrname"
        set temp = `eval echo '$'$arrname`
        foreach item ( $temp )
            echo $item
        end
    end
    

    It creates array1 .. arrayN for each (x x x x x) group. For your string:

    (0 1) ^ 3 * (0 4 5) * (0 2 4 6) ^ 4 * (0 2 3) ^ 2
    

    prints

    My string: ===(0 1) ^ 3 * (0 4 5) * (0 2 4 6) ^ 4 * (0 2 3) ^ 2===
    created 4 arrays (array1 .. array4)
    The content of array1
    0
    1
    The content of array2
    0
    4
    5
    The content of array3
    0
    2
    4
    6
    The content of array4
    0
    2
    3