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 generateLogicGraph(v) {
const count = lgInt(v, 'nodes', 1, 30), directed = lgYes(v, 'directed'), weighted = lgYes(v, 'weighted'), edgeCount = lgInt(v, 'edges', 0, Math.min(200, count * (count - 1) / (directed ? 1 : 2))), format = lgChoice(v, 'format', ['Lista de adjacência', 'Matriz de adjacência']), next = lgRng(v.seed);
const min = weighted ? lgInt(v, 'min', -1000, 1000) : 1, max = weighted ? lgInt(v, 'max', min, 1000) : 1;
const nodes = Array.from({ length: count }, (_, i) => 'n' + i), pairs = [];
for (let a = 0; a < count; a++)
for (let b = directed ? 0 : a + 1; b < count; b++)
if (a !== b)
pairs.push([a, b]);
const edges = [], matrix = nodes.map(() => nodes.map(() => null)), list = Object.fromEntries(nodes.map(n => [n, []]));
for (let i = 0; i < edgeCount; i++) {
const j = i + next(pairs.length - i);
[pairs[i], pairs[j]] = [pairs[j], pairs[i]];
const [a, b] = pairs[i], weight = min + next(max - min + 1);
edges.push({ from: nodes[a], to: nodes[b], weight });
matrix[a][b] = weight;
list[nodes[a]].push({ to: nodes[b], weight });
if (!directed) {
matrix[b][a] = weight;
list[nodes[b]].push({ to: nodes[a], weight });
}
}
const graph = { nodes, edges, directed, weighted };
return { ...lgJson({ nodes, directed, weighted, ...(format === 'Matriz de adjacência' ? { matrix } : { adjacency: list }) }), graph };
}
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 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 generateLogicGraph(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
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')
count, directed, weighted = integer('nodes', 1, 30), yes('directed'), yes('weighted')
edge_count = integer('edges', 0, min(200, count * (count - 1) // (1 if directed else 2)))
form = choice('format', ['Lista de adjacência', 'Matriz de adjacência'])
next_int = rng(values['seed'])
low = integer('min', -1000, 1000) if weighted else 1
high = integer('max', low, 1000) if weighted else 1
nodes = ['n' + str(i) for i in range(count)]
pairs = [(a, b) for a in range(count) for b in range(0 if directed else a + 1, count) if a != b]
edges, matrix, adjacency = [], [[None] * count for _ in nodes], {n: [] for n in nodes}
for i in range(edge_count):
j = i + next_int(len(pairs) - i)
pairs[i], pairs[j] = pairs[j], pairs[i]
a, b = pairs[i]
weight = low + next_int(high - low + 1)
edges.append({'from': nodes[a], 'to': nodes[b], 'weight': weight})
matrix[a][b] = weight
adjacency[nodes[a]].append({'to': nodes[b], 'weight': weight})
if not directed:
matrix[b][a] = weight
adjacency[nodes[b]].append({'to': nodes[a], 'weight': weight})
result = output({'nodes': nodes, 'directed': directed, 'weighted': weighted, **({'matrix': matrix} if form == 'Matriz de adjacência' else {'adjacency': adjacency})})
result['graph'] = {'nodes': nodes, 'edges': edges, 'directed': directed, 'weighted': weighted}
return result
<?php
function executar(array $values): array {
// PHP 8.1+ de 64 bits, JSON, PCRE e iconv.
$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;
};
};
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.');
}
$count = $integer('nodes', 1, 30);
$directed = $yes('directed');
$weighted = $yes('weighted');
$edgeCount = $integer('edges', 0, min(200, intdiv($count * ($count - 1), $directed ? 1 : 2)));
$format = $choice('format', ['Lista de adjacência', 'Matriz de adjacência']);
$next = $rng($values['seed']);
$low = $weighted ? $integer('min', -1000, 1000) : 1;
$high = $weighted ? $integer('max', $low, 1000) : 1;
$nodes = array_map(static fn($i) => 'n' . $i, range(0, $count - 1));
$pairs = [];
for ($a = 0; $a < $count; $a++) for ($b = $directed ? 0 : $a + 1; $b < $count; $b++) if ($a !== $b) $pairs[] = [$a, $b];
$edges = [];
$matrix = array_fill(0, $count, array_fill(0, $count, null));
$adjacency = array_fill_keys($nodes, []);
for ($i = 0; $i < $edgeCount; $i++) {
$j = $i + $next(count($pairs) - $i);
[$pairs[$i], $pairs[$j]] = [$pairs[$j], $pairs[$i]];
[$a, $b] = $pairs[$i];
$weight = $low + $next($high - $low + 1);
$edges[] = ['from' => $nodes[$a], 'to' => $nodes[$b], 'weight' => $weight];
$matrix[$a][$b] = $weight; $adjacency[$nodes[$a]][] = ['to' => $nodes[$b], 'weight' => $weight];
if (!$directed) { $matrix[$b][$a] = $weight; $adjacency[$nodes[$b]][] = ['to' => $nodes[$a], 'weight' => $weight]; }
}
return [...$output(['nodes' => $nodes, 'directed' => $directed, 'weighted' => $weighted, ...($format === 'Matriz de adjacência' ? ['matrix' => $matrix] : ['adjacency' => $adjacency])]), 'graph' => ['nodes' => $nodes, 'edges' => $edges, 'directed' => $directed, 'weighted' => $weighted]];
}