home *** CD-ROM | disk | FTP | other *** search
- /*
- Problem 01 - Mode Sort
-
- This problem is to sort an input string of N characters, N<1000000, based on
- the number of times a character occurs in the input. The most frequently
- occurring character should be sorted to the front of the string, followed by
- the next most frequently occurring character, etc. For characters occurring
- the same number of times, the character that occurs first in the input should
- be sorted to the front.
-
- Header specification
-
- pascal OSErr ModeSort( const FSSpec* infile, const FSSpec* outfile );
-
- Input specification
-
- The infile input file contains the characters. Input characters other than
- those printable low ascii characters c, 0x20<c<0x7f, must be ignored.
-
-
- Output specification
-
- The outfile must be created and then filled with the sorted characters. It's
- final length should be exactly the same as the count of characters in the
- allowed range (0x20<c<0x7f) (which may be shorter than the infile file length).
-
- Sample input
-
- abcdefghabbcccdddeee
- or
- 012345678911234567892123456789312345678941234567895123456789612345678971234567891
-
- Sample output
-
- ccccddddeeeebbbaafgh
- or
- 111111111122222222233333333344444444455555555566666666677777777788888888999999990
- */
-
- #include "Solution.h"
-
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
-
- // Fill in your solution and then submit this folder
-
- // Team Name: Mark Johns & Charlie M-T
-
- typedef struct
- {
- char value;
- long num;
- // long index;
- } La;
-
- pascal OSErr ModeSort( const FSSpec* infile, const FSSpec* outfile )
- {
- char *source;
- short f1, f2;
- short numDat = 0;
- long length, size, i, j, k;
- La *dat, swap;
-
- if(FSpOpenDF(infile, fsRdWrPerm, &f1)!=noErr)
- ExitToShell();
-
- FSpCreate(outfile, '????', '????', smSystemScript);
- if(FSpOpenDF(outfile, fsRdWrPerm, &f2)!=noErr)
- ExitToShell();
-
- GetEOF(f1, &length);
- // SetEOF(f2, length);
- source = malloc(length);
- for(i = 0; i < length; i++)
- source[i] = 0;
- FSRead(f1, &length, source);
-
- printf("%*s\n", length, source);
- dat = malloc(0);
- for(i=0;i<length;i++)
- {
- for(k = 0; k < numDat; k++)
- {
- if(dat[k].value == source[i])
- {
- dat[k].num++;
- break;
- }
- }
- if(k == numDat)
- {
- numDat++;
- dat = realloc(dat, sizeof(La) * numDat);
- dat[numDat - 1].value = source[i];
- dat[numDat - 1].num = 1;
- }
- }
- for(i = 0; i < numDat; i++)
- {
- for(j = 0; j < numDat; j++)
- {
- if(dat[i].num > dat[j].num)
- {
- swap = dat[i];
- dat[i] = dat[j];
- dat[j] = swap;
- }
- }
- }
- size = sizeof(char);
- for(i = 0; i < numDat; i++)
- {
- for(j = 0; j < dat[i].num; j++)
- {
- putchar(dat[i].value);
- FSWrite(f2, &size, &dat[i].value);
- }
- }
- putchar('\n');
- free(source);
- free(dat);
- return noErr;
- }