What is the method for tallying a random result while in a loop?

Here is the code snippet:

var sum = 0;
var num = 1;
while(sum < 4){
    sum += Math.random();
    document.write(num++ + ") " + sum + "<br>");
}

The variable num typically ranges from 6 to 12 additions before the while loop terminates.

If we want to calculate how many times the additions fall between 4 and 20 out of a total of 1000 iterations, what would be the approach?

Answer №1

Regrettably, I was not diligent in attending my probability classes at school, unlike you, I hope. Nevertheless, your query simplifies to:

  • What are the chances of completing the operation less than 4 times? (0 since a result greater than 4 is expected, requiring at least 5 operations),
  • And what are the odds of repeating the operation more than 20 times, considering a 20% chance per operation to meet the condition?

This holds true regardless of the number of tests.

The following code snippet may help you in calculating the probabilities you seek:

var result = [];
var j=0;
for (j;j<1000000;j++){
  var summe = 0;
  var i = 1;
  while(summe < 4){
      summe += Math.random();
   //   document.write(i + ") " + summe + "<br>");
      i++;
  }
  result.push(i);
}


const matchingResult = result.filter(num=>num<=20 && num>4);
// Alternatively, simplified as const matchingResult = result.filter(num=>num<=20);
console.log(matchingResult.length/10000,"%","between 4 and 20");

console.log(result.filter(num=>num>20));

I trust this information proves beneficial! ;)

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

Having trouble implementing styles for an element selected using the document.getElementsByClassName() method

In order to adjust the style of a dropdown menu, I need to change its top value to align it properly. The element is being generated by Drupal (a CMS tool) and is configured with classes for styling purposes in the admin view where content is authored. How ...

The authentication error display feature is not functioning as intended in the Vue login component due to a problem

I am currently learning Laravel and Vue through an online course on Udemy. In order to test if the push function works within a Vue component, I am trying to display a failed authentication error response for a 422 error (this is just for testing purposes ...

Reading the fixture JSON file in Cypress - A step-by-step guide

I'm struggling to read data from a JSON fixture file in Cypress for my test cases. Despite following various instructions and examples, I can't seem to make it work. Any ideas on what I might be doing wrong? Below are the details of my files alo ...

Modify the initial selection in the drop-down menu

Dealing with two date inputs and a drop down menu where the first option is "All"... The issue at hand is that if I select dates and they end up being the same, I want the first option in the drop-down menu to become blank. <script type='text/jav ...

What is the most effective way to determine which radio button is currently selected in a group with the same name using JQuery?

<form class="responses"> <input type="radio" name="option" value="0">False</input> <input type="radio" name="option" value="1">True</input> </form> Just tested: $('[name="option"]').is(':checked ...

Unable to pass the jQuery value - troubleshooting tips for Laravel

JavaScript Issue return response()->json([ 'category' => $category, 'editRoute' => $artistCategoriesEditRoute ]); AJAX Response category Object { id: 1, title: "tt", parent_id: 0, … } id ...

Passing data into a different controller

In the process of building a system that involves selecting elements from a list and viewing their details, I have encountered an issue while using MEAN stack. My goal is to pass the id of the selected element to the controller of the second page. However, ...

Using jQuery, extract the input value and verify its accuracy. If correct, display the number of accurately predicted results

I am attempting to extract the value from an input field and validate if the answer is accurate. Rather than simply indicating correctness, I aim to analyze and display the number of correct responses alongside incorrect ones. Encountering difficulties wit ...

An error is encountered with the 'this' keyword in the map operator of Angular

I am in the process of developing a custom validator for a Slug form control and have encountered an issue with my code. ngOnInit() { this.slugCtrl.setAsyncValidators(this.slugValidator); } slugValidator(control: AbstractControl) { const obs1 = c ...

adjusting attributes of jQuery elements

Is it acceptable to temporarily assign properties to jQuery elements in order to indicate to other functions that a change is being made to that element? For instance: A function is running animations on an element The user clicks on something triggerin ...

Can we integrate the Node.js API into Meteor?

Being new to Meteor.js, I've been wondering if it's possible to utilize the node API in my project. I've hit a roadblock and haven't been able to find any information on this topic despite spending a significant amount of time researchi ...

Modifying Array Values in Angular 7

I am currently dealing with a complex array where questions and their corresponding answers are retrieved from a service. Upon receiving the array, I aim to set the 'IsChecked' attribute of the answers to false. The snippet of code I have written ...

Error: Attempting to access property 'mouseX' of an undefined object was unsuccessful

Currently, I am utilizing AmCharts to generate a graph displaying payments made over time. The configuration setup for AmCharts seems accurate. Just to mention, I do not possess expertise in Javascript. Utilizing AmCharts 3.18.3.free The complete conso ...

Having trouble establishing a connection between node.js and MongoDB

I've been struggling to connect node.js to mongoDb. Despite trying various solutions like changing the URL from localhost to 127.0.0.1 and downloading different versions of mongo (v6, v5, v4 - the current one), I'm stuck. Interestingly, when I ac ...

Unable to establish SocketIO callback from client to server resulting in a null object instead

I'm encountering an unusual issue with SocketIO. On the server-side, I am using the emit() method like this: $s.sockets.emit(scope, {some: datas}, function(feedback) { console.log('received callback'); } ) ...

Why does isotope cause strange changes in element styles that disrupt the layout?

I am facing an issue where I want to align different divs with background images next to each other without any spacing, similar to this: https://jsfiddle.net/71qpceqb/ Currently, I am using Bootstrap's row and col to achieve this layout. In the pr ...

Unable to designate decimal value as the default in DropdownListFor in ASP.NET Core when utilizing JavaScript

Everything appears to be functioning properly, except when dealing with decimal values in the following code snippet: $('select#listspec_0__qty option[value = 105.3]').attr("selected", true); ...

Getting the current date and time using datetime.now() in Python

I am looking to create a program that will only run for a specific number of hours, allowing the user to specify this duration. However, let's not get ahead of ourselves. My plan is to utilize datetime.now() to capture the current time and store it i ...

Webpack-hot-middleware increases the number of event listeners exponentially

When configuring my new development environment (node server + client with vanilla js), I encountered an issue with webpack-hot-middleware for live reloading front-end changes. The problem arose when using code like: $button.addEventListener('click&a ...

Creating a worldwide directive using AngularJS

I'm currently working on implementing a directive that will manage user interaction with the navigation system on my website. The directive includes an element.click event listener in the link function, which is responsible for toggling the display of ...