Random sentence from book: Difference between revisions

→‎{{Header|AutoHotkey}}: added missing jq header
m (→‎{{header|Wren}}: Minor tidy)
(→‎{{Header|AutoHotkey}}: added missing jq header)
(One intermediate revision by one other user not shown)
Line 8,931:
escolhido = 1 -> The greater part -> I stumbled into the road in the sky? he asked abruptly. I told them to death tomorrow, my dear. I did not clearly understand how I figure it out. It isnt quite according to what a man in workday clothes, riding one of the farther bank, and in my enfeebled condition, too fatigued to push on at once under water, and, holding my breath until movement was an intermittent, metallic rattle. That! said the woman over the ground heaved under foot for days, on account of the cylinders, that at last induced my brother leading the pony across its head. A waggon locked wheels for a few heaps of broken bricks in the doorway. The thunderstorm had passed. The towers of the horse scattered and gnawed. For a minute she seemed halfway between the life on Mars and terrestrial life, I may remark here, as dissection has since shown, was almost equally simple. The greater
----------------
</pre>
 
=={{header|jq}}==
 
'''Adapted from [[#Wren|Wren]]'''
 
'''Works with jq, the C implementation of jq'''
 
'''Works with gojq, the Go implementation of jq'''
 
In the following, the MRG32k3a combined recursive PRNG is used to generate random numbers;
the code is borrowed from [[Pseudo-random_numbers/Combined_recursive_generator_MRG32k3a#jq|RosettaCode.org]].
 
Invocation of jq is along the lines of
<pre>
< 36-0.txt jq -ncrR -f random-sentences-from-book.jq
</pre>
<syntaxhighlight lang="jq">
### Generic functions
 
def sum(stream): reduce stream as $s (0; . +$s);
 
# Python-style modulus
def Mod($x; $y):
def abs: if . < 0 then - . else . end;
($x % $y) as $m
| if $m < 0 then $m + ($y|abs) else $m end;
 
### The MRG32k3a PRNG
# constants
def A1: [0, 1403580, -810728];
def M1: 4294967087; # pow(2;32) - 209
def A2: [527612, 0, -1370589];
def M2: 4294944443; # pow(2;32) - 22853
def D: M1 + 1;
 
# Initialize the PRNG
def seed($seedState):
if $seedState <= 0 or $seedState >= D
then "Argument of seed must be in the range (0, \(D))" | error
else {x1: [$seedState, 0, 0]} | .x2 = .x1
end ;
 
# Input: {x1, x2} as for MRG32k31
# Output: {x1, x2, nextInt}
def nextInt:
Mod(A1[0]*.x1[0] + A1[1]*.x1[1] + A1[2]*.x1[2]; M1) as $x1i
| Mod(A2[0]*.x2[0] + A2[1]*.x2[1] + A2[2]*.x2[2]; M2) as $x2i
| .x1 = [$x1i, .x1[0], .x1[1]] # keep last three
| .x2 = [$x2i, .x2[0], .x2[1]] # keep last three
| .nextInt = Mod($x1i - $x2i; M1) + 1 ;
 
def nextFloat: nextInt | .nextFloat = (.nextInt / D);
 
### Random sentences
# puctuation to keep (also keep hyphen and apostrophe but do not count as words)
def ending: ".!?";
def pausing:" ,:;";
 
# regex for removing puctuation
def removing: "[\"#\\$\\%&\\(\\)\\*\\+/<=>@\\[\\\\]^_`{|}~“”]";
 
# Emit a stream of lines
def text:
foreach inputs as $in (null;
if . then $in
else # skip to start
($in|index("No one would have believed")) as $ix
| if $ix then $in[$ix:] end
end;
select(.)
| gsub( removing; "" ) # remove extraneous punctuation
| gsub("[\r—]"; " ") # replace \r and EM DASH (unicode 8212) with a space
);
 
def pairsAndTriples(stream):
reduce stream as $x ({};
.pair as $in2
| .triple as $in3
| if .pair | length <= 1 then .pair += [$x] end
| if .triple | length <= 2 then .triple += [$x] end
| if .pair | length == 2
then # .dict2[ .pair | join(" ")] += 1
.dict[ .pair[0] ][.pair[1]] += 1
end
| if $in2 | length == 2
then .pair |= [ last, $x]
end
 
| if .triple | length == 3
then .dict3[.triple[0:2]|join(" ")][ .triple[2]] += 1
end
| if $in3 | length == 3
then .triple |= .[1:] + [$x]
end
) ;
 
# split into words
def words:
text
| splits(" +")
| select(length>0)
| (first( foreach (ending, pausing | split("")[]) as $x (.;
if endswith($x) then [.[:-1], .[-1:]] end)
| select(type=="array")) | .[])
// .
;
 
# $randomFloat should be a randomFloat value
# . should be a JSON object with {WORD: count} pairs
def weightedRandomChoice($randomFloat):
to_entries
| . as $entries
| .[0].key as $default
| sum( .[] | .value) as $n
| ($n * $randomFloat | floor) as $r
| first(
{ sum: 0 }
| foreach $entries[] as $kv (.;
.key = $kv.key
| .sum += $kv.value )
| if $r < .sum then .key else empty end)
// $default;
 
# build 5 random sentences
def sentences:
pairsAndTriples(words) as $library
| range(1;6) as $u
# First word:
| { prng: (seed((now + $u) % D) | nextFloat)}
| .prng.nextFloat as $nf
| .sentence = ($library.dict["."] | weightedRandomChoice($nf))
| .lastOne = .sentence
| .lastTwo = ". " + .sentence
| until(.break;
$library.dict3[.lastTwo] as $x
| if $x
then .prng |= nextFloat
| (.prng.nextFloat) as $nf
| ($x | weightedRandomChoice($nf)) as $nextOne
| .sentence += " " + $nextOne
# stop on reaching ending punctuation
| if any(ending|split("")[]; . as $punctuation | $nextOne | index($punctuation))
then .break = true
else .lastTwo = .lastOne + " " + $nextOne
| .lastOne = $nextOne
end
else debug("unexpected failure") | .break=true
end )
# tidy up sentence
| .sentence
| reduce (ending + pausing | split("")[]) as $p (.; . |= gsub(" [\($p)]"; "\($p)") )
| if startswith("“") and (test("”")|not) then .sentence += "”" end ;
 
sentences
</syntaxhighlight>
{{output}}
<pre>
It was the preparation of mines and pitfalls, and the Martians, and immediately a second company marched through Chobham to deploy on the steamer’s stern shouted together.
It seems to me then that the Martians behind me.
It seems there were shops half opened in the twilight of the window.
It was on fire, and then another.
It may be, the wheel had broken off to get an evening paper, for a time lost in a methodical and discriminating manner.
</pre>
 
3,048

edits