programing

임의 값으로 배열 만들기

codeshow 2023. 10. 9. 23:39
반응형

임의 값으로 배열 만들기

0에서 39 사이의 임의의 값을 가진 40개의 요소로 배열을 만들려면 어떻게 해야 합니까?

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

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

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

하지만 제가 얻은 배열은 거의 무작위적이지 않습니다.연속적인 숫자의 블록을 많이 만들어내는데...

최단 접근 방식(ES6):

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

여기에 고유한 숫자 목록을 섞는 솔루션이 있습니다(반복되지 않음).

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가 원하는 값이 아닌 반복 값을 허용하려면 다른 곳을 확인합니다.:)

최단:

[...Array(40)].map(e=>~~(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/

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

보기 쉽도록 배열을 6개 값으로 제한했습니다.

.. 제가 얻은 배열은 거의 무작위적이지 않습니다.연속적인 숫자의 블록을 많이 만들어내는데...

랜덤 항목의 시퀀스에는 종종 연속적인 숫자의 블록이 포함됩니다. 도박자의 오류를 참조하십시오.예를 들어,

.. 우리는 방금 4개의 머리를 연속으로 던졌습니다.5개의 헤드가 연속적으로 실행될 확률이 1 ⁄32에 불과하므로 도박자의 오류의 대상이 되는 사람은 이 다음 플립이 테일보다 헤드일 확률이 낮다고 믿을 수 있습니다.http://en.wikipedia.org/wiki/Gamblers_fallacy

왜냐면*보다 우선 순위가 높습니다.|, 를 사용하면 더 짧아질 수 있습니다.|0대체할Math.floor().

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

두 줄의 코드만으로 10개의 난수로 배열을 생성할 수 있습니다.

let result = new Array(10)
result = result.fill(0).map(() => Math.random());

그리고 그냥.

console.log(vals);

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

새로운 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 기능을 지원하는 최신 브라우저에서만 작동합니다.

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입니다.

매일 Quirk 한 줄 솔루션을 사용할 수 있습니다.

배열의 값은 완전 랜덤이므로 이 토막글을 언제 사용할지는 다릅니다.

소문자로 랜덤 문자가 있는 배열(길이 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('') });

[ 'cub 짜프', 'bmw리', '알호브', '세우드', '트눌린', 'vpkdflarhnf', 'hv그', '아라줄린', 'jzz', 'cyx' ]

다른 유용한 것들은 여기 https://github.com/setivolkylany/nodejs-utils/blob/master/utils/faker.js 에서 찾을 수 있습니다.

으로.Es6

옵션1

new Array(40).fill(0).map(_ => Math.random() * 40 | 0)

길이 40의 빈 배열을 만든 다음 0으로 채우고 0을 난수로 바꾸는 것입니다.Math.random()bitwise OR(|)을 사용하여 int로 부동수를 생성합니다.

옵션2

[...Array(40)].map(_ => Math.random() * 40 | 0)

new Array(40).fill(0)와 함께[...Array(40)] 40빈은)되지 않은)합니다.

옵션3

사용하는

Array.from(arrayLike, mapFn)

arrayLike

배열로 변환할 배열 유사 개체 또는 반복 가능 개체입니다.

mapFn (선택사항)

배열의 모든 요소를 호출하는 맵 함수.

Array.from({length: 10}, () => Math.floor(Math.random() * 100));

고유 난수로 채우려는 경우

는 입니다를 입니다.Set, 우리가 알고 있는 것처럼 집합은 고유한 값만 추가할 수 있습니다.

let set = new Set();
while (set.size <= 40) {
  set.add((Math.random() * 400) | 0);
}
let randomArray = [...set];

하지만 여기서 한 가지 중요한 점은 배열 길이보다 큰 수를 곱해야 한다는 것입니다. 그렇지 않으면 고유한 수를 생성하는 데 시간이 너무 많이 걸리고 실행이 오래 걸릴 수 있습니다. 여기에 있는 400보다 10배 큰 수를 사용하려고 합니다.

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
}

저는 이 방법이 확률 문제를 해결할 수 있을 것이라고 생각합니다. 단지 난수 생성기에 의해서만 제한됩니다.

이것이 반복하지 않고 랜덤 배열을 만드는 가장 짧은 방법이라고 확신합니다.

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

아래 참조 :-

let arr = Array.apply(null, {length: 1000}).map(Function.call, Math.random)
/* will create array with 1000 elements */

@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 } );

특정 범위에 고유한 난수가 포함된 배열을 만들어야 한다는 점에서 이 솔루션이 제공하는 것과는 조금 다른 무언가가 필요했습니다.아래는 저의 해결책입니다.

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; 
}

불필요한 통화가 많이 발생할 가능성이 있는 루프(카운트와 범위가 높고 동일한 숫자에 가까운 경우)를 만들지 않는 것이 더 나았을 것이지만, 이것이 내가 생각할 수 있는 최선입니다.

0...길이 범위의 임의 고유 값을 사용하여 필요한 경우:

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]

파티에 조금 늦었지만, 저는 이런 일들을 아주 쉽게 만들 수 있기 때문에 무작위성을 위해 randojs.com 을 사용합니다.다음과 같이 0부터 39까지의 숫자 배열을 임의로 섞을 수 있습니다.

console.log(randoSequence(40));
<script src="https://randojs.com/1.0.0.js"></script>

그 모든 것의 물류에 대해 전혀 개의치 않음 - 게다가 그것은 아주 읽기 쉽고 이해하기 쉽습니다 :)

제너레이터

@Phrogz와 @Jared Beck이 설명하듯이 반복 값 없이 40개의 임의의 가능한 값(0 - 39)의 길이 40 배열은 섞는 것이 더 좋습니다.기록만을 위한 또 다른 방법은 발전기를 사용하는 것입니다.그러나 이 접근 방식은 제안된 다른 솔루션에 비해 성능이 부족합니다.

function* generateRandomIterable(n, range) {
  for (let i = 0; i < n; i++) {
    yield ~~(Math.random() * range);
  }
}
const randomArr = [...generateRandomIterable(40,40)];

다음은 min과 max를 허용하고 min부터 max까지의 모든 숫자를 포함하는 고유 값 배열을 랜덤 순서로 생성하는 ES6 함수입니다.

const createRandomNumbers = (min, max) => {
  const randomNumbers = new Set()
  const range = max - min + 1

  while (randomNumbers.size < range) {
    randomNumbers.add(~~(Math.random() * range))
  }

  return [...randomNumbers]
}

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

반응형