Java Script Dice-rolling Tally System

Having trouble creating a JavaScript dice roll counter. I'm aiming to roll the dice 25 times and generate a random array of numbers one through six. The ultimate goal is to keep track of how many times each number is rolled. Here's my current code snippet:

function rnd(dice){
var number=Math.floor(Math.random(dice)*25);
}

var dice = ["One" , "Two" , "Three" , "Four" , "Five" , "Six"];

length = dice.length;
console.log(length);

for (var i = 0; i < dice.length; i++) {
console.log("i:" + i + "" + dice[i]);
}

Answer №1

Your approach to computer programming seems reminiscent of Frankenstein's monster - piecing together code fragments like body parts and hoping they function as a cohesive program. Rather than starting with this patchwork method, consider a top-down approach. Begin by clearly defining in plain language what you want your program to accomplish. You've already made progress on this:

I need the code to roll the dice 25 times.

Convert this problem statement into pseudo-code format before proceeding any further:

repeat 25 times
  roll die

The next part of your task states:

I need to generate a random array of "one", "two", "three", "four", "five", "six".

This requires more precise thought. Instead of 'a random array', it appears you actually want 'a random value from an array'. Adjust the pseudo-code accordingly:

repeat 25 times
  roll die

to roll die
  generate random value from array of "one" to "six"

Lastly, the problem statement includes:

I also need to count how many times each number is rolled. Here's what I have:

We can handle this by either adding a separate step for counting rolls or integrating the counting within the existing process. Choosing the latter, the updated pseudo-code becomes:

initialize counts

loop from 1 to 25
  roll die
  update counts

to roll die
  generate random value from array of "one" to "six"

This structured approach allows clarity in functionality without getting bogged down in syntax intricacies. By solidifying the pseudo-code, we can easily discuss its flow or delegate implementation to others. With JavaScript as the chosen language, we refine the pseudo-code for better detail and prepare to store results for future reference.

define an array of six numbers for counts with initial values set to zero
create an empty array called results

loop from 1 to 25
  simulate rolling a die to get a result
  adjust counts based on result
  append result to the results array

display results
display counts

to roll die
  provide a random value from the range of "one" to "six"
  return the selected value

Now, with a clearer blueprint in place, proceed to implement a JavaScript program that aligns closely with this structure. Actions outlined in our pseudo-code are encapsulated within a JavaScript function.

function rollDie() {
  return Math.floor(Math.random() * 6); 
}

var counts = [0, 0, 0, 0, 0, 0];
var results = [];

for (var i = 0; i < 25; i++) {
  var result = rollDie();
  counts[result] = counts[result] + 1;
  results.push(result);
}

console.log(results);  
console.log(counts);    

Although numeric values are used instead of strings for simplicity in this code snippet, the core concept remains unchanged.

Answer №2

To solve this problem effectively, it is advisable to divide it into smaller segments.

Begin by ensuring that you are capable of rolling a single die successfully.

const sides = ["One", "Two", "Three", "Four", "Five", "Six"];
const rollDie = () => sides[Math.floor(Math.random() * 6)];

Subsequently, proceed to perform multiple dice rolls in order to achieve a series of n outcomes.

const performRolls = (n) => {
    const results = [];
    for (let i = 0; i < n; i++) {
        results.push(rollDie());
    }
    return results;
};

Lastly, analyze the data obtained from the rolls and determine how many times each outcome occurs.

const countResults = (rolls) => {
    const tally = new Map();
    for (const result of rolls) {
        tally.set(result, 1 + (tally.get(result) || 0));
    }
    return tally;
}

Answer №3

I'm feeling hesitant about providing an answer to this question, but here it goes.
Let's start by identifying what is incorrect in the original code.

function rnd(dice){//the function is never used
var number=Math.floor(Math.random(dice)*25);//
}

var dice = ["One" , "Two" , "Three" , "Four" , "Five" , "Six"];

length = dice.length;
console.log(length);//it's helpful to keep track

for (var i = 0; i < dice.length; i++) {
console.log("i:" + i + "" + dice[i]);//can you clarify?
}

There seems to be no effort to address the issue in the original post. Let's now look at the solution provided by the OP.

var dice = ["One", "Two", "Three", "Four", "Five", "Six"];//an array of names is defined here
var stat = {};//we will store dice roll statistics here
for (var i = 0; i < 25; ++i) {//25 represents the number of rolls
  var rand = Math.floor(Math.random() * 6);//random roll [0,5]; for more sides use dice.length instead of 6
  stat[dice[rand]] = (stat[dice[rand]] || 0) + 1;//counting hits
}
console.log(stat);

I hope this explanation helps you with your assignment.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generating a matrix using two arrays in numpy

Is there a specific numpy command that can be used to multiply a column vector by a row vector resulting in a matrix? For example, [1, 1, 1, 1] ^T * [2, 3] = [[2, 3], [2, 3], [2, 3], [2, 3]] ...

