Challenging scenario

Hi,

My input file contains

1,2
2,4
3,6
4,9
9,10

My expected output is

1,10
2,10
3,6
4,1
9,10

the logic is we need to chain the records, find out the target.

How we can achieve this in unix?

Thanks

Shouldn't output be:

1,10
2,10
3,6
4,10
9,10

?

@pandeesh: How do you arrive at output from input? What's the logic?

Yes.You are correct. That's 4,10.

---------- Post updated at 11:58 PM ---------- Previous update was at 11:56 PM ----------

You need t chain through the input.
For example, take the first record

1--->2--->4-->9---->10 

So the output will be 1,10.

I hope you get it.

thanks

Try this script:

#!/usr/bin/perl
open I,$ARGV[0];
while (<I>){
  chomp;
  @x=split /,/;
  $a{$x[0]}=$x[1];
}
for $i (keys %a){
  $t=$a{$i};
  $b{$i}=$a{$i};
  $q=1;
  while ($q){
    if ($a{$t}){
      $q=1;
      $b{$i}=$a{$t};
      $t=$a{$t};
    } else {
      $q=0;
    }
  }
}
for $i (keys %b){
  print "$i,$b{$i}\n";
}

Run it as: ./script.pl file

1 Like

I see bartus11 posted a perl solution, here's the awk I was working on:

 awk -F , '
    BEGIN { max = 0; }
    {
        nxt[$1+0] = $2+0;
        if( $1+0 > max )
            max = $1;
        next;
    }
    END {
        for( i = 1; i <= max; i++ )
        {
            if( nxt != "" )
            {
                n = i;
                while( nxt[n] != "" )
                    n = nxt[n];
                printf( "%d,%d\n", i, n );
            }
        }
    }
'  input-file

---------- Post updated at 15:34 ---------- Previous update was at 15:29 ----------

A bit cleaner, but doesn't preserve original order:

 awk -F , '
    { nxt[$1+0] = $2+0; }
    END {
        for( i in nxt )
        {
                n = i;
                while( n in nxt )
                    n = nxt[n];
                printf( "%d,%d\n", i, n );
        }
    }
' input-file
1 Like

Also preserves order:

awk -F , 'FNR==NR {nxt[$1+0]=$2+0;next}
{for(n=$1;n in nxt;n=nxt[n]); print $1","n}' infile infile
1 Like