¿Cómo se activa una tabla en una matriz?
-
22-08-2019 - |
Pregunta
Si tengo una tabla en un archivo de texto, tales como
- A B 1
- A C 2
- A D 1
- B A 3
- C D 2
- A E 1
- E D 2
- C B 2
- . . .
- . . .
- . . .
Y tengo otra lista de símbolos en otro archivo de texto. Quiero transformar esta tabla en una estructura de datos Perl como:
- _ A D E. . .
- A 0 1 1. . .
- D 1 0 2. . .
- E 1 2 0. . .
- . . . . . . .
Pero yo sólo necesito un poco de símbolo seleccionado, por ejemplo, A, D y E se seleccionan en el símbolo texto pero B y C no son.
Solución
utilizar una matriz para el primero y un hash 2-dimensional para la segunda. El primero de ellos debería ser más o menos así:
$list[0] # row 1 - the value is "A B 1"
Y el hash como:
$hash{A}{A} # the intersection of A and A - the value is 0
Encontrar la manera de implementar un problema es alrededor del 75% de la batalla mental para mí. No voy a entrar en detalles acerca de cómo imprimir el hash o de la matriz, porque eso es fácil y tampoco estoy del todo claro sobre cómo quiere que se imprime o la cantidad que desea imprimir. Sin embargo, la conversión de la matriz para el hash debe mirar un poco como esto:
foreach (@list) {
my ($letter1, $letter2, $value) = split(/ /);
$hash{$letter1}{$letter2} = $value;
}
Al menos, yo creo que eso es lo que estás buscando. Si realmente quiere usted podría utilizar una expresión regular, pero eso es algo excesivo por sólo 3 valores extracción de una cadena.
EDIT: Por supuesto, se puede renunciar a la @list
y simplemente montar el hash directamente desde el archivo. Pero eso es su trabajo para averiguar, no la mía.
Otros consejos
puede probar esto con awk:
awk -f matrix.awk yourfile.txt> newfile.matrix.txt
donde matrix.awk es:
BEGIN {
OFS="\t"
}
{
row[$1,$2]=$3
if (!($2 in f2)) { header=(header)?header OFS $2:$2;f2[$2]}
if (col1[c]!=$1)
col1[++c]=$1
}
END {
printf("%*s%s\n", length(col1[1])+2, " ",header)
ncol=split(header,colA,OFS)
for(i=1;i<=c;i++) {
printf("%s", col1[i])
for(j=1;j<=ncol;j++)
printf("%s%s%c", OFS, row[col1[i],colA[j]], (j==ncol)?ORS:"")
}
}
Otra manera de hacer esto sería hacer una matriz bidimensional -
my @fArray = ();
## Set the 0,0th element to "_"
push @{$fArray[0]}, '_';
## Assuming that the first line is the range of characters to skip, e.g. BC
chomp(my $skipExpr = <>);
while(<>) {
my ($xVar, $yVar, $val) = split;
## Skip this line if expression matches
next if (/$skipExpr/);
## Check if these elements have already been added in your array
checkExists($xVar);
checkExists($yVar);
## Find their position
for my $i (1..$#fArray) {
$xPos = $i if ($fArray[0][$i] eq $xVar);
$yPos = $i if ($fArray[0][$i] eq $yVar);
}
## Set the value
$fArray[$xPos][$yPos] = $fArray[$yPos][$xPos] = $val;
}
## Print array
for my $i (0..$#fArray) {
for my $j (0..$#{$fArray[$i]}) {
print "$fArray[$i][$j]", " ";
}
print "\n";
}
sub checkExists {
## Checks if the corresponding array element exists,
## else creates and initialises it.
my $nElem = shift;
my $found;
$found = ($_ eq $nElem ? 1 : 0) for ( @{fArray[0]} );
if( $found == 0 ) {
## Create its corresponding column
push @{fArray[0]}, $nElem;
## and row entry.
push @fArray, [$nElem];
## Get its array index
my $newIndex = $#fArray;
## Initialise its corresponding column and rows with '_'
## this is done to enable easy output when printing the array
for my $i (1..$#fArray) {
$fArray[$newIndex][$i] = $fArray[$i][$newIndex] = '_';
}
## Set the intersection cell value to 0
$fArray[$newIndex][$newIndex] = 0;
}
}
No estoy demasiado orgulloso con respecto a la forma en que he manejado referencias pero hay que tener con un principiante aquí (por favor deje sus sugerencias / cambios en los comentarios). El método de hash mencionada por Chris suena mucho más fácil (por no mencionar mucho menos de escribir).
CPAN tiene muchos potencialmente útil suff . Yo uso tabla de datos :: para muchos propósitos. de datos :: pivote también parece prometedor, pero nunca he usado.