(C) Getting the 3 minimum elements of an row in a matrix, and choose one randomly -
i've 8x8 matrix, , after choosing row desire, want 3 minimum elements of it, , choose 1 of 3 randomly. thing i'dont know how handle 3 elements. know how minimum element, following code.
int piezas[8][8] = { 0, 2, 2, 5, 3, 2, 1, 1, 0, 4, 5, 2, 4, 3, 0, 0, 0, 4, 2, 2, 1, 2, 3, 2, 0, 3, 1, 5, 1, 2, 3, 4, 2, 5, 6, 5, 3, 1, 2, 7, 8, 2, 0, 0, 0, 2, 1, 1, 1, 2, 2, 1, 1, 6, 3, 4, }; int myrow = 3; // row want analyze int index; int min=0; (index=0;index<8;index++) { printf("%d", piezas[myrow][index] ); if(piezas[myrow][index]<min) min=piezas[myrow][index]; printf("\t\t"); } printf("min: %d", min);
the output want have is, if initial matrix is:
int piezas[8][8] = { 0, 2, 2, 5, 3, 2, 1, 1, 0, 4, 5, 2, 4, 3, 0, 0, 0, 4, 2, 2, 1, 2, 3, 2, 0, 3, 1, 5, 1, 2, 3, 4, 2, 5, 6, 5, 3, 1, 2, 7, 8, 2, 0, 0, 0, 2, 1, 1, 1, 2, 2, 1, 1, 6, 3, 4, };
and choose row number 3:
0, 3, 1, 5, 1, 2, 3, 4,
the algorithm must choose
0, 1, 1
and choose randomly 1 of these three.
can give me ideas of how can it? i'm stuck since morning. thanks
#include <stdio.h> #include <stdlib.h> #include <time.h> #define size_row 8 #define n_min 3 int piezas[size_row][size_row] = { 0, 2, 2, 5, 3, 2, 1, 1, 0, 4, 5, 2, 4, 3, 0, 0, 0, 4, 2, 2, 1, 2, 3, 2, 0, 3, 1, 5, 1, 2, 3, 4, 2, 5, 6, 5, 3, 1, 2, 7, 8, 2, 0, 0, 0, 2, 1, 1, 1, 2, 2, 1, 1, 6, 3, 4, }; int sort(const void *x, const void *y) { return (*(int*)x - *(int*)y); } int* sort_array(int* row, int size_row){ int* output = (int*) calloc(size_row, sizeof(int) ); memcpy(output, row, size_row*sizeof(int) ); // copy array qsort (output, size_row, sizeof (int), sort); return output; } int random_pick(int* array, int size_row){ return array[ rand() % size_row ]; // possible buffer overflow if size_row big. } int main(void){ srand(time(null)); int myrow = 3; // row want analyze int* sorted_row = null; int i,j; sorted_row = sort_array(piezas[myrow],size_row ); printf("n mins : \n"); for(i=0;i<n_min;i++){ printf(" %d ", sorted_row[i] ); } printf("\n"); printf("random pick : %d \n", random_pick(sorted_row, n_min) ); }
Comments
Post a Comment