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 visualizeLogicAlgorithm(v) {
const algorithm = lgChoice(v, 'algorithm', ['Bubble sort', 'Insertion sort', 'Busca linear', 'Busca binária']);
let data;
try {
data = JSON.parse(v.input);
}
catch {
throw new Error('Informe um array JSON válido de inteiros.');
}
if (!Array.isArray(data) || data.length < 1 || data.length > 40 || data.some(n => !Number.isSafeInteger(n) || n < -1000000 || n > 1000000))
throw new Error('Use um array de 1–40 inteiros entre −1 milhão e 1 milhão.');
const values = [...data], steps = [];
let comparisons = 0, movements = 0, found = -1;
function step(action, indices = []) { if (steps.length >= 5000)
throw new Error('Limite de 5.000 passos.'); steps.push({ action, indices, values: [...values], comparisons, movements }); }
step('Estado inicial');
if (algorithm === 'Bubble sort') {
for (let end = values.length - 1; end > 0; end--) {
let changed = false;
for (let i = 0; i < end; i++) {
comparisons++;
step('Comparar', [i, i + 1]);
if (values[i] > values[i + 1]) {
[values[i], values[i + 1]] = [values[i + 1], values[i]];
movements++;
changed = true;
step('Trocar', [i, i + 1]);
}
}
if (!changed)
break;
}
}
else if (algorithm === 'Insertion sort') {
for (let i = 1; i < values.length; i++) {
const key = values[i];
let j = i - 1;
while (j >= 0) {
comparisons++;
step('Comparar com chave ' + key, [j, i]);
if (values[j] <= key)
break;
values[j + 1] = values[j];
movements++;
step('Deslocar', [j, j + 1]);
j--;
}
values[j + 1] = key;
movements++;
step('Inserir chave', [j + 1]);
}
}
else {
const target = lgInt(v, 'target', -1000000, 1000000);
if (algorithm === 'Busca linear') {
for (let i = 0; i < values.length; i++) {
comparisons++;
step('Comparar com alvo ' + target, [i]);
if (values[i] === target) {
found = i;
break;
}
}
}
else {
if (values.some((n, i) => i > 0 && n < values[i - 1]))
throw new Error('Busca binária exige array em ordem crescente. A entrada não foi ordenada.');
let lo = 0, hi = values.length - 1;
while (lo <= hi) {
const mid = Math.floor((lo + hi) / 2);
comparisons++;
step(`Comparar com alvo ${target}; intervalo ${lo}…${hi}`, [mid]);
if (values[mid] === target) {
found = mid;
break;
}
if (values[mid] < target)
lo = mid + 1;
else
hi = mid - 1;
}
}
}
step(algorithm.startsWith('Busca') ? 'Busca concluída; índice ' + found : 'Ordenação concluída');
return { ...lgJson({ algorithm, result: algorithm.startsWith('Busca') ? found : values, comparisons, movements, steps }, true), steps };
}
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 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 visualizeLogicAlgorithm(values);
}
import json
import re
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'}
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')
algorithm = choice('algorithm', ['Bubble sort', 'Insertion sort', 'Busca linear', 'Busca binária'])
data = json.loads(values['input'])
if not isinstance(data, list) or not 1 <= len(data) <= 40 or any(type(n) not in (int, float) or not -1000000 <= n <= 1000000 or n != int(n) for n in data):
raise ValueError('Use um array de 1–40 inteiros entre −1 milhão e 1 milhão.')
data = [int(n) for n in data]
steps, comparisons, movements, found = [], 0, 0, -1
def step(action, indices=None):
if len(steps) >= 5000:
raise ValueError('Limite de 5.000 passos.')
steps.append({'action': action, 'indices': indices or [], 'values': data[:], 'comparisons': comparisons, 'movements': movements})
step('Estado inicial')
if algorithm == 'Bubble sort':
for end in range(len(data) - 1, 0, -1):
changed = False
for i in range(end):
comparisons += 1
step('Comparar', [i, i + 1])
if data[i] > data[i + 1]:
data[i], data[i + 1] = data[i + 1], data[i]
movements += 1
changed = True
step('Trocar', [i, i + 1])
if not changed:
break
elif algorithm == 'Insertion sort':
for i in range(1, len(data)):
key, j = data[i], i - 1
while j >= 0:
comparisons += 1
step('Comparar com chave ' + str(key), [j, i])
if data[j] <= key:
break
data[j + 1] = data[j]
movements += 1
step('Deslocar', [j, j + 1])
j -= 1
data[j + 1] = key
movements += 1
step('Inserir chave', [j + 1])
else:
target = integer('target', -1000000, 1000000)
if algorithm == 'Busca linear':
for i, n in enumerate(data):
comparisons += 1
step('Comparar com alvo ' + str(target), [i])
if n == target:
found = i
break
else:
if any(data[i] < data[i - 1] for i in range(1, len(data))):
raise ValueError('Busca binária exige array em ordem crescente. A entrada não foi ordenada.')
lo, hi = 0, len(data) - 1
while lo <= hi:
mid = (lo + hi) // 2
comparisons += 1
step(f'Comparar com alvo {target}; intervalo {lo}…{hi}', [mid])
if data[mid] == target:
found = mid
break
if data[mid] < target:
lo = mid + 1
else:
hi = mid - 1
step('Busca concluída; índice ' + str(found) if algorithm.startswith('Busca') else 'Ordenação concluída')
result = output({'algorithm': algorithm, 'result': found if algorithm.startswith('Busca') else data, 'comparisons': comparisons, 'movements': movements, 'steps': steps}, True)
result['steps'] = steps
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];
};
$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'];
};
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.');
}
$algorithm = $choice('algorithm', ['Bubble sort', 'Insertion sort', 'Busca linear', 'Busca binária']);
$data = json_decode($values['input'], false, 512, JSON_THROW_ON_ERROR);
if (!is_array($data) || count($data) < 1 || count($data) > 40) throw new InvalidArgumentException('Use um array de 1–40 inteiros entre −1 milhão e 1 milhão.');
foreach ($data as &$number) {
if ((!is_int($number) && !is_float($number)) || !is_finite((float)$number) || floor($number) != $number || $number < -1000000 || $number > 1000000) throw new InvalidArgumentException('Use um array de 1–40 inteiros entre −1 milhão e 1 milhão.');
$number = (int)$number;
}
unset($number);
$steps = [];
$comparisons = $movements = 0;
$found = -1;
$step = static function (string $action, array $indices = []) use (&$steps, &$data, &$comparisons, &$movements): void {
if (count($steps) >= 5000) throw new InvalidArgumentException('Limite de 5.000 passos.');
$steps[] = ['action' => $action, 'indices' => $indices, 'values' => $data, 'comparisons' => $comparisons, 'movements' => $movements];
};
$step('Estado inicial');
if ($algorithm === 'Bubble sort') {
for ($end = count($data) - 1; $end > 0; $end--) {
$changed = false;
for ($i = 0; $i < $end; $i++) {
$comparisons++;
$step('Comparar', [$i, $i + 1]);
if ($data[$i] > $data[$i + 1]) { [$data[$i], $data[$i + 1]] = [$data[$i + 1], $data[$i]]; $movements++; $changed = true; $step('Trocar', [$i, $i + 1]); }
}
if (!$changed) break;
}
} elseif ($algorithm === 'Insertion sort') {
for ($i = 1; $i < count($data); $i++) {
$key = $data[$i];
$j = $i - 1;
while ($j >= 0) {
$comparisons++;
$step('Comparar com chave ' . $key, [$j, $i]);
if ($data[$j] <= $key) break;
$data[$j + 1] = $data[$j]; $movements++; $step('Deslocar', [$j, $j + 1]); $j--;
}
$data[$j + 1] = $key; $movements++; $step('Inserir chave', [$j + 1]);
}
} else {
$target = $integer('target', -1000000, 1000000);
if ($algorithm === 'Busca linear') {
foreach ($data as $i => $n) { $comparisons++; $step('Comparar com alvo ' . $target, [$i]); if ($n === $target) { $found = $i; break; } }
} else {
for ($i = 1; $i < count($data); $i++) if ($data[$i] < $data[$i - 1]) throw new InvalidArgumentException('Busca binária exige array em ordem crescente. A entrada não foi ordenada.');
$lo = 0; $hi = count($data) - 1;
while ($lo <= $hi) {
$mid = intdiv($lo + $hi, 2); $comparisons++;
$step("Comparar com alvo $target; intervalo {$lo}…{$hi}", [$mid]);
if ($data[$mid] === $target) { $found = $mid; break; }
if ($data[$mid] < $target) $lo = $mid + 1; else $hi = $mid - 1;
}
}
}
$search = str_starts_with($algorithm, 'Busca');
$step($search ? 'Busca concluída; índice ' . $found : 'Ordenação concluída');
return [...$output(['algorithm' => $algorithm, 'result' => $search ? $found : $data, 'comparisons' => $comparisons, 'movements' => $movements, 'steps' => $steps], true), 'steps' => $steps];
}