is there a way to randomly reshuffle an array, so the array can appear differently everytime?

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

is there a way to randomly reshuffle an array, so the array can appear differently everytime?

问题

var arr = [1, 2, 3, 4];
finalarr = [];
for (i = 0; i <= 5; i++) {
  arr.sort(function(a, b) {
    return 0.5 - Math.random();
  });
  finalarr.push(arr);
}
/*once it randomizes that first array, it keeps repeating it. i dont want 
that i want it to reshuffle the array everytime i run that loop*/
console.log(finalarr);

它只随机化数组一次然后重复使用它

英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var arr = [1, 2, 3, 4];
finalarr = [];
for (i = 0; i &lt;= 5; i++) {
  arr.sort(function(a, b) {
    return 0.5 - Math.random();
  });
  finalarr.push(arr);
}
/*once it randomizes that first array, it keeps repeating it. i dont want 
that i want it to reshuffle the array everytime i run that loop*/
console.log(finalarr);

<!-- end snippet -->

It randomizes the array only once and keeps repeating it

答案1

得分: 2

第二个演示是对Demo 1的修改,接受两个参数:

@Params: array [Array]...: 要洗牌的数组
        repeat [Number]..: 要返回的新随机数组的数量

@Return: 一个数组的数组(也称为“二维数组”)

正如Nick Parsons所提到的,您使用了对数组的引用,而且您的结果是一个完整的数组,其中您将其添加到一个空数组中(例如 [[4, 3, 2, 1]])。更实用的返回值应该只是一个具有与原始数组相同元素的随机顺序的数组([2, 4, 1, 3])。

以下演示:

  1. 使用最有效的方法对数组进行洗牌:Fisher-Yates算法

  2. 接受一个标准数组,并通过扩展运算符 [...array] 克隆它。

  3. shuffle()函数被调用三次,每次都返回一个具有随机顺序的新数组。

注意: 还有一个可选的实用函数,只是更好地显示控制台日志。这不是必需的。

Demo 1

let array = [1, 2, 3, 'A', 'B', 'C'];

