Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

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


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: obfuscated [id://62671]
Approved by root
[Corion]: Also, London is always a nice visit, as I got to meet a friend there, and spent some time offline, working on "minor" features of the shadertoy thing ;)
[marto]: maybe next year when the kids are a little older I'll have time to attend perl events in Europe
[Corion]: marto: Yeah - there isn't a Perl Day-Care at Perl events - we thought about it for YAPC::Europe 2012 but it's a gigantic effort to organize that
[marto]: Corion yeah, it'd be too costly for me to bring them both :P

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2016-12-07 09:33 GMT
Find Nodes?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:

    Results (125 votes). Check out past polls.