Code:
/*
Created By: TJRAK
Title: Flatten
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
void movechips(int [], int, int);
void main()
{
FILE *indt;
int chips[10];
char getdata[20];
char *tokenptr;
int size,i =0,total =0,prpile;
if ( (indt = fopen("flat.inp", "r"))==NULL)
// if ( (indt = fopen("flat1.inp", "r"))==NULL)
printf("Could not open input file");
else {
fscanf(indt, "%d", &size);
while(!feof(indt)) {
fgets(getdata, 20, indt);
}//end while
fclose (indt);
tokenptr = strtok(getdata, " ");
while (tokenptr!=NULL) {
chips[i] = atoi(tokenptr);
tokenptr = strtok(NULL, " ");
i++;
} //end while loop
for(i=0; i < size; i++)
total+=chips[i];
prpile = total/size;
movechips(chips, size, prpile);
}//end else not file open error
}
//_^__^__^__^__^__^__^__^__^__^__^__^__^__^__^__^__^__^__^__^__^__^__^__^__^__^_
//______________________________________________________________________________
void movechips(int a[], int b, int pp)
{
int key, success,i, temp[10], d;
int count =0, pos = b, swap = 0, control = 0;
FILE *indt;
if ( (indt = fopen("flat.out", "w"))==NULL)
printf("Could not open output file");
else{
fseek(indt, 1, SEEK_SET);
do{
for(i = control; i < b; i++){
success = 0;
key = (a[i]/pp)*2; //determine the amount of chips to move
if(i == 0) //check if current position is first pile
if(a[i] >= pp) //check to see if more chips than allowed is on the pile
{
a[i] -= key; //take off pile
a[i+1]+= key; //add to pile on right
if(swap%2 == 0)
fprintf(indt, "\n%d %1d", i+1, key);
else
{
d = (b - (b-(i+1)));
fprintf(indt, "\n%d %1d", d, key);
}
count++;
}
if(i == (b-1)) //check if your at the last pile
if(a[i] >= pp) //check to see if more chips than allowed is on the pile
{
a[i] -= key; //take off pile
a[i-1]+= key; //add to pile on left
if(swap%2 == 0)
fprintf(indt, "\n%d %1d", i+1, key);
else
{
d = (b - (b-(i+1)));
fprintf(indt, "\n%d %1d", d, key);
}
count++;
}
if (i!=0 && i!= (b-1))
if(a[i] >= pp)
{
if(a[i]%pp == 0 && control == 1)
{
a[i]-= key;
a[i-1] += key/2;
a[i+1] += key/2;
if(swap%2 == 0)
fprintf(indt, "\n%d %1d", i+1, key/2);
else
{
d = (b - (b-(i+1)));
fprintf(indt, "\n%d %1d", d, key/2);
}
}
else
{
a[i]-= key*2;
a[i-1] += key;
a[i+1] += key;
if(swap%2 == 0)
fprintf(indt, "\n%d %1d", i+1, key);
else
{
d = (b - (b-(i+1)));
fprintf(indt, "\n%d %1d", d, key);
}
}
count ++;
}
for(int c = 0; c < b; c++)
if (a[c] == pp)
success++;
if (success == b)
{
break;
}
}//end of for i = control
//==============================================================================
if (success < b)
{
for(i = 0; i < b; i++)
{
temp[pos-1] = a[i];
pos--;
}
a = temp;
control = 1;
swap++;
}
else
break;
//==============================================================================
} while (success < b);
fseek(indt, 0, SEEK_SET);
fprintf(indt, "%d\n", count);
fclose (indt);
}//end of else
}//end function