A solution for Project Two
Below is the listing for a possible solution to the project.
/* MCS 275 Project Two: Scrabble */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int *match_positions (char s1[], char s2[]);
/* maches the positions in s1 with s2 as follows,
for pos = match_positions(s1,s2) :
if s1[i] == s2[j], then pos[i] = j (first occurrence)
otherwise if s1[i] does not occur in s2[j], pos[i] = -1;
returns the number of positions that match. */
void cross_words (char s1[], char s2[], int pos[]);
/* writes the words s1 and s2 so that they cross */
int main(int argc, char *argv[])
{
int *pos;
if (argc > 2)
{
pos = match_positions(argv[1],argv[2]);
cross_words(argv[1],argv[2],pos);
}
else
{
printf("We need two words to scrabble.\n");
printf("Please call again.\n");
}
}
int *match_positions (char s1[], char s2[])
{
int i,j;
int len=strlen(s1);
int *pos;
pos = (int*)calloc(len,sizeof(int));
for (i=0; i < len; i++) /* scan string s1 */
{
pos[i]=-1;
for (j=0; s2[j] != '\0' ; j++) /* search for match in s2 */
if (s1[i]==s2[j])
{
pos[i]=j; break; /* need first match, so break out */
}
}
return pos;
}
void cross_words (char s1[], char s2[], int pos[])
{
int lens1 = strlen(s1);
int lens2 = strlen(s2);
int i,j,row;
int minrow = 2*lens2-2; /* minimal row in display */
int maxrow = 0; /* maximal row in display */
char display[2*lens2-1][lens1];
for (i=0; i < 2*lens2-1; i++) /* initialize display */
for (j=0; j= 0; i--)
display[row--][j] = s2[i];
if (row+1 < minrow) minrow = row+1;
row = lens2;
for (i=pos[j]+1; s2[i] != '\0'; i++)
display[row++][j] = s2[i];
if (row-1 > maxrow) maxrow = row-1;
}
if (minrow <= maxrow)
{
printf("Crossing \"%s\" with \"%s\" :\n",s1,s2);
for (i=minrow; i < maxrow+1; i++) /* print the display */
{
for (j=0; j < lens1; j++)
putchar(display[i][j]);
printf("\n");
}
}
else
printf("\"%s\" does not cross with \"%s\".\n",s1,s2);
}