function result = magic_trick(input_string)
% 将输入字符串转换为字符数组
elements = char(input_string);
% 随机打乱顺序
permutation = elements;
permutation = permutation(randperm(length(permutation)));
fprintf('初始排列: %s\n', permutation);
% 定义通用交换函数
function perm = swap(perm, index, direction)
if strcmp(direction, 'left') && index > 1
perm([index-1, index]) = perm([index, index-1]);
elseif strcmp(direction, 'right') && index < length(perm)
perm([index+1, index]) = perm([index, index+1]);
end
end
% 执行动作
for i = 1:length(permutation)
if permutation(i) == 'A'
permutation = swap(permutation, i, 'left');
elseif permutation(i) == 'B'
permutation = swap(permutation, i, 'right');
elseif permutation(i) == 'C'
permutation = swap(permutation, i, 'left');
end
fprintf('执行动作后排列: %s\n', permutation);
end
% 检查最右边的元素是否为B
right_check = permutation(end) == 'B';
if right_check
result = true;
fprintf('成功!最右边的元素是B。\n');
else
result = false;
fprintf('失败!最右边的元素不是B。\n');
end
end
% main_script.m
result = magic_trick("ABC");
fprintf('最终结果: %d\n', result);
%这个是magic_trick.m代码
% main_script.m
% 定义测试次数
num_tests = 10000;
success_count = 0;
for i = 1:num_tests
result = magic_trick("ABC");
if result
success_count = success_count + 1;
end
end
fprintf('经过 %d 次测试,成功 %d 次。\n', num_tests, success_count);
fprintf('成功率: %.2f%%\n', (success_count / num_tests) * 100);