Tuesday, November 08, 2005

counting

Counting and arranging in the highest number of words available

 

--------------------code1-----------------------------

#include <stdio.h>

 

#define LETTERS "RBWWBBRWWRRWRBW"

 

void RWB_sort(char *array, size_t n);

 

int main(void)

{

    char array[] = LETTERS;

   

    puts(array);

    RWB_sort(array, sizeof array - 1);

    puts(array);

    return 0;

}

 

void RWB_sort(char *array, size_t n)

{

    size_t count[3] = {0};

 

    while (n-- != 0) {

        ++count[(array[n] == 'W') + 2 * (array[n] == 'B')];       

    }

    while (count[0]-- != 0) {

        array[++n] = 'R';

    }   

    while (count[1]-- != 0) {

        array[++n] = 'W';

    }

    while (count[2]-- != 0) {

        array[++n] = 'B';

    }

}

-----------------------------EOF----------------------------------------------

 

----------------------------code 2--------------------------------------------

#include <stdio.h>

#include <stdlib.h>

 

#define LETTERS "RBWWBBRWWRRWRBW"

 

int compar(const void *arg1, const void *arg2);

 

int main(void)

{

    char array[] = LETTERS;

   

    puts(array);

    qsort(array, sizeof array - 1, sizeof *array, compar);

    puts(array);

    return 0;

}

 

int compar(const void *arg1, const void *arg2)

{

    int one = (*(char *)arg1 == 'W') + 2 * (*(char *)arg1 == 'B');

    int two = (*(char *)arg2 == 'W') + 2 * (*(char *)arg2 == 'B');

 

    return two > one ? -1 : two != one;

}

---------------------------------EOF----------------------------------------------

 

 

Pradyut
http://pradyut.tk
http://spaces.msn.com/members/oop-edge/
http://groups-beta.google.com/group/oop_programming
India

 

No comments: