1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
use bools::random::{weighted_random_bools, WeightedRandomBools};
use chars::char_is_graphic;
use chars::crement::{char_to_contiguous_range, contiguous_range_to_char, decrement_char};
use comparison::traits::Min;
use num::random::{random_unsigned_inclusive_range, RandomUnsignedInclusiveRange};
use random::Seed;
use vecs::{random_values_from_vec, RandomValuesFromVec};

/// Uniformly generates random [`char`]s in a closed interval.
///
/// This `struct` is created by [`random_char_range`] and [`random_char_inclusive_range`]; see
/// their documentation for more.
#[derive(Clone, Debug)]
pub struct RandomCharRange {
    chunks: RandomUnsignedInclusiveRange<u32>,
}

impl Iterator for RandomCharRange {
    type Item = char;

    #[inline]
    fn next(&mut self) -> Option<char> {
        contiguous_range_to_char(self.chunks.next().unwrap())
    }
}

/// Uniformly generates random [`char`]s in a closed interval, weighting graphic and non-graphic
/// [`char`]s separately.
///
/// This `struct` is created by [`graphic_weighted_random_char_range`] and
/// [`graphic_weighted_random_char_inclusive_range`]; see their documentation for more.
#[derive(Clone, Debug)]
pub struct WeightedGraphicRandomCharRange {
    xs: WeightedRandomBools,
    graphic: RandomValuesFromVec<char>,
    non_graphic: RandomValuesFromVec<char>,
}

impl Iterator for WeightedGraphicRandomCharRange {
    type Item = char;

    fn next(&mut self) -> Option<char> {
        if self.xs.next().unwrap() {
            self.graphic.next()
        } else {
            self.non_graphic.next()
        }
    }
}

/// Uniformly generates random [`char`]s.
///
/// $P(c) = \frac{1}{2^{20}+2^{16}-2^{11}}$.
///
/// The output length is infinite.
///
/// # Worst-case complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::chars::random::random_chars;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
///     random_chars(EXAMPLE_SEED)
///         .take(10)
///         .collect::<String>()
///         .as_str(),
///     "\u{5f771}\u{87234}\u{bcd36}\u{9e195}\u{5da07}\u{36553}\u{45028}\u{1cdfd}\u{d8530}\u{c7f2e}"
/// )
/// ```
#[inline]
pub fn random_chars(seed: Seed) -> RandomCharRange {
    random_char_inclusive_range(seed, char::MIN, char::MAX)
}

/// Uniformly generates random ASCII [`char`]s.
///
/// $$
/// P(c) = \\begin{cases}
///     2^{-7} & \text{if} \\quad c < \\backslash\\text{u\\{0x80\\}} \\\\
///     0 & \\text{otherwise}
/// \\end{cases}
/// $$
///
/// The output length is infinite.
///
/// # Worst-case complexity per iteration
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::chars::random::random_ascii_chars;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
///     random_ascii_chars(EXAMPLE_SEED)
///         .take(20)
///         .collect::<String>()
///         .as_str(),
///     "q^\u{17}bF\\4T!/\u{1}q6\n/\u{11}Y\\wB"
/// )
/// ```
#[inline]
pub fn random_ascii_chars(seed: Seed) -> RandomCharRange {
    random_char_inclusive_range(seed, char::MIN, '\u{7f}')
}

/// Uniformly generates random [`char`]s in the half-open interval $[a, b)$.
///
/// $a$ must be less than $b$. This function cannot create a range that includes `char::MAX`; for
/// that, use [`random_char_inclusive_range`].
///
/// $$
/// P(x) = \\begin{cases}
///     \frac{1}
///     {\mathrm{char\\_to\\_contiguous\\_range(b)}-\mathrm{char\\_to\\_contiguous\\_range(a)}} &
///         \text{if} \\quad a \leq x < b \\\\
///     0 & \\text{otherwise}
/// \\end{cases}
/// $$
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Panics
/// Panics if $a \geq b$.
///
/// # Examples
/// ```
/// use malachite_base::chars::random::random_char_range;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
///     random_char_range(EXAMPLE_SEED, 'a', 'z')
///         .take(50)
///         .collect::<String>()
///         .as_str(),
///     "rlewrsgkdlbeouylrelopxqkoonftexoshqulgvonioatekqes"
/// )
/// ```
#[inline]
pub fn random_char_range(seed: Seed, a: char, mut b: char) -> RandomCharRange {
    if a >= b {
        panic!("a must be less than b. a: {}, b: {}", a, b);
    }
    decrement_char(&mut b);
    random_char_inclusive_range(seed, a, b)
}

