Website Design United States, Website Design California, Website Designing United States, Website Designing California

islem v1.0 - C++

Anonymous

A simple program to find target number with using 6 (or any) numbers and (+,-,/,*) operators

Example:

Target = 673
Numbers = 3, 4, 6, 7, 9, 25

Solution:
25 - 9 = 16
7 * 6 = 42
4 - 3 = 1
42 * 16 = 672
672 + 1 = 673

/*
* Author: Mete Kart
*
* Program: To find target number with using 6 (or any) numbers and (+,-,/,*) operators
* (program is unoptimized)
*
* Example: Target = 673, Numbers = 3, 4, 6, 7, 9, 25
* Solution: 25 - 9 = 16; 7 * 6 = 42; 4 - 3 = 1; 42 * 16 = 672; 672 + 1 = 673
*
*/

#include <stdio.h>
#include <string.h>

#define NUMBER_OF_NUMBERS 6

int sol;

typedef struct combi_s {
int len;
int num[NUMBER_OF_NUMBERS];
char buf[128];
} combi_t;

int op (combi_t *r, combi_t *c, int i, int j, int o)
{
int ret = 0;
char t[50];
int m1, m2;

if (c->num[i] > c->num[j]) {
m1 = c->num[i];
m2 = c->num[j];
} else {
m1 = c->num[j];
m2 = c->num[i];
}

switch (o) {
case 0:
strcpy (r->buf, c->buf);
r->num[0] = m1 + m2;
sprintf (t, "%d + %d = %d\n", m1, m2, r->num[0]);
strcat (r->buf, t);

ret = 1;
break;
case 1:
strcpy (r->buf, c->buf);
r->num[0] = m1 - m2;
sprintf (t, "%d - %d = %d\n", m1, m2, r->num[0]);
strcat (r->buf, t);

ret = 1;
break;
case 2:
strcpy (r->buf, c->buf);
r->num[0] = m1 * m2;
sprintf (t, "%d * %d = %d\n", m1, m2, r->num[0]);
strcat (r->buf, t);

ret = 1;
break;
case 3:
if (c->num[i] % c->num[j] == 0) {
strcpy (r->buf, c->buf);
r->num[0] = m1 / m2;
sprintf (t, "%d / %d = %d\n", m1, m2, r->num[0]);
strcat (r->buf, t);

ret = 1;
} else
ret = 0;
break;
default:
ret = 0;
break;
}

return ret;
}

void combi (combi_t *c, int target)
{
int i, j, k, o;

if (c->len <= 1) {
if (c->num[0] == target) {
sol++;
printf("***** Solution %02d *****\n", sol);
printf("%s", c->buf);
printf("***********************\n");
}
} else {
for (i = 0; i < c->len - 1; i++) {
for (j = i + 1; j < c->len; j++) {

if (c->num[i] == 0 || c->num[j] == 0 )
continue;

for (o = 0; o < 4; o++) {
int z = 1;
combi_t r;
r.len = c->len - 1;

if (op (&r, c, i, j, o) == 0)
continue;

for (k = 0; k < c->len; k++) {
if (k != i && k != j)
r.num[z++] = c->num[k];
}

combi (&r, target);
}
}
}
}
}

int main (int argc, char *argv[])
{
int i, target;

while (1) {
combi_t com;
sol = 0;
printf("Target: ");
scanf ("%d", &target);

for (i = 0; i < NUMBER_OF_NUMBERS; i++) {
printf("Number %d: ", i + 1);
scanf ("%d", &com.num[i]);
}

com.buf[0] = '\0';
com.len = NUMBER_OF_NUMBERS;

combi(&com, target);

printf("TOTAL %d solution found!\n", sol);
}

return 0;
}

WEB DESIGN INDIA
42 B Malviya Nagar , New Delhi-110017

Skype: manmeetsi
Email: support.webdesignindia@gmail.com
Tel: 91-011-40502005, 9810067295

 















 


© 2008-2009 dotnet4all.com