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 generateLogicStructures(v) {
const shape = lgChoice(v, 'shape', ['Array', 'Matriz', 'Árvore']), type = lgChoice(v, 'type', ['Strings', 'Inteiros', 'Booleanos']), next = lgRng(v.seed), make = lgValueFactory(v, type, next);
if (shape === 'Array')
return lgJson(Array.from({ length: lgInt(v, 'size', 1, 500) }, make));
if (shape === 'Matriz') {
const rows = lgInt(v, 'rows', 1, 50), columns = lgInt(v, 'columns', 1, 50);
return lgJson(Array.from({ length: rows }, () => Array.from({ length: columns }, make)));
}
const depth = lgInt(v, 'depth', 0, 6), branching = lgInt(v, 'branching', 1, 5);
let total = 0, level = 1;
for (let d = 0; d <= depth; d++) {
total += level;
level *= branching;
}
if (total > 1000)
throw new Error('Árvore excede 1.000 nós. Reduza profundidade ou filhos.');
let id = 0;
function node(d) { return { id: id++, value: make(), children: d < depth ? Array.from({ length: branching }, () => node(d + 1)) : [] }; }
return lgJson(node(0));
}
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 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 generateLogicStructures(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 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')
shape = choice('shape', ['Array', 'Matriz', 'Árvore'])
make = factory(choice('type', ['Inteiros', 'Strings', 'Booleanos']), rng(values['seed']))
if shape == 'Array':
return output([make() for _ in range(integer('size', 1, 500))])
if shape == 'Matriz':
rows, columns = integer('rows', 1, 50), integer('columns', 1, 50)
return output([[make() for _ in range(columns)] for _ in range(rows)])
depth, branching = integer('depth', 0, 6), integer('branching', 1, 5)
if sum(branching ** d for d in range(depth + 1)) > 1000:
raise ValueError('Árvore excede 1.000 nós. Reduza profundidade ou filhos.')
identifier = 0
def node(d):
nonlocal identifier
own = identifier
identifier += 1
value = make()
return {'id': own, 'value': value, 'children': [node(d + 1) for _ in range(branching)] if d < depth else []}
return output(node(0))
<?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];
};
$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.');
}
$shape = $choice('shape', ['Array', 'Matriz', 'Árvore']);
$make = $factory($choice('type', ['Inteiros', 'Strings', 'Booleanos']), $rng($values['seed']));
if ($shape === 'Array') {
$size = $integer('size', 1, 500);
$result = [];
for ($i = 0; $i < $size; $i++) $result[] = $make();
return $output($result);
}
if ($shape === 'Matriz') {
$rows = $integer('rows', 1, 50);
$columns = $integer('columns', 1, 50);
$result = [];
for ($i = 0; $i < $rows; $i++) { $row = []; for ($j = 0; $j < $columns; $j++) $row[] = $make(); $result[] = $row; }
return $output($result);
}
$depth = $integer('depth', 0, 6);
$branching = $integer('branching', 1, 5);
$total = 0;
for ($d = 0; $d <= $depth; $d++) $total += $branching ** $d;
if ($total > 1000) throw new InvalidArgumentException('Árvore excede 1.000 nós. Reduza profundidade ou filhos.');
$identifier = 0;
$node = static function (int $d) use (&$node, &$identifier, $depth, $branching, $make): array {
$own = $identifier++;
$value = $make();
$children = [];
if ($d < $depth) for ($i = 0; $i < $branching; $i++) $children[] = $node($d + 1);
return ['id' => $own, 'value' => $value, 'children' => $children];
};
return $output($node(0));
}