/// Uniformly generates random [`char`]s in the closed interval $[a, b]$.
///
/// $a$ must be less than or equal to $b$.
///
/// $$
/// P(x) = \\begin{cases}
///     \frac{1}
///         {\mathrm{char\\_to\\_contiguous\\_range(b)}-\mathrm{char\\_to\\_contiguous\\_range(a)}
///         +1} &
///         \text{if} \\quad a \leq x < b \\\\
///     0 & \\text{otherwise}
/// \\end{cases}
/// $$
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Panics
/// Panics if $a > b$.
///
/// # Examples
/// ```
/// use malachite_base::chars::random::random_char_inclusive_range;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
///     random_char_inclusive_range(EXAMPLE_SEED, 'a', 'z')
///         .take(50)
///         .collect::<String>()
///         .as_str(),
///     "rlewrsgkdlbeouylrelopxqkoonftexoshqulgvonioatekqes"
/// )
/// ```
#[inline]
pub fn random_char_inclusive_range(seed: Seed, a: char, b: char) -> RandomCharRange {
    if a > b {
        panic!("a must be less than or equal to b. a: {}, b: {}", a, b);
    }
    RandomCharRange {
        chunks: random_unsigned_inclusive_range(
            seed,
            char_to_contiguous_range(a),
            char_to_contiguous_range(b),
        ),
    }
}

/// Generates random [`char`]s, weighting graphic and non-graphic [`char`]s separately.
///
/// See [`char_is_graphic`](crate::chars::char_is_graphic) for the definition of a graphic
/// [`char`].
///
/// Let $n_p$ be `p_numerator` and $d_p$ be `p_denominator`, and let $p = p_n/p_d$.
///
/// The set of graphic [`char`]s is selected with probability $p$, and the set of non-graphic
/// [`char`]s with probability $1-p$. Then, a [`char`] is selected uniformly from the appropriate
/// set. There are 142,523 graphic [`char`]s out of 1,112,064, so we have
///
/// $$
/// P(x) = \\begin{cases}
///     \frac{p}{142523} & \text{if} \\quad x \\ \\text{is} \\ \\text{graphic} \\\\
///     \frac{1-p}{969541} & \\text{otherwise}
/// \\end{cases}
/// $$
///
/// To recover the uniform distribution, use $p = 142523/1112064$, which is roughly $1/8$.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Panics
/// Panics if `p_denominator` is zero or `p_denominator > p_denominator`.
///
/// # Examples
/// ```
/// use malachite_base::chars::random::graphic_weighted_random_chars;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
///     graphic_weighted_random_chars(EXAMPLE_SEED, 10, 11)
///         .take(20)
///         .collect::<String>()
///         .as_str(),
///     "𘌮𰠁礣깼ꅐ枃쭧𬡵╲𣕽⢎𰾞瀑\u{8c6d6}ՠ𦫷𪆉\u{36c8a}\u{d6075}𧂻"
/// )
/// ```
#[inline]
pub fn graphic_weighted_random_chars(
    seed: Seed,
    p_numerator: u64,
    p_denominator: u64,
) -> WeightedGraphicRandomCharRange {
    graphic_weighted_random_char_inclusive_range(
        seed,
        char::MIN,
        char::MAX,
        p_numerator,
        p_denominator,
    )
}

