home *** CD-ROM | disk | FTP | other *** search
/ ftp.cs.arizona.edu / ftp.cs.arizona.edu.tar / ftp.cs.arizona.edu / icon / historic / v941.tgz / icon.v941src.tar / icon.v941src / ipl / progs / choose.icn < prev    next >
Text File  |  2002-01-14  |  2KB  |  74 lines

  1. ############################################################################
  2. #
  3. #    File:     choose.icn
  4. #
  5. #    Subject:  Program to pick lines from a file
  6. #
  7. #    Author:   Gregg M. Townsend
  8. #
  9. #    Date:     January 14, 2002
  10. #
  11. ############################################################################
  12. #
  13. #   This file is in the public domain.
  14. #
  15. ############################################################################
  16. #
  17. #  usage:  choose [-N] [file...]
  18. #
  19. #  This program randomly selects N lines from the input stream and
  20. #  outputs them in order.  If N is omitted, one line is chosen.
  21. #  If the input stream supplies fewer than N lines, all are output.
  22. #
  23. ############################################################################
  24. #
  25. #  Links: random
  26. #
  27. ############################################################################
  28.  
  29. link random
  30.  
  31. global wanted        # number of lines wanted
  32. global seen        # number of lines read so far
  33.  
  34. record chosen(        # one tentatively chosen input line
  35.    lnum,        #    line number
  36.    text)        #    data
  37.  
  38. global llist        # list of tentatively chosen lines
  39.  
  40. procedure main(args)
  41.    local fname
  42.  
  43.    if wanted := abs(integer(args[1])) then
  44.       get(args)
  45.    else
  46.       wanted := 1
  47.  
  48.    llist := []
  49.    seen := 0
  50.    randomize()
  51.  
  52.    if *args = 0 then
  53.       dofile(&input)
  54.    else while fname := get(args) do
  55.       dofile(open(fname)) | stop("cannot open ", fname)
  56.  
  57.    llist := sortf(llist, 1)
  58.    every write((!llist).text)
  59. end
  60.  
  61. procedure dofile(f)
  62.    local line
  63.  
  64.    while line := read(f) do {
  65.       seen +:= 1
  66.       if seen <= wanted then
  67.          put(llist, chosen(seen, line))
  68.       else if ?0 < wanted / real(seen) then
  69.          ?llist := chosen(seen, line)
  70.       }
  71.    close(f)
  72.    return
  73. end
  74.