JavaScript Python PHP
function executar(values) {
function lgText(value) { if (typeof value !== 'string' || value.length > 100000 || !value.isWellFormed())
throw new Error('Use texto Unicode válido de até 100 mil caracteres por campo.'); return value; }
function generateLogicRandom(v) {
const mode = lgChoice(v, 'mode', ['Strings', 'Inteiros']), count = lgInt(v, 'count', 1, 500), repeat = lgYes(v, 'repeat'), next = lgRng(v.seed), make = lgValueFactory(v, mode, next);
const capacity = mode === 'Strings' ? BigInt([...v.alphabet].length) ** BigInt(Number(v.length)) : BigInt(Number(v.max) - Number(v.min) + 1);
if (!repeat && capacity < BigInt(count))
throw new Error('Quantidade maior que as combinações disponíveis sem repetição.');
const values = [], used = new Set();
for (let attempt = 0; values.length < count; attempt++) {
if (attempt >= 200000)
throw new Error('Limite de tentativas sem repetição atingido. Reduza a quantidade ou amplie o domínio.');
const value = make();
if (repeat || !used.has(value)) {
values.push(value);
used.add(value);
}
}
return lgJson(values);
}
function lgInt(v, key, min, max) { const raw = v[key], n = Number(raw); if (!/^-?\d+$/.test(raw ?? '') || !Number.isSafeInteger(n) || n < min || n > max)
throw new Error(`${key}: informe um inteiro de ${min} a ${max}.`); return n; }
function lgChoice(v, key, choices) { if (!choices.includes(v[key]))
throw new Error(`Opção inválida: ${key}.`); return v[key]; }
function lgYes(v, key) { return lgChoice(v, key, ['Sim', 'Não']) === 'Sim'; }
function lgRng(seed) {
if (seed.length > 128)
throw new Error('Seed: até 128 caracteres.');
let state = 2166136261;
for (const byte of new TextEncoder().encode(seed))
state = Math.imul(state ^ byte, 16777619) >>> 0;
return (max) => {
if (!Number.isSafeInteger(max) || max < 1 || max > 4294967296)
throw new Error('Intervalo aleatório não suportado.');
const limit = Math.floor(4294967296 / max) * max;
let word;
do {
if (seed !== '') {
state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
word = Math.imul(state ^ (state >>> 16), 0x21f0aaad) >>> 0;
word = Math.imul(word ^ (word >>> 15), 0x735a2d97) >>> 0;
word = (word ^ (word >>> 15)) >>> 0;
}
else
word = crypto.getRandomValues(new Uint32Array(1))[0];
} while (word >= limit);
return word % max;
};
}
function lgValueFactory(v, type, next) {
if (type === 'Booleanos')
return () => Boolean(next(2));
if (type === 'Inteiros') {
const min = lgInt(v, 'min', -1000000000, 1000000000), max = lgInt(v, 'max', min, 1000000000);
return () => min + next(max - min + 1);
}
const length = lgInt(v, 'length', 1, 128), alphabet = [...v.alphabet];
if (!alphabet.length || alphabet.length > 128 || new Set(alphabet).size !== alphabet.length)
throw new Error('Alfabeto: 1–128 caracteres Unicode distintos; espaços contam.');
return () => Array.from({ length }, () => alphabet[next(alphabet.length)]).join('');
}
function lgJson(value, compact = false) { const text = JSON.stringify(value, null, compact ? undefined : 2); if (text.length > 1000000)
throw new Error('Resultado excede 1 milhão de caracteres. Reduza os limites.'); return { text, file: 'resultado.json' }; }
for (const value of Object.values(values)) lgText(value);
return generateLogicRandom(values);
}
import json
import re
import secrets
def executar(values):
def integer(key, low, high):
raw = values.get(key, '')
if not re.fullmatch(r'-?[0-9]+', raw) or not low <= int(raw) <= high:
raise ValueError(f'{key}: informe um inteiro de {low} a {high}.')
return int(raw)
def choice(key, options):
if values.get(key) not in options:
raise ValueError('Opção inválida: ' + key)
return values[key]
def yes(key):
return choice(key, ['Sim', 'Não']) == 'Sim'
def output(value, compact=False):
text = json.dumps(value, ensure_ascii=False, indent=None if compact else 2, separators=(',', ':') if compact else (',', ': '), allow_nan=False)
if len(text.encode('utf-16-le')) // 2 > 1000000:
raise ValueError('Resultado excede 1 milhão de caracteres. Reduza os limites.')
return {'text': text, 'file': 'resultado.json'}
def rng(seed):
if len(seed.encode('utf-16-le')) // 2 > 128:
raise ValueError('Seed: até 128 caracteres.')
state = 2166136261
for byte in seed.encode('utf-8'):
state = ((state ^ byte) * 16777619) & 0xffffffff
def next_int(maximum):
nonlocal state
limit = (4294967296 // maximum) * maximum
while True:
if seed:
state = (state * 1664525 + 1013904223) & 0xffffffff
word = ((state ^ (state >> 16)) * 0x21f0aaad) & 0xffffffff
word = ((word ^ (word >> 15)) * 0x735a2d97) & 0xffffffff
word ^= word >> 15
else:
word = secrets.randbits(32)
if word < limit:
return word % maximum
return next_int
def factory(kind, next_int):
if kind == 'Booleanos':
return lambda: bool(next_int(2))
if kind == 'Inteiros':
low = integer('min', -1000000000, 1000000000)
high = integer('max', low, 1000000000)
return lambda: low + next_int(high - low + 1)
length = integer('length', 1, 128)
alphabet = values['alphabet']
if not 1 <= len(alphabet) <= 128 or len(set(alphabet)) != len(alphabet):
raise ValueError('Alfabeto: 1–128 caracteres Unicode distintos; espaços contam.')
return lambda: ''.join(alphabet[next_int(len(alphabet))] for _ in range(length))
for value in values.values():
if not isinstance(value, str) or len(value.encode('utf-16-le')) // 2 > 100000:
raise ValueError('Use texto Unicode válido de até 100 mil caracteres por campo.')
value.encode('utf-8')
kind = choice('mode', ['Strings', 'Inteiros'])
count, repeat = integer('count', 1, 500), yes('repeat')
make = factory(kind, rng(values['seed']))
capacity = len(values['alphabet']) ** int(values['length']) if kind == 'Strings' else int(values['max']) - int(values['min']) + 1
if not repeat and capacity < count:
raise ValueError('Quantidade maior que as combinações disponíveis sem repetição.')
result, used = [], set()
for _ in range(200000):
value = make()
if repeat or value not in used:
result.append(value)
used.add(value)
if len(result) == count:
return output(result)
raise ValueError('Limite de tentativas sem repetição atingido. Reduza a quantidade ou amplie o domínio.')
<?php
function executar(array $values): array {
// PHP 8.1+ de 64 bits, JSON, PCRE e iconv.
$chars = static function (string $text): array {
$result = preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY);
if ($result === false) throw new InvalidArgumentException('Use Unicode válido.');
return $result;
};
$integer = static function (string $key, int $low, int $high) use ($values): int {
$raw = $values[$key] ?? '';
if (!preg_match('/^-?[0-9]+$/D', $raw) || strlen(ltrim($raw, '-0')) > 10 || (int)$raw < $low || (int)$raw > $high) throw new InvalidArgumentException("$key: informe um inteiro de $low a $high.");
return (int)$raw;
};
$choice = static function (string $key, array $options) use ($values): string {
if (!in_array($values[$key] ?? null, $options, true)) throw new InvalidArgumentException('Opção inválida: ' . $key);
return $values[$key];
};
$yes = static fn(string $key): bool => $choice($key, ['Sim', 'Não']) === 'Sim';
$output = static function ($value, bool $compact = false): array {
$flags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_LINE_TERMINATORS | JSON_THROW_ON_ERROR;
$text = json_encode($value, $flags | ($compact ? 0 : JSON_PRETTY_PRINT));
if (!$compact) $text = preg_replace_callback('/^ +/m', static fn($m) => str_repeat(' ', intdiv(strlen($m[0]), 2)), $text);
if (strlen(iconv('UTF-8', 'UTF-16LE', $text)) / 2 > 1000000) throw new InvalidArgumentException('Resultado excede 1 milhão de caracteres. Reduza os limites.');
return ['text' => $text, 'file' => 'resultado.json'];
};
$rng = static function (string $seed): Closure {
if (strlen(iconv('UTF-8', 'UTF-16LE', $seed)) / 2 > 128) throw new InvalidArgumentException('Seed: até 128 caracteres.');
$state = 2166136261;
foreach (unpack('C*', $seed) as $byte) $state = (($state ^ $byte) * 16777619) & 0xffffffff;
return static function (int $maximum) use ($seed, &$state): int {
$limit = intdiv(4294967296, $maximum) * $maximum;
do {
if ($seed !== '') {
$state = ($state * 1664525 + 1013904223) & 0xffffffff;
$word = (($state ^ ($state >> 16)) * 0x21f0aaad) & 0xffffffff;
$word = (($word ^ ($word >> 15)) * 0x735a2d97) & 0xffffffff;
$word ^= $word >> 15;
} else $word = unpack('N', random_bytes(4))[1];
} while ($word >= $limit);
return $word % $maximum;
};
};
$factory = static function (string $kind, Closure $next) use ($integer, $values, $chars): Closure {
if ($kind === 'Booleanos') return static fn() => (bool)$next(2);
if ($kind === 'Inteiros') {
$low = $integer('min', -1000000000, 1000000000);
$high = $integer('max', $low, 1000000000);
return static fn() => $low + $next($high - $low + 1);
}
$length = $integer('length', 1, 128);
$alphabet = $chars($values['alphabet']);
if (count($alphabet) < 1 || count($alphabet) > 128 || count(array_unique($alphabet)) !== count($alphabet)) throw new InvalidArgumentException('Alfabeto: 1–128 caracteres Unicode distintos; espaços contam.');
return static function () use ($length, $alphabet, $next): string {
$text = '';
for ($i = 0; $i < $length; $i++) $text .= $alphabet[$next(count($alphabet))];
return $text;
};
};
foreach ($values as $value) {
if (!is_string($value) || preg_match('//u', $value) !== 1 || strlen(iconv('UTF-8', 'UTF-16LE', $value)) / 2 > 100000) throw new InvalidArgumentException('Use texto Unicode válido de até 100 mil caracteres por campo.');
}
$kind = $choice('mode', ['Strings', 'Inteiros']);
$count = $integer('count', 1, 500);
$repeat = $yes('repeat');
$make = $factory($kind, $rng($values['seed']));
// Saturar a capacidade em 500 evita overflow: só precisamos comparar com count.
$capacity = $kind === 'Inteiros' ? (int)$values['max'] - (int)$values['min'] + 1 : 1;
if ($kind === 'Strings') for ($i = 0; $i < (int)$values['length'] && $capacity < 500; $i++) $capacity = min(500, $capacity * count($chars($values['alphabet'])));
if (!$repeat && $capacity < $count) throw new InvalidArgumentException('Quantidade maior que as combinações disponíveis sem repetição.');
$result = [];
$used = [];
for ($attempt = 0; $attempt < 200000; $attempt++) {
$value = $make();
$key = json_encode($value, JSON_THROW_ON_ERROR);
if ($repeat || !isset($used[$key])) { $result[] = $value; $used[$key] = true; }
if (count($result) === $count) return $output($result);
}
throw new InvalidArgumentException('Limite de tentativas sem repetição atingido. Reduza a quantidade ou amplie o domínio.');
}