Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Key Word In Context system (golf, anyone)?

by Falkkin (Chaplain)
on Mar 07, 2001 at 09:18 UTC ( #62671=obfuscated: print w/replies, xml ) Need Help??

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.
    --

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: obfuscated [id://62671]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (3)
As of 2023-04-02 05:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?