2D数组随机交换项

huangapple go评论75阅读模式
英文:

2D Array item swap randomly

问题

我有一个枚举:

public enum Player
{
   X, O, NOBODY
}

我有一个用随机玩家项填充的数组:

Player [size][size] p;

示例矩阵:

[ X, NOBODY, NOBODY ]
[ NOBODY, O, O ]
[ X, X, NOBODY ]

我想随机将X或O元素与NOBODY元素交换,应该如何实现?

示例:

[ NOBODY, NOBODY, NOBODY ]
[ NOBODY, O, O ]
[ X, X, X ]
英文:

I have an enum:

public enum Player
{
   X, O, NOBODY
}

And I have this array filled with player items randomly:

Player [size][size] p;

Example matrix:

[ X, NOBODY, NOBODY ]
[ NOBODY, O, O ]
[ X, X, NOBODY ] 

I would like to swap an X or O element with a NOBODY element randomly, how can I do that?

Example:

[ NOBODY, NOBODY, NOBODY ]
[ NOBODY, O, O ]
[ X, X, X ] 








</details>


# 答案1
**得分**: 1

一个直接的方法是选择一个随机的X/O单元,以及一个随机的NOBODY单元,然后交换它们的值:

```java
// 类内的方法,包含数组
public void 交换值() {
    Random rand = new Random();
    int xoPos;
    int nobodyPos;

    do {
        xoPos = rand.nextInt(size*size);
        Player p = p[xoPos / size][xoPos % size];
    } while (Player.NOBODY.equals(p));

    do {
        nobodyPos = rand.nextInt(size*size);
        Player p = p[nobodyPos / size][nobodyPos % size];
    } while (!Player.NOBODY.equals(p));

    p[nobodyPos / size][nobodyPos % size] = p[xoPos / size][xoPos % size];
    p[xoPos / size][xoPos % size] = Player.NOBODY;
}

这里的策略是生成一个介于0和二维棋盘单元格总数减一之间的随机数。然后,我们使用整数除法和取模来确定这个单个值对应的二维坐标。

英文:

One straightforward approach would be to select a random X/O cell as well as a random NOBODY cell, and then swap their values:

// method inside class containing the array
public void swapValues() {
    Random rand = new Random();
    int xoPos;
    int nobodyPos;

    do {
        xoPos = rand.nextInt(size*size);
        Player p = p[xoPos / size][xoPos % size];
    } while (Player.NOBODY.equals(p));

    do {
        nobodyPos = rand.nextInt(size*size);
        Player p = p[nobodyPos / size][nobodyPos % size];
    } while (!Player.NOBODY.equals(p));

    p[nobodyPos / size][nobodyPos % size] = p[xoPos / size][xoPos % size];
    p[xoPos / size][xoPos % size] = Player.NOBODY;
}

The strategy here is to generate a single random number between 0 and one minus the total number of cells in the 2D board. Then, we use integer division and modulus to figure out to what 2D coordinates that single value corresponds.

huangapple
  • 本文由 发表于 2020年10月16日 12:21:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/64382880.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定