【问题标题】:Arduino language shuffle order of an array数组的Arduino语言洗牌顺序
【发布时间】:2015-10-08 15:09:28
【问题描述】:

我正在使用 arduino ,但我似乎无法洗牌。 问题是使用arduino我不能使用arraylist所以帽子让我很难洗牌。

我真正想要的是从 0 到 52 随机排列的数字列表。所以每次我运行程序时,它都会以不同的顺序排列,数字从 0 到 52

这是我的代码:

const int MAXNUMMER = 52;
int numbers[52];



int temp = numbers[first];
//int numbers[first] = numbers[second];
//int numbers[second] = temp;




 void setup() {
 // put your setup code here, to run once:
 Serial.begin(9600);

     randomizeList();
 }

 void loop() {
 // put your main code here, to run repeatedly:

 }


 void randomizeList()
 {

 randomSeed(analogRead(A0));
 int r = random(53);


for(int i =0; i < MAXNUMMER; i++)
 {
  if(numbers[i] != r)

   {
  numbers[i] = r;

   Serial.println(numbers[i]);
   }

  }


  }

【问题讨论】:

  • 而你的问题是……究竟是什么?
  • 我真正想要的是一个从 0 到 52 的数字列表。所以每次我运行程序时,它都会以不同的顺序排列,数字从 0 到 52

标签: arrays for-loop random arduino shuffle


【解决方案1】:

我对此进行了测试,它应该可以工作。我只是在函数中使用了Serial.print,因为我想看到最后的所有内容;)

const int NUMOFNUMBERS = 52;
int numbers[NUMOFNUMBERS];

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

  randomizeList();
}

void loop() {
// put your main code here, to run repeatedly:

}

void randomizeList()
{
  unsigned char chosen[NUMOFNUMBERS];
  unsigned char index, i2;

  for (index = 0; index < NUMOFNUMBERS; index++)
    chosen[index] = 0;

  randomSeed(analogRead(A0));

  for (index = 0; index < NUMOFNUMBERS; index++)
  {
    int r = random(NUMOFNUMBERS-index);
    for (i2 = 0; i2 <= r; i2++)
    {
      r += chosen[i2];
    }
    chosen[r] = 1;
    numbers[index] = r;
    Serial.print(numbers[index]);
    Serial.print(" ");
  }
  Serial.println("");
}

我把变量的名字从MAXNUMMER改成了NUMOFNUMBERS,因为它是要生成的数字的个数(即最大数字是NUMOFNUMBERS - 1

这是一个运行此程序 6 次的示例,将 NUMOFNUMBERS 设置为 5:

4 1 3 2 0 
2 3 4 0 1 
1 0 2 4 3 
0 4 1 3 2 
3 0 4 2 1 
4 3 2 1 0 

编辑:如果您想多次随机化列表,我建议您将 randomSeed 函数从函数移动到 setup 函数。这样您就可以随时致电randomizeList

还有一件事:如果您希望使用值 [1,52] 而不是 [0,51] 的列表,您可以将 numbers[index] = r; 行编辑为 numbers[index] = r + 1;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 2010-09-08
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    相关资源
    最近更新 更多