(C)获取矩阵中一行的3个最小元素,并随机选择一个 [英] (C) Getting the 3 minimum elements of an row in a matrix, and choose one randomly

查看:97
本文介绍了(C)获取矩阵中一行的3个最小元素,并随机选择一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个8x8的矩阵,在选择了我想要的行之后,我想要获得它的三个最小元素,并从这三个元素中随机选择一个.问题是我不知道该如何处理这三个要素.我只知道如何获取最小元素,那就是下面的代码.

I've a 8x8 matrix, and after choosing the row I desire, I want to get the three minimum elements of it, and choose one of this three randomly. The thing is that I'dont know how to handle those three elements. I just know how to get the minimum element, that is the 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; // the row I want to analyze
int index;
int min=0;

for (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 I want to have is, if the 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,
};

然后选择第3行:

0, 3, 1, 5, 1, 2, 3, 4,

算法必须选择

0, 1, 1

然后从这三个中随机选择一个.

And choose randomly one of these three.

有人可以给我关于如何做的任何想法吗?从今天早上开始,我就一直坚持这一点.谢谢

Can someone give me any ideas of how can I do it? I'm stuck with this since early this 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 too big.
}

int main(void){
    srand(time(NULL));

    int myrow = 3; // the row I want to 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) );


}

这篇关于(C)获取矩阵中一行的3个最小元素,并随机选择一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