简体   繁体   English

从数组Javascript生成随机元素组

[英]Generating Random Groups of Elments from an Array Javascript

HI I am working on project for school and I am trying to generate random groups of names from a list of names. 我正在为学校项目工作,我正在尝试从名单列表中生成随机的名称组。 The group size and amount of groups will be based off the users input. 组的大小和组的数量将基于用户输入。 I have the code to randomly generate a single element from the array, but I need some help grouping. 我有代码从数组中随机生成一个元素,但我需要一些帮助分组。 This my code so far. 这是我的代码到目前为止。 Its not functioning Please help thanks 它不起作用请帮助谢谢

 function yeah() { var arr = prompt("Enter your names").split(",") console.log(arr); var random = arr[Math.floor(Math.random() * arr.length)]; document.getElementById("h2").innerHTML = random; } function groups() { var arr = prompt("Enter your names").split(","); var random = arr[Math.floor(Math.random() * arr.length)]; var numElem = document.getElementById("input2").value; for (i=0;i <= arr.length; i++) { var newArr = [random]; console.log(newArr); //print name to a new list //remove name from old list /* var arr = prompt("Enter your names").split(",") var groupNum = document.getElementById("input1").value; var newArrays = arr.length / groupNum; */ } } 
  /* Reset */ * { margin: 0; padding: 0; } html,body { height:100%; margin:0; font-family: 'Montserrat', 'sans-serif'; color:#424242; overflow: hidden; } .display { text-align: center; display: table; height:100%; margin:0 auto; } .wrap { display: table-cell; vertical-align: middle; } p { font-size: 50px; /* For lamers who don't support viewport sizing */ font-size:20vmin; text-align: center; margin: 0; } #h2 { float: center; font-size: 30vmin; background-size: contain; } input.text-display { display: inline-block; color: #5E5E5E; font: bold 20px arial; text-decoration: none; text-align: center; margin: 20px auto; padding: 15px 20px; background: #EFF0F2; border-radius: 4px; border-top: 1px solid #F5F5F5; box-shadow: inset 0 0 25px #E8E8E8, 0 1px 0 #C3C3C3, 0 2px 0 #C9C9C9, 0 2px 3px #333; text-shadow: 0px 1px 0px #F5F5F5; } span.love { display: block; position: absolute; bottom:10px; width: 100%; text-align: center; } span.love a { text-decoration: none; color:#D12026; } .twitter-follow-button { vertical-align: text-bottom; } .twitter-share-button { vertical-align: text-bottom; } 
 <div class="display"> <div class="wrap"> <p>Your random value is:</p> <div id="h2">Null</div> <input class="text-display" type="button" onclick="yeah()" height="50px" width="50px" value="click to input data"> <!-- <input type="button" onclick="display()" value="display random"> --> <br> <input id="input1" value="Enter number of Groups"> <input id="input2" value="Enter number of elements per Group"> <input type="button" onclick="groups()"> </div> </div> 

Here's a first fix: to add a new element to an array (like it appears you're doing in your for loop), you should use the arr.push() method. 这是第一个修复:向数组中添加一个新元素(就像你在for循环中看到的那样),你应该使用arr.push()方法。 You'll also want to declare newArr as an empty array before that. 您还需要在此之前将newArr声明为空数组。

I'm not entirely sure, however, that you're doing what you intend to in your groups function. 但是,我并不完全确定你在你的小组中正在做你想做的事情。 Right now it looks like you're choosing a random name from your list and then, for as many times as there are names in your list, assigning that one random name to your new array. 现在,您似乎从列表中选择了一个随机名称,然后,与列表中的名称一样多次,将该随机名称分配给新阵列。

What might help you is to just write out a list of the steps you want to take (what we call pseudo-code), then turn that list into javascript code. 可能对您有所帮助的是只写出您要采取的步骤列表(我们称之为伪代码),然后将该列表转换为javascript代码。 It can be a lot easier to find inconsistencies in that list than it would be to sift through the sometimes confusing code. 找到该列表中的不一致性要比筛选有时令人困惑的代码要容易得多。

Hope this helps, let me know if you have any more questions! 希望这有帮助,如果您有任何疑问,请告诉我!

Not sure what is your function groups doing. 不确定你的功能组在做什么。 As I can see it take all data in arr and put in newarr with random sequence. 正如我所看到的,它将arr中的所有数据放入并随机序列放入newarr中。 You should check on .push() method for creating new array. 您应该检查.push()方法以创建新数组。 It should make your code work. 它应该使您的代码工作。

Sample code: 示例代码:

var newarr = ["David", "Mic"];
newarr.push("Adeline");

Result: Your newarr will have all 3 names in it. 结果:你的newarr将包含所有3个名字。

This is my interpretation of your question. 这是我对你的问题的解释。 Hope it helps.. 希望能帮助到你..

    <script>
    var arr = new Array();   
    function yeah()
    {
    arr = prompt("Enter your names").split(",")
    console.log(arr);
    //var random = arr[Math.floor(Math.random() * arr.length)];
    var allStudents ="";

    for(var i=0; i<arr.length; i++) {
        allStudents += arr[i] + "<br/>\n";
    }

     document.getElementById("h2").innerHTML = allStudents;
    }


    function groups()
    {  
        var arr = prompt("Enter your names").split(",");

        var groups = document.getElementById("groups").value;
        var perGrp = document.getElementById("per_grp").value;

        var innerText = "<h4>All</h4> ";
        for(var i=0; i<arr.length; i++) {
            innerText += arr[i] + ",";
        }
        innerText += "<br/>\n";            


        arr = shuffleArray(arr);

        var finalGroups = new Array();

        for(var i=0; i<groups; i++) {
            // assign shuffled elements
            var grpArr = "";
            for(j=0; j<perGrp; j++) {
                grpArr += arr[0] + ",";
                arr.shift(); // removes first element from array    
            }

            grpArr = grpArr.substring(0,grpArr.length - 1);
            finalGroups[i] = grpArr;
        }




        innerText += "<h4>Groups</h4><br/>\n";
        innerText += "<table width='100%' border='1'><tr>\n";           
        for(var i=0; i<groups; i++) {
            // print groups
            var j=i+1;
            var grpArr = finalGroups[i].split(",");
            innerText += "<td>Group " +j+"<br>";
            for(var k=0; k < grpArr.length; k++){
              innerText += grpArr[k] + "<br>";
            }

            innerText += "</td>\n";
        }
        innerText += "</tr></table>\n";

        document.getElementById("FinalGroups").innerHTML = innerText;


   } 

   /**
    * Randomize array element order in-place.
    * Using Durstenfeld shuffle algorithm.
    */
   function shuffleArray(array) {
       for (var i = array.length - 1; i > 0; i--) {
           var j = Math.floor(Math.random() * (i + 1));
           var temp = array[i];
           array[i] = array[j];
           array[j] = temp;
       }
       return array;
   }


</script>
    <style>
    /* Reset */
      * {
            margin: 0;
            padding: 0;
      }

      html,body {
        height:100%;
        margin:0;
        font-family: 'Montserrat', 'sans-serif';
        color:#424242;
        overflow: hidden;
      }
      .display {
        text-align: center;
        display: table;
        height:100%;
        margin:0 auto;
      }
      .wrap {
        display: table-cell;
        vertical-align: middle;
      }
      p {
        font-size: 30px; /* For lamers who don't support viewport sizing */
        font-size:10vmin;
        text-align: center;
        margin: 0;
      }
    #h2 {
        float: center;
        font-size: 10vmin;

        background-size: contain;

    }
      input.text-display {
        display: inline-block;
        color: #5E5E5E;
        font: bold 20px arial;
        text-decoration: none;
        text-align: center;
        margin: 20px auto;
        padding: 15px 20px;
        background: #EFF0F2;
        border-radius: 4px;
        border-top: 1px solid #F5F5F5;
        box-shadow: inset 0 0 25px #E8E8E8, 0 1px 0 #C3C3C3, 0 2px 0 #C9C9C9, 0 2px 3px #333;
        text-shadow: 0px 1px 0px #F5F5F5;
      }

      span.love {
        display: block;
        position: absolute;
        bottom:10px;
        width: 100%;
        text-align: center;
      }
      span.love a {
        text-decoration: none;
        color:#D12026;
      }
      .twitter-follow-button {
        vertical-align: text-bottom;
      }
      .twitter-share-button {
        vertical-align: text-bottom;
      }


    </style>

    <div class="display">
        <div class="wrap">
            <p>Create Random Groups</p>
            <!--<div id="h2"> </div>

            <input  class="text-display" type="button" onclick="yeah()"  value="click to input data"> -->
           <!-- <input type="button" onclick="display()" value="display random"> -->
            <br>
            <input id="groups" placeholder="Enter number of Groups" >
            <input id="per_grp" placeholder="Enter number of elements per Group">
            <br/>
            <input type="button" value="Create Groups" onclick="groups()">
            <div id="FinalGroups"></div>
        </div>



    </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM