How to resolve the algorithm One of n lines in a file step by step in the Factor programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm One of n lines in a file step by step in the Factor programming language

Table of Contents

Problem Statement

A method of choosing a line randomly from a file: Is to:

Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling

Let's start with the solution:

Step by Step solution about How to resolve the algorithm One of n lines in a file step by step in the Factor programming language

Source code in the factor programming language

! rosettacode/random-line/random-line.factor
USING: io kernel locals math random ;
IN: rosettacode.random-line

:: random-line ( -- line )
    readln :> choice! 1 :> count!
    [ readln dup ]
    [ count 1 + dup count! random zero?
        [ choice! ] [ drop ] if
    ] while drop
    choice ;


! rosettacode/one-of-n/one-of-n.factor
USING: accessors io kernel math rosettacode.random-line ;
IN: rosettacode.one-of-n

<PRIVATE
TUPLE: mock-stream count last ;
: <mock-stream> ( n -- stream )
    mock-stream new 0 >>count swap >>last ;
M: mock-stream stream-readln ! stream -- line
    dup [ count>> ] [ last>> ] bi <
    [ [ 1 + ] change-count count>> ]
    [ drop f ] if ;
PRIVATE>

: one-of-n ( n -- line )
    <mock-stream> [ random-line ] with-input-stream* ;

USING: assocs formatting locals sequences sorting ;
<PRIVATE
: f>0 ( object/f -- object/0 )
    dup [ drop 0 ] unless ;
:: test-one-of-n ( -- )
    H{ } clone :> chosen
    1000000 [
        10 one-of-n chosen [ f>0 1 + ] change-at
    ] times
    chosen keys natural-sort [
        dup chosen at "%d chosen %d times\n" printf
    ] each ;
PRIVATE>
MAIN: test-one-of-n


  

You may also check:How to resolve the algorithm Generate lower case ASCII alphabet step by step in the Pascal programming language
You may also check:How to resolve the algorithm Textonyms step by step in the Io programming language
You may also check:How to resolve the algorithm Maze solving step by step in the Ada programming language
You may also check:How to resolve the algorithm Same fringe step by step in the zkl programming language
You may also check:How to resolve the algorithm Execute a system command step by step in the DBL programming language