IT Share you

임의의 값으로 배열 만들기

shareyou 2020. 11. 15. 12:04
반응형

임의의 값으로 배열 만들기


0부터 39까지의 임의 값을 사용하여 40 개의 요소로 배열을 어떻게 만들 수 있습니까? 처럼

[4, 23, 7, 39, 19, 0, 9, 14 ...]

여기에서 솔루션을 사용해 보았습니다.

http://freewebdesigntutorials.com/javaScriptTutorials/jsArrayObject/randomizeArrayElements.htm

그러나 내가 얻는 배열은 거의 무작위 화되지 않습니다. 연속적인 숫자 블록을 많이 생성합니다.


다음은 고유 번호 목록을 섞는 솔루션입니다 (반복 없음).

for (var a=[],i=0;i<40;++i) a[i]=i;

// http://stackoverflow.com/questions/962802#962890
function shuffle(array) {
  var tmp, current, top = array.length;
  if(top) while(--top) {
    current = Math.floor(Math.random() * (top + 1));
    tmp = array[current];
    array[current] = array[top];
    array[top] = tmp;
  }
  return array;
}

a = shuffle(a);

반복되는 값 (OP가 원하는 것이 아님)을 허용하려면 다른 곳을 찾으십시오. :)


최단 접근법 (ES6)

// randomly generated N = 40 length array 0 <= A[N] <= 39
Array.from({length: 40}, () => Math.floor(Math.random() * 40));

즐겨!


ES5 :

function randomArray(length, max) {
    return Array.apply(null, Array(length)).map(function() {
        return Math.round(Math.random() * max);
    });
}

ES6 :

randomArray = (length, max) => [...new Array(length)]
    .map(() => Math.round(Math.random() * max));

더 짧은 ES6 접근 방식 :

Array(40).fill().map(() => Math.round(Math.random() * 40))

또한 인수가있는 함수를 가질 수 있습니다.

const randomArray = (length, max) => 
  Array(length).fill().map(() => Math.round(Math.random() * max))

Math.random()0과 1 (제외) 사이의 숫자를 반환합니다. 따라서 0-40을 원하면 40으로 곱할 수 있습니다. 가장 높은 결과는 곱하는 값입니다.

var arr = [];
for (var i=0, t=40; i<t; i++) {
    arr.push(Math.round(Math.random() * t))
}
document.write(arr);

http://jsfiddle.net/robert/tUW89/


최단 :-)

[...Array(40)].map(e=>~~(Math.random()*40))


.. 내가 얻는 배열은 거의 무작위 화되지 않습니다. 연속적인 숫자 블록을 많이 생성합니다.

무작위 항목의 시퀀스는 종종 연속적인 숫자 블록을 포함합니다 . Gambler 's Fallacy를 참조하십시오 . 예를 들면 :

.. 우리는 4 개의 앞면을 연속으로 던졌습니다. .. 5 번 연속 앞면이 나올 확률이 1⁄32에 불과하기 때문에 갬블러의 오류에 노출 된 사람은이 다음 플립이 앞면이 될 가능성이 적다고 믿을 수 있습니다. 꼬리입니다. http://en.wikipedia.org/wiki/Gamblers_fallacy


숫자의 범위가 제한되어 있기 때문에 가장 좋은 방법은 배열을 생성하고 0부터 39까지의 숫자를 순서대로 채운 다음 섞는 것입니다.


일상적인 단선 솔루션.

배열의 값은 총 랜덤이므로이 스 니펫을 사용하면 달라집니다.

소문자로 된 임의의 문자가있는 배열 (길이 10)

Array.apply(null, Array(10)).map(function() { return String.fromCharCode(Math.floor(Math.random() * (123 - 97) + 97)); })

[ 'k', 'a', 'x', 'y', 'n', 'w', 'm', 'q', 'b', 'j']

0에서 99 사이의 임의의 정수가있는 배열 (길이 10)

Array.apply(null, Array(10)).map(function() { return Math.floor(Math.random() * 100 % 100); })

[86, 77, 83, 27, 79, 96, 67, 75, 52, 21]

배열 임의 날짜 (10 년 전부터 지금까지)

Array.apply(null, Array(10)).map(function() { return new Date((new Date()).getFullYear() - Math.floor(Math.random() * 10), Math.floor(Math.random() * 12), Math.floor(Math.random() * 29) )})

