algorithm - 如何对数字数组进行排序以形成分散的数字?

标签 algorithm sorting math

<分区>

有一个由数字组成的数组。有些数字重复 2 到 6 次。我怎样才能分散如此重复的数字不能站在一起的数字? 每个内部数组最多可以有 4 个数字

[
  [54, 23, 23, 23],
  [12, 12, 66, 66],
  [66, 66, 08, 43],
  [43, 43, 99, 00],
  [32, 54, 27, 73],
  [93, 51, 71, 39]
]

最佳答案

好的。解决这个问题花了很长时间。

这是一个方法。虽然这个问题可能有多种技术,但我认为这个解决方案很容易理解。

  1. 将所有元素排序到另一个数组中。
  2. 定义 r = 0, c = 0。
  3. 从数组中选取每个元素,然后尝试将其放入矩阵中。如果不可能,则尝试下一个位置。

    int n = matrix.size();
    int m = matrix[0].size();
    
    vector<int> arr;
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++) {
            arr.push_back(matrix[i][j]);
        }
    }
    sort(arr.begin(), arr.end());
    int dr[] = {-1, 0, 1, 0}; /// 4 sides
    int dc[] = {0, 1, 0, -1}; /// 4 sides
    int r = 0, c = 0;
    int new_matrix[n][m];
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++)
            new_matrix[i][j] = -1;
    }
    bool vis[n][m] = {false};
    for(int k = 0; k < n*m; ) {
        int cur_num = arr[k];
        bool check = false;
        if(!vis[r][c]) {
            for(int p = 0; p < 4; p++) {
                int adjr = r + dr[p];
                int adjc = c + dc[p];
                if(adjr < 0 || adjr >= n || adjc < 0 || adjc >= m) continue;
                if(new_matrix[adjr][adjc] == cur_num) check = true;
            }
            if(check == false) {
                new_matrix[r][c] = cur_num;
                vis[r][c] = true;
                k++;
            }
        }
        c++;
        if(c >= m) r++, c = c % m;
        if(r >= n) r = r % n;
    }
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++) {
            cout<<new_matrix[i][j]<<" ";
        }
        cout<<endl;
    }
    

编码愉快!!!

关于algorithm - 如何对数字数组进行排序以形成分散的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57684118/

相关文章:

python - 计算自最后一个头以来的尾数

math - 如何从golang中的数组中获取偏度值

javascript - 试图计算圆上两点之间的 Angular ?

java - 反转操作

python - 在按下的每个键上实现自动建议

algorithm - 为什么我们要努力保持树木平衡

MATLAB 中与算法无关的超参数网格搜索

c - 在C中对多维数组进行排序

c++ - 是否可以循环遍历文件中的一些数字并检查它们是否已排序,而不需要将它们读入 vector 然后检查 vector

algorithm - 具有有序节点的树的搜索成本