|
Programming Problems:
Arranging digits
|
|||||||||
|
Problem: Solution: Analysis of the problem: The problem may seem very easy at first sight. But we will understand that it is not so. Actually solving this problem become very difficult for some one who has not seen problems pertaining to this specific class. Whenever we try to find a solution for the problem using paper and pencil, we may only find some simple solutions, and may not be able to get all the solutions. Also after finding a number of solutions, we may not know whether any other solution exits or not. Thus in essence, it is difficult to list all the solutions of the problem using pencil and paper. So we will use a computer to solve the problem. We have to write a program for this. Solution: Let us illustrate the basic problem statement in a more computer friendly way: _1 _ 2_ 3 _4 _5 _6 _7 _8 _9 We must either fill the blanks above with +/- or we must remove the blanks such that the digits on either side of the blank combine to form a single number. E.g.: _ 1 _ 2_ 3 _4 _5 _6 _7 _8 _9 becomes 123 - 4 + 5 + 67 - 89 Then we must evaluate the resulting expression to find whether it is equal to 100. If it equals 100, we may output the expression. Now, there are three possible ways we may deal with a blank: (1) Remove the blank (2) Put a + sign in the blank (3) Put a - sign in the blank
The C source code for getting all the solutions of the problem is given below: #include<stdio.h>
#include<conio.h>
// This function is used to generate number between 0 and 2
int findnumber(int i,int j)
{
int k;
int n;
for(k = 0; k < j; k++)
{
n = i % 3;
i = i / 3;
}
return n;
}
void main()
{
int i, j, k, current, result, operation;
clrscr();
for(i = 0; i < 19683; i++)
{
if(i%3 == 0)
continue;
current = 0;
result = 0;
for(j = 1; j < 10; j++)
{
k = findnumber(i,j);
if(k==0)
{
current = current * 10 + j;
}
else
{
result = result + (operation == 1 ? current : -current);
current = j;
operation = k;
}
}
result = result + (operation == 1 ? current : -current);
if(result == 100)
{
for(j = 1; j < 10; j++)
{
k = findnumber(i,j);
if(k==0)
printf("%d",j);
else
printf("%c%d",k==1?'+':'-',j);
}
printf("\n");
}
}
getch();
}
Author: Niyaz PK
|
|||||||||
All Rights Reserved © 2007 Hoozi