[2008-08-22T21 : 00 : 00.000Z, 2007-07-17T21 : 00 : 00.000Z,
2015-05-05T21 : 00 : 00.000Z, 2011-06-14T21 : 00 : 00.000Z,
2009-07-23T21 : 00 : 00.000Z, 2009-11-13T22 : 00 : 00.000Z,
2010-05-09T21 : 00 : 00.000Z, 2008-01-05T22 : 00 : 00.000Z,
2016-05-06T21 : 00 : 00.000Z, 2014-08-06T21 : 00 : 00.000Z]

배열 (길이 10) 임의의 문자열

Array.apply(null, Array(10)).map(function() { return Array.apply(null, Array(Math.floor(Math.random() * 10  + 3))).map(function() { return String.fromCharCode(Math.floor(Math.random() * (123 - 97) + 97)); }).join('') });

[ 'cubjjhaph', 'bmwy', 'alhobd', 'ceud', 'tnyullyn', 'vpkdflarhnf', 'hvg', 'arazuln', 'jzz', 'cyx']

여기에서 찾을 수있는 다른 유용한 정보 https://github.com/setivolkylany/nodejs-utils/blob/master/utils/faker.js


var myArray = [];
var arrayMax = 40;
var limit = arrayMax + 1;
for (var i = 0; i < arrayMax; i++) {
  myArray.push(Math.floor(Math.random()*limit));
}

위의 방법은 전통적인 방법이지만 값 비싼 계산을하지 않고 배열에서 중복을 피하려면 @Pointy와 @Phrogz를 두 번째로 사용합니다.


몇 가지 새로운 ES6 기능을 사용하여 이제 다음을 사용하여이를 수행 할 수 있습니다.

function getRandomInt(min, max) {
    "use strict";
    if (max < min) {
        // Swap min and max
        [min, max] = [min, max];
    }

    // Generate random number n, where min <= n <= max
    let range = max - min + 1;
    return Math.floor(Math.random() * range) + min;
}

let values = Array.from({length: 40}, () => getRandomInt(0, 40));

console.log(values);

이 솔루션은 화살표 함수 및 Array.from ()과 같은 ES6 기능을 지원하는 최신 브라우저에서만 작동합니다.


let randomNumber = Array.from({length: 6}, () => Math.floor(Math.random() * 39));

쉽게 볼 수 있도록 배열을 6 개의 값으로 제한했습니다.


@Phrogz가 제안한 페이지에서

for (var i=0,nums=[];i<49;i++) nums[i]={ n:i, rand:Math.random() };
nums.sort( function(a,b){ a=a.rand; b=b.rand; return a<b?-1:a>b?1:0 } );

I needed something a bit different than what these solutions gave, in that I needed to create an array with a number of distinct random numbers held to a specified range. Below is my solution.

function getDistinctRandomIntForArray(array, range){
   var n = Math.floor((Math.random() * range));
   if(array.indexOf(n) == -1){        
    return n; 
   } else {
    return getDistinctRandomIntForArray(array, range); 
   }
}

function generateArrayOfRandomInts(count, range) {
   var array = []; 
   for (i=0; i<count; ++i){
    array[i] = getDistinctRandomIntForArray(array, range);
   };
   return array; 
}

I would have preferred to not create a loop that has the possibility to end up with a lot of unnecessary calls (if your count, and range are high and are close to the same number) but this is the best I could come up with.


function shuffle(maxElements) {
    //create ordered array : 0,1,2,3..maxElements
    for (var temArr = [], i = 0; i < maxElements; i++) {
        temArr[i] = i;
    }

    for (var finalArr = [maxElements], i = 0; i < maxElements; i++) {
        //remove rundom element form the temArr and push it into finalArrr
        finalArr[i] = temArr.splice(Math.floor(Math.random() * (maxElements - i)), 1)[0];
    }

    return finalArr
}

I guess this method will solve the issue with the probabilities, only limited by random numbers generator.


If you need it with random unique values from 0...length range:

const randomRange = length => {
  const results = []
  const possibleValues = Array.from({ length }, (value, i) => i)

  for (let i = 0; i < length; i += 1) {
    const possibleValuesRange = length - (length - possibleValues.length)
    const randomNumber = Math.floor(Math.random() * possibleValuesRange)
    const normalizedRandomNumber = randomNumber !== possibleValuesRange ? randomNumber : possibleValuesRange

    const [nextNumber] = possibleValues.splice(normalizedRandomNumber, 1)

    results.push(nextNumber)
  }

  return results
}

randomRange(5) // [3, 0, 1, 4, 2]

I am pretty sure that this is the shortest way to create your random array without any repeats

var random_array = new Array(40).fill().map((a, i) => a = i).sort(() => Math.random() - 0.5);

참고URL : https://stackoverflow.com/questions/5836833/create-an-array-with-random-values

반응형