http://qs1969.pair.com?node_id=62671

sub f{@a=();for(@_){push @_,shift;push @a,"@_"}@a}push@_,f split while + <>;print join "\n",sort @_
This program implements the Key Word In Context (KWIC) index system (in 98 bytes). This system accepts a sequence of lines of text and circularly shifts each line by repeatedly removing the first word and appending it to the end of the line. The KWIC system then outputs a listing of all circular shifts of all lines, in sorted order.

Run it with perl kwic.pl filename, where filename contains the lines you want to apply the KWIC system to.

This can probably be done more compactly... anybody out there got a shorter solution?

Replies are listed 'Best First'.
Re: Key Word In Context system (golf, anyone)?
by danger (Priest) on Mar 07, 2001 at 10:26 UTC

    I believe this'll do it in 60 bytes:

    print sort map{sub{map{push@_,shift;"@_\n"}@_}->(split)}<>

    update: Yup, I can't count ... 58 characters showing (59 bytes if we include a terminal newline in our file).

Re: Key Word In Context system (golf, anyone)?
by btrott (Parson) on Mar 07, 2001 at 09:49 UTC
    This is a bit shorter:
    % perl -n -e 'sub f{map{push@_,shift;"@_"}@_}push@b,f split;END{$, +="\n";print sort@b}' filename
    The actual code here (between the single quotes) is 72 chars. Though that's cheating slightly since you need the -n to make it work.

    Should have the same output. I'm sure there's a faster/shorter way to do that f sub. Someone'll come up with it.

Re: Key Word In Context system (golf, anyone)?
by jmcnamara (Monsignor) on Mar 27, 2001 at 17:34 UTC
    How about this, 45 bytes perl + 5 bytes for the pipe and sort:
    perl -lane'for(@F){print"@F";push@F,shift@F}' file |sort

    Or with an internal sort, 68 bytes:
    perl -lane'for(@F){push@E,"@F";push@F,shift@F}END{print for sort@E}' f +ile

    John.
    --