Friday, May 15, 2015

Show all combinations of numbers from 1 to 9 that add up to 100 by adding, subtracting and concatenating

So, this week I saw a blog post somewhere where the poster claimed that if you can't solve the mentioned 5 problems each in under and hour, you ain't no programmer, dev or software engineer. So, I went in and read the problems. 1-4 were easy but number 5 got me a worrying a little. And expected, I failed to solve that in under 1 hour yesterday. But today morning I solved that in less than 30 minutes. But whatever, I can't call myself a programmer anymore :(
Here's my approach though, using recursion:
Each i (from 1 through 9) has 2 different ways of connecting to the sequence.
1. Add itself to the closest sum (1 + 23 + 4 + .......)
2. Or concatenate itself (1 + 234 + ......)
So if we either add an i to the sequence that has reached it or we concatenate. Examples: .......8 + 9
.......89
Now the part before 8 has the same behavior with 8
.......7 + 8
.......78
This goes all the way back to 1 and 2
1 + 2
12
So, the program works something like this
Each branch ultimately ends on the leftmost call.
Code:
#include <cstdio>
#include <iostream>
#include <sstream>

using namespace std;

string i2s(int i) {
    stringstream op;
    op << i;
    return op.str();
}

int solveS(int i, int sum, string p) {

    if (i >= 10) {
        if (sum == 100) {
            cout << p + " = " << sum << endl;
        }
        return 0;
    }

    int iSum = 0;
    for (int j = i ; j<=9 ; j++) {
        iSum = iSum * 10 + j;
        if (i == 1) {
            solveS(j+1, iSum, i2s(iSum));
        } else {
            solveS(j+1, sum+iSum, p + " + " + i2s(iSum));
            solveS(j+1, sum-iSum, p + " - " + i2s(iSum));
        }
    }

    return 0;
}

int main() {

    //freopen("output.txt", "w+", stdout);

    solveS(1, 0, "");

    return 0;
}


No comments:

Post a Comment

Post your comment here. If you want to say something about programming problems, scripts, software etc, please try to be as descriptive as possible.

Connect Rapoo MT750S with Linux (Tested on Manjaro)

 I bought this obvious copy of MX Master 2S in hopes of having the device switching functionality along with a lightweight body because I ha...