The upcoming tick override feature will execute the specified function

I am looking to replace the code below The function will run in the following tick req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) { setTimeout(fn, 5); } : function (fn) { fn(); }; with this new code, window.require.nextT ...

"Ionic offers a seamless integration of both side menu and tabs for enhanced navigation

I am working on implementing a sidemenu and tabs on the same screen in my Ionic app project. Currently, it is almost working, but I need the bottom tabs to be visible at all times while also being able to navigate to other views from the sidemenu without ...

turning every input field's border to red if none of them were filled out at least once

I struggle with javascript and need some help. I have a form with multiple input fields, and I want to ensure that the user fills in at least one of them. I found code that triggers an alert message if the user does not fill in any fields, but I would pref ...

Combining images and text from diverse sources

I'm currently engaged in some web scraping, attempting to extract both the image and text from different classes, and then showcase them together. Below is an example of the HTML snippet: <div class="thumbnail"> <div class="i ...

Automatically press a button that appears on the webpage

I am looking to automate the clicking of a button that appears on a website. How can I accomplish this using Python? I have no experience in JavaScript and am fairly new to programming. Here is the outer HTML code for the button: <button type="button" ...

Utilize the angularJS filter to emphasize the search text within the search results

I have a search box that filters results displayed on the screen. I am using a filter called 'startWith' for this purpose. Now, I need to implement a feature where the search text is highlighted among the search results in angularJS. For example ...

Error message: Unable to locate local module in node.js subdirectory

Exploring the folder structure within my application https://i.stack.imgur.com/Pkxpg.png Referring to app_modules/bar and app_modules/foo as local modules Root Folder package.json "dependencies": { "body-parser": "~1.18.2", "cookie-parser": "~ ...

Navigating the complexities of functions in javascript can often leave one feeling perplexed and

I am currently working on an implementation that involves the following code snippet: var globalVar = []; var tomakeJson = JSON.Stringify(globalVar); window.load = function grpwrk() { hdWork: function() { // return somefatherwork; ...

Failure to display div upon onmouseover event

The div 'hidden-table' is causing issues as it does not display even though the style attribute 'display:none' has been removed. I have attempted to show the table separately outside of the echo statement, and it appears to work correct ...

Adding input data to an array inside a specific object using AngularJS

My array contains multiple employee objects, each with their own nested payments array: var employees = [ { id: '1', icon: 'img/NC.png', iconAlt: 'N C Image', title: 'Mr', firstName: 'N&apos ...

Effectively generating observables that extract a designated element from a collection of observables

Within my application, I am utilizing a RxJS subject to broadcast changes within a collection. Each time the collection is updated, the subject emits the new contents as an array format. let collectionSubject = new Rx.BehaviourSubject(); collectionSubjec ...

What is the best way to set up a promise for an HTTP GET request?

How can promises be implemented around the provided http get request? $http({ method: 'GET', url: 'getData.php', params: {bill: 'Active'} }) .then(function (response) { bill=response.data.results; }); There i ...

Does moment/moment-timezone have a feature that allows for the conversion of a timezone name into a more easily comprehendible format?

Consider this example project where a timezone name needs to be converted to a more readable format. For instance: input: America/Los_Angeles output: America Los Angeles While "America/Los_Angeles" may seem human-readable, the requirement is to convert ...

What is the best way to sort through this complex array of nested objects in Typescript/Angular?

tableData consists of an array containing PDO objects. Each PDO object may have zero or more advocacy (pdo_advocacies), and each advocacy can contain zero or more programs (pdo_programs). For example: // Array of PDO object [ { id: 1, ...

Numerous criteria for selecting a checkbox

I am working with a student database table called student_db, which looks like this: Name Gender Grade City John Male 2 North Dave Male 4 North Garry Male 3 North Chirsty Female 5 East Monica Female 4 East Andrew Male ...

NodeJS application experiencing significant delays due to slow response times from MySQL database queries

Currently, I am in the process of learning about Node.js. Through utilizing Express and Node-Mysql, I have been able to effectively query my mysql database and return the outcomes as JSON to the client. However, there seems to be a significant delay. Eve ...

Ensure that the view is only updated once the JSON has been completely received from the AJAX call in AngularJS

Just starting out with angularJS and still in the learning phase. I'm currently working on creating a navbar for the header that will fetch data from an ajax call. The issue I'm facing is that it displays {{obj.pageData}} until the data is fully ...

Setting response query correctly in Solr using AJAX

Inspired by an example of using Solr's JSON output for AJAX, I have incorporated a drop-down menu into my project form and introduced faceting to the parameters. Parameters: function getstandardargs() { var params = [ 'wt=json' ...

Mastering Bash execution using commander.js

Is there a way to execute basic bash commands such as rm -rf directory or echo whatever using commander.js? ...