Follow

Good morning and here comes the latest challenge.

git.qoto.org/Absinthe/onetonin

The numbers 1 2 3 4 5 6 7 8 9 can have either the operator "+" or "-" placed between them.
As well, if no operator is placed, then the adjoining numbers go together such as 1 2 would
become "12" or 1 2 3 would become "123" and so forth.

The goal is to find the combinations that would make the line calculate up to 100 exactly.

Here is an example: 12 + 3 - 4 + 5 + 67 + 8 + 9 = 100

Would like maybe something other than eval().

Octave solution: print_combos(1:9, 100) 

function num = print_combos(arr, tgt)
num = 0;
ops = zeros(numel(arr) - 1, 1);
for i = int32(0:(3 ^ numel(ops)))
for j = 1:numel(ops)
ops(j) = mod(i, 3);
i = floor(i / 3); end;
if eval_array(arr, ops) == tgt
for j = 1:numel(ops) fprintf("%d%s", arr(j), decode_op(ops(j))); end;
fprintf("%d = %d\n", arr(end), tgt);
num++; end; end; end

function res = eval_array(arr, ops)
i = 1;
while i <= numel(ops)
if ops(i) == 0
arr = [arr(1:(i - 1)) 10 * arr(i) + arr(i + 1) arr((i + 2): end)];
ops = ops([1:(i - 1) (i + 1):end]);
else i++; end; end;
res = arr(1);
for i = 1:numel(ops)
res = apply_op(res, arr(i + 1), ops(i)); end; end

function res = apply_op(lar, rar, idx)
if idx == 1 res = lar + rar;
elseif idx == 2 res = lar - rar; end; end

function sym = decode_op(num)
if num == 1 sym = " + ";
elseif num == 2 sym = " - ";
else sym = ""; end; end;

Sign in to participate in the conversation
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.