At todays C++ meetup I was told a programming quiz:

Given the digits 1-9 (in that order), you can combine them with either '+', '-' or nothing.
Now find all of these mathematical terms, that evaluate to 100.

You can use any programming language and library you like and you have 1 hour to complete the task.

At first I came up with a solution in JavaScript.
time spent: 22min
execution time: ~170ms
loc: 21

Expressions that evaluate to 100 

123+45-67+8-9
123+4-5+67-89
123-45-67+89
123-4-5-6-7+8-9
12+3+4+5-6-7+89
12+3-4+5+67+8+9
12-3-4+5-6+7+89
1+23-4+56+7+8+9
1+23-4+5+6+78-9
1+2+34-5+67-8+9
1+2+3-4+5+6+78+9

Then I came up with a solution in that took me ~5 minutes to write but with an execution time of 20s.

Follow

But #bash can also do it in 46ms 

#/usr/bin/env bash
for string in 1{,+,-}2{,+,-}3{,+,-}4{,+,-}5{,+,-}6{,+,-}7{,+,-}8{,+,-}9; do
result=$(($string))
if [[ $result == 100 ]]; then
echo $string
fi
done

Sign in to participate in the conversation
mastodon.cloud

Everyone is welcome as long as you follow our code of conduct! Thank you. Mastodon.cloud is maintained by Sujitech, LLC.