/// Generates random ASCII [`char`]s, weighting graphic and non-graphic [`char`]s separately.
///
/// See [`char_is_graphic`](crate::chars::char_is_graphic) for the definition of a graphic
/// [`char`].
///
/// Let $n_p$ be `p_numerator` and $d_p$ be `p_denominator`, and let $p = p_n/p_d$.
///
/// The set of graphic ASCII [`char`]s is selected with probability $p$, and the set of non-graphic
/// ASCII [`char`]s with probability $1-p$. Then, a [`char`] is selected uniformly from the
/// appropriate set. There are 95 graphic ASCII [`char`]s out of 128, so we have
///
/// $$
/// P(x) = \\begin{cases}
///     \frac{p}{95} & \text{if} \\quad
///     x < \\backslash\\text{u\\{0x80\\}} \\ \\text{and} \\ x \\ \\text{is graphic} \\\\
///     \frac{1-p}{33} & \text{if} \\quad
///     x < \\backslash\\text{u\\{0x80\\}} \\ \\text{and} \\ x \\ \\text{is not graphic} \\\\
///     0 & \\text{otherwise}
/// \\end{cases}
/// $$
///
/// To recover the uniform distribution, use $p = 95/128$.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Panics
/// Panics if `p_denominator` is zero or `p_denominator > p_denominator`.
///
/// # Examples
/// ```
/// use malachite_base::chars::random::graphic_weighted_random_ascii_chars;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
///     graphic_weighted_random_ascii_chars(EXAMPLE_SEED, 10, 11)
///         .take(40)
///         .collect::<String>()
///         .as_str(),
///     "x14N(bcXr$g)7\u{1b}/E+\u{8}\rf\u{2}\u{11}Y\u{11}Poo.$V2R.$V=6\u{13}\t\u{11}"
/// )
/// ```
#[inline]
pub fn graphic_weighted_random_ascii_chars(
    seed: Seed,
    p_numerator: u64,
    p_denominator: u64,
) -> WeightedGraphicRandomCharRange {
    graphic_weighted_random_char_inclusive_range(
        seed,
        char::MIN,
        '\u{7f}',
        p_numerator,
        p_denominator,
    )
}

/// Generates random [`char`]s in the half-open interval $[a, b)$, weighting graphic and
/// non-graphic [`char`]s separately.
///
/// See [`char_is_graphic`](crate::chars::char_is_graphic) for the definition of a graphic
/// [`char`].
///
/// Let $n_p$ be `p_numerator` and $d_p$ be `p_denominator`, and let $p = p_n/p_d$.
///
/// The set of graphic [`char`]s in the specified range is selected with probability $p$, and the
/// set of non-graphic [`char`]s in the range with probability $1-p$. Then, a [`char`] is selected
/// uniformly from the appropriate set.
///
/// $a$ must be less than $b$. Furthermore, $[a, b)$ must contain both graphic and non-graphic
/// [`char`]s. This function cannot create a range that includes `char::MAX`; for that, use
/// [`graphic_weighted_random_char_inclusive_range`].
///
/// Let $g$ be the number of graphic [`char`]s in $[a, b)$. Then we have
///
/// $$
/// P(x) = \\begin{cases}
///     \frac{p}{g} & a \leq x < b \\ \\text{and} \\ x \\ \\text{is graphic} \\\\
///     \frac{1-p}{b-a-g} & a \leq x < b \\ \\text{and} \\ x \\ \\text{is not graphic} \\\\
///     0 & \\text{otherwise}
/// \\end{cases}
/// $$
///
/// To recover the uniform distribution, use $p = g/(b-a)$.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Panics
/// Panics if `p_denominator` is zero or `p_denominator > p_denominator`, if $a \geq b$, if
/// $[a, b)$ contains no graphic [`char`]s, or if $[a, b)$ contains only graphic [`char`]s.
///
/// # Examples
/// ```
/// use malachite_base::chars::random::graphic_weighted_random_char_range;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
///     graphic_weighted_random_char_range(EXAMPLE_SEED, '\u{100}', '\u{400}', 10, 11)
///         .take(30)
///         .collect::<String>()
///         .as_str(),
///     "ǘɂŜȢΙƘƣʅΰǟ˳ˊȇ\u{31b}ʰɥΈ\u{324}\u{35a}Ϟ\u{367}\u{337}ƃ\u{342}ʌμƢϳϪǰ"
/// )
/// ```
#[inline]
pub fn graphic_weighted_random_char_range(
    seed: Seed,
    a: char,
    mut b: char,
    p_numerator: u64,
    p_denominator: u64,
) -> WeightedGraphicRandomCharRange {
    if a >= b {
        panic!("a must be less than b. a: {}, b: {}", a, b);
    }
    decrement_char(&mut b);
    graphic_weighted_random_char_inclusive_range(seed, a, b, p_numerator, p_denominator)
}

/// Generates random [`char`]s in the closed interval $[a, b]$, weighting graphic and
/// non-graphic [`char`]s separately.
///
/// See [`char_is_graphic`](crate::chars::char_is_graphic) for the definition of a graphic
/// [`char`].
///
/// Let $n_p$ be `p_numerator` and $d_p$ be `p_denominator`, and let $p = p_n/p_d$.
///
/// The set of graphic [`char`]s in the specified range is selected with probability $p$, and the
/// set of non-graphic [`char`]s in the range with probability $1-p$. Then, a [`char`] is selected
/// uniformly from the appropriate set.
///
/// $a$ must be less than $b$. Furthermore, $[a, b]$ must contain both graphic and non-graphic
/// [`char`]s. This function cannot create a range that includes `char::MAX`; for that, use
/// [`graphic_weighted_random_char_inclusive_range`].
///
/// Let $g$ be the number of graphic [`char`]s in $[a, b]$. Then we have
///
/// $$
/// P(x) = \\begin{cases}
///     \frac{p}{g} & a \leq x < b \\ \\text{and} \\ x \\ \\text{is graphic} \\\\
///     \frac{1-p}{b-a-g+1} & a \leq x < b \\ \\text{and} \\ x \\ \\text{is not graphic} \\\\
///     0 & \\text{otherwise}
/// \\end{cases}
/// $$
///
/// To recover the uniform distribution, use $p = g/(b-a+1)$.
///
/// The output length is infinite.
///
/// # Expected complexity per iteration
/// Constant time and additional memory.
///
/// # Panics
/// Panics if `p_denominator` is zero or `p_denominator > p_denominator`, if $a > b$, if $[a, b]$
/// contains no graphic [`char`]s, or if $[a, b]$ contains only graphic [`char`]s.
///
/// # Examples
/// ```
/// use malachite_base::chars::random::graphic_weighted_random_char_inclusive_range;
/// use malachite_base::random::EXAMPLE_SEED;
///
/// assert_eq!(
///     graphic_weighted_random_char_inclusive_range(EXAMPLE_SEED, '\u{100}', '\u{3ff}', 10, 11)
///         .take(30)
///         .collect::<String>()
///         .as_str(),
///     "ǘɂŜȢΙƘƣʅΰǟ˳ˊȇ\u{31b}ʰɥΈ\u{324}\u{35a}Ϟ\u{367}\u{337}ƃ\u{342}ʌμƢϳϪǰ"
/// )
/// ```
pub fn graphic_weighted_random_char_inclusive_range(
    seed: Seed,
    a: char,
    b: char,
    p_numerator: u64,
    p_denominator: u64,
) -> WeightedGraphicRandomCharRange {
    if a > b {
        panic!("a must be less than or equal to b. a: {}, b: {}", a, b);
    }
    let (graphic_chars, non_graphic_chars): (Vec<_>, Vec<_>) =
        (a..=b).partition(|&c| char_is_graphic(c));
    if graphic_chars.is_empty() {
        panic!("The range {:?}..={:?} contains no graphic chars", a, b);
    }
    if non_graphic_chars.is_empty() {
        panic!("The range {:?}..={:?} only contains graphic chars", a, b);
    }
    WeightedGraphicRandomCharRange {
        xs: weighted_random_bools(seed.fork("xs"), p_numerator, p_denominator),
        graphic: random_values_from_vec(seed.fork("graphic"), graphic_chars),
        non_graphic: random_values_from_vec(seed.fork("non_graphic"), non_graphic_chars),
    }
}