const shuffle = ([...array]) => {
  let i = 0;
  let j = 0;
  let temp = null;

  for (i = array.length - 1; i > 0; i -= 1) {
    j = Math.floor(Math.random() * (i + 1));
    temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
  return array;
}

const log = data => console.log(JSON.stringify(data));

log(shuffle(array));
log(shuffle(array));
log(shuffle(array));

Demo 2

let array = [1, 2, 3, 'A', 'B', 'C'];

const shuffle = (array, repeat = 1) => {
  let result = [];
  for (let r = repeat; r > 0; r -= 1) {
    let clone = [...array];
    for (let i = clone.length - 1; i > 0; i -= 1) {
      let s = Math.floor(Math.random() * (i + 1));
      let temp = clone[i];
      clone[i] = clone[s];
      clone[s] = temp;
    }
    result.push(clone);
  }
  return result;
}

const log = data => console.log(JSON.stringify(data));

log(shuffle(array));
log(shuffle(array, 5));
// .flat() 在返回的数组上调用以提供单个数组
log(shuffle(array, 5).flat());
英文:

###Edit

The second demo is Demo 1 modified to accept two parameters:

@Params: array [Array]...: The array to shuffle
        repeat [Number]..: The number of new randomized arrays to be returned

@Return: An array of arrays (aka &quot;two-dimensional array&quot;) 

<hr>
As mentioned by Nick Parsons, you are using a reference to the array plus your result is a full array in which you are adding to an empty array (ex. [[4, 3, 2, 1]]) a more practical return would be just an array with the same elements as the original array but in a random order ([2, 4, 1, 3]).

The following demo:

  1. Uses the most effective way to shuffle an array: Fisher–Yates algorithm.

  2. Accepts a standard array and clones it by the spread operator [...array]

  3. The shuffle() function is called three separate times and returns a new array with a randomized order.

Note: There's an optional utility function that just displays console logs nicer. It is not a requirement.

###Demo 1
<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let array = [1, 2, 3, &#39;A&#39;, &#39;B&#39;, &#39;C&#39;];

const shuffle = ([...array]) =&gt; {
  let i = 0;
  let j = 0;
  let temp = null;

  for (i = array.length - 1; i &gt; 0; i -= 1) {
    j = Math.floor(Math.random() * (i + 1));
    temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
  return array;
}

const log = data =&gt; console.log(JSON.stringify(data));

log(shuffle(array));
log(shuffle(array));
log(shuffle(array));

<!-- end snippet -->

<hr>

###Demo 2

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let array = [1, 2, 3, &#39;A&#39;, &#39;B&#39;, &#39;C&#39;];

const shuffle = (array, repeat = 1) =&gt; {
  let result = [];
  for (let r = repeat; r &gt; 0; r -= 1) {
    let clone = [...array];
    for (let i = clone.length - 1; i &gt; 0; i -= 1) {
      let s = Math.floor(Math.random() * (i + 1));
      let temp = clone[i];
      clone[i] = clone
展开收缩
; clone
展开收缩
= temp; } result.push(clone); } return result; } const log = data =&gt; console.log(JSON.stringify(data)); log(shuffle(array)); log(shuffle(array, 5)); // .flat() is invoked on the return array to provide a single array log(shuffle(array, 5).flat());

<!-- end snippet -->

答案2

得分: 1

只需在推送之前取消引用arr即可。以下三种方法都可以使用。

var arr = [1, 2, 3, 4];
finalarr = [];
for (i = 0; i <= 5; i++) {
  arr.sort(function(a, b) {
    return 0.5 - Math.random();
  });
  finalarr.push(Object.assign({}, arr));
}
console.log(finalarr);
var arr = [1, 2, 3, 4];
finalarr = [];
for (i = 0; i <= 5; i++) {
  arr.sort(function(a, b) {
    return 0.5 - Math.random();
  });
  finalarr.push({...arr});
}
console.log(finalarr);
var arr = [1, 2, 3, 4];
finalarr = [];
for (i = 0; i <= 5; i++) {
  arr.sort(function(a, b) {
    return 0.5 - Math.random();
  });
  finalarr.push(JSON.parse(JSON.stringify(arr)));
}
console.log(finalarr);
英文:

You just need to dereference the arr before pushing. Any of following three would work.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var arr = [1, 2, 3, 4];
finalarr = [];
for (i = 0; i &lt;= 5; i++) {
  arr.sort(function(a, b) {
    return 0.5 - Math.random();
  });
  finalarr.push(Object.assign({},arr));
}
console.log(finalarr);

<!-- end snippet -->

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var arr = [1, 2, 3, 4];
finalarr = [];
for (i = 0; i &lt;= 5; i++) {
  arr.sort(function(a, b) {
    return 0.5 - Math.random();
  });
  finalarr.push({...arr});
}
console.log(finalarr);

<!-- end snippet -->

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var arr = [1, 2, 3, 4];
finalarr = [];
for (i = 0; i &lt;= 5; i++) {
  arr.sort(function(a, b) {
    return 0.5 - Math.random();
  });
  finalarr.push(JSON.parse(JSON.stringify(arr)));
}
console.log(finalarr);

<!-- end snippet -->

答案3

得分: 1

将数组文字附加到排序函数,并将结果推入最终数组。

let finalarr = []

for (i = 0; i <= 5; i++) {
  let arr = [1, 2, 3, 4].sort(function(a, b) {
    return 0.5 - Math.random()
  })
  finalarr.push(arr)
}

console.log(finalarr)
英文:

Attach an array literal to the sort function, and push the result to the final array.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let finalarr = []

for (i = 0; i &lt;= 5; i++) {
  let arr = [1, 2, 3, 4].sort(function(a, b) {
    return 0.5 - Math.random()
  })
  finalarr.push(arr)
}

console.log(finalarr)

<!-- end snippet -->

答案4

得分: 1

问题在于您对相同数组的每个索引都添加了一个引用。它们不是各自拥有的数组-它们都是完全相同的一个数组。想象一下有两名新闻记者,每个人都在报道同一个故事。如果故事发生变化,两位记者都会告诉您同样的更新。这就是这些数组正在做的事情。当您说像 arr1 = arr2 这样的话时,您只是在说 arr1 现在是同一个故事/值的新闻记者,所以更改其中一个相关联的值会更改它们两个,并且更改其中一个的位置会更改它们两个的位置。要更改这个行为,您需要在将其分配给新变量之前克隆数组。

将:

finalarr.push(arr);

改为:

finalarr.push(arr.slice(0));

在数组上使用 .slice(0) 是克隆数组的一种方法(对于您的代码来说足够了),以便每个数组实际上都是它自己的值。在这里运行您代码的新版本:

var arr = [1, 2, 3, 4];
finalarr = [];
for (i = 0; i <= 5; i++) {
  arr.sort(function(a, b) {
    return 0.5 - Math.random();
  });
  finalarr.push(arr.slice(0));
}
console.log(finalarr);

个人而言,我选择使用 randojs.com 来获取打乱的数组。每次调用 randoSequence 时,它都会获取一个新的独立数组,因此不需要担心引用的问题。使用 randojs,您的代码将如下所示:

var finalarr = [];
for (var i = 0; i <= 5; i++) finalarr.push(randoSequence(1, 4));
console.log(finalarr);
英文:

The problem here is that you're adding a reference to the same array for each index. They're not all their own arrays- they're all the exact same one. Imagine there are two newscasters, each reporting on the same story. If the story changes, both newscasters will tell you the same update. That's what these arrays are doing. When you say something like arr1 = arr2, you're just saying that arr1 is now a newscaster for the same story/value- so changing the value associated with one of them changes both of them, and shuffling one of them shuffles both of them. To change this, you need to clone the array before assigning it to a new variable.

Change:

finalarr.push(arr);

to:

finalarr.push(arr.slice(0));

Using .slice(0) on the array is a method to clone a shallow copy of the array (which will be sufficient for your code) so each one is actually its own value. Run this new version of your code here:
<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var arr = [1, 2, 3, 4];
finalarr = [];
for (i = 0; i &lt;= 5; i++) {
  arr.sort(function(a, b) {
    return 0.5 - Math.random();
  });
  finalarr.push(arr.slice(0));
}
console.log(finalarr);

<!-- end snippet -->

Personally, I choose to use randojs.com to grab shuffled arrays. It grabs a new, independent array each time you call randoSequence, so no funny business to worry about with references. Your code would look like this with randojs:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var finalarr = [];
for (var i = 0; i &lt;= 5; i++) finalarr.push(randoSequence(1, 4));
console.log(finalarr);

<!-- language: lang-html -->

&lt;script src=&quot;https://randojs.com/1.0.0.js&quot;&gt;&lt;/script&gt;

<!-- end snippet -->

答案5

得分: 0

是的,您可以使用JavaScript数组洗牌函数来随机打乱您的数组。

就像在您的代码中一样,

var arr = [1, 2, 3, 4];
var finalarr = [];
var shuffle_arr = shuffle(arr);
finalarr.push(shuffle_arr);

只需使用shuffle函数即可。

英文:

Yes, you can use javascript array shuffle function to randomly shuffle your array.

like in your code,

var arr=[1,2,3,4]
finalarr = [];
var shuffle_arr=shuffle(arr);
finalarr.push(shuffle_arr);

just use the shuffle function.

huangapple
  • 本文由 发表于 2020年1月3日 13:49:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/59573756.html
匿名

发表评论

匿名网友

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

确定