idlize

Форк
0
/
rand_utils.ts 
121 строка · 3.3 Кб
1
/*
2
 * Copyright (c) 2024 Huawei Device Co., Ltd.
3
 * Licensed under the Apache License, Version 2.0 (the "License");
4
 * you may not use this file except in compliance with the License.
5
 * You may obtain a copy of the License at
6
 *
7
 * http://www.apache.org/licenses/LICENSE-2.0
8
 *
9
 * Unless required by applicable law or agreed to in writing, software
10
 * distributed under the License is distributed on an "AS IS" BASIS,
11
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
 * See the License for the specific language governing permissions and
13
 * limitations under the License.
14
 */
15

16
let rand: XorRand|undefined = undefined
17

18
const MASK = 0x7FFFFFFF
19

20
export function initRNG() {
21
    let seed: number
22

23
    console.log(`Use  IDLIZE_SEED env variable to set a seed value.`)
24
    console.log(`Set  IDLIZE_SEED env variable to RANDOM to use a random seed value.`)
25
    console.log(`IDLIZE_SEED=${process.env.IDLIZE_SEED}`)
26

27
    if (process.env.IDLIZE_SEED === undefined) {
28
        seed = 29
29
        console.log(`Env IDLIZE_SEED variable is not.`)
30
        console.log(`Use predefined seed: ${seed}.`)
31
    } else if (process.env.IDLIZE_SEED == "RANDOM") {
32
        seed = Math.floor(Math.random() * 4096)
33
        console.log(`Use random seed: ${seed}`)
34
    } else {
35
        seed = Number(process.env.IDLIZE_SEED)
36
        console.log(`Use seed: ${seed}`)
37
    }
38

39
    rand = new XorRand(seed)
40
}
41

42
class XorRand {
43
    private seed
44

45
    constructor(seed: number) {
46
        this.seed = seed
47
    }
48
    random(): number {
49
        let x = this.seed
50
        x ^= (x << 13) & MASK;
51
        x ^= (x >> 17) & MASK;
52
        x ^= (x << 5) & MASK;
53
        this.seed = x
54
        return x / MASK
55
    }
56
}
57

58

59
export function randInt(max: number, min: number = 0) {
60
    return Math.floor(rand!.random() * (max - min)) + min;
61
}
62

63
function randChar(minChar: string, range: number) {
64
    return String.fromCharCode(minChar.charCodeAt(0) + randInt(range))
65
}
66

67
export function randString(max: number): string {
68

69
    let array: string[] = []
70
    for (let i = 0; i < max; i++) {
71
        const range = randInt(3)
72
        let c = (range == 0)
73
            ? randChar('0', 10)
74
            : (range == 1)
75
                ? randChar('a', 26)
76
                : randChar('A', 26)
77
        array.push(c)
78
    }
79

80
    return array.join('')
81
}
82

83
export function pick<K, V>(keys: K[], gen: (key: K) => string[], pickedNumbers: number = 3): string[] {
84

85
    let values: string[][] = keys.map(it => gen(it))
86
    let picked: string[] = []
87

88
    if (values.map(it => it.length).some(it => it == 0)) {
89
        console.log("Empty arguments!")
90
        return []
91
    }
92

93
    for (let _ = 0; _ < pickedNumbers; _++) {
94
        let v = []
95
        for (let i = 0; i < values.length; i++) {
96
            let len = values[i].length
97
            let index = randInt(len)
98
            let elem = values[i][index]
99
            v.push(elem)
100
        }
101
        picked.push(v.join(","))
102
    }
103

104
    return [...new Set(picked)]
105
}
106

107
export function pickArray<T>(values: T[], maxLen: number, pickedNumbers: number = 3): string[] {
108

109
    let picked: string[] = ["[]"]
110

111
    for (let _ = 0; _ < pickedNumbers; _++) {
112
        let len = randInt(maxLen)
113
        let p: T[] = []
114
        for (let i = 0; i < len; i++) {
115
            p.push(values[randInt(values.length)])
116
        }
117
        picked.push(`[${p.join(",")}]`)
118
    }
119

120
    return [...new Set(picked)]
121
}

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.