What is the best way to create three distinct fractions in JavaScript that cannot be simplified?

I have a specific requirement to create 3 fractions with the following conditions:

  • The denominator remains constant
  • The numerator must be unique and fall within the range of 1 to three times the denominator
  • The fraction should not be reducible (e.g., 2/6 can be simplified to 1/3, which is not allowed)

Currently, I possess a function that can generate unique numerators:

static randomUnique(range: number, count: number) {
  let nums: number[] = [];
  while (nums.length < count) {
    nums.push(Math.floor(Math.random() * (range) + 1));
  }
  return [...nums];
}

Additionally, I have a method to determine if a fraction is simplifiable:

static isSimplified(numOne: number, numTwo: number) {
        let numerator = numOne;
        let denominator = numTwo;
        for (let i = Math.max(numOne, numTwo); i > 1; i--) {
            if ((numOne % i === 0) && (numTwo % i === 0)) {
                numOne /= i;
                numTwo /= i;
            }
        }
        return numOne === numerator && numTwo === denominator ? false : true;
    }

The issue arises when the generated numerators can potentially be reduced. Hence, I modified the randomUnique function as follows:

static randomUnique(denominator: number, count: number) {
    let nums: number[] = [];
    let numerator = 0;

    while ((nums.length < count)) {
        numerator = Math.floor(Math.random() * (denominator * 3) + 1);
        if (!FractionAxisLogic.isSimplified(numerator, denominator))
            nums.push(numerator);
    }
    return [...nums];
}

However, now an issue has emerged where the numerators are no longer unique.

Could you provide guidance on how to address this concern?

Answer №1

To resolve the issue, I updated the code from let nums: number[] = []; to utilize JavaScript's Set(), a data structure designed for holding distinct elements.

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

Limit the Jquery selection specifically to elements on the modal page

Recently I encountered an issue with a webpage that opens a modal form. The problem arises when the validation function, written in JQuery, checks all fields on both the modal and the page beneath it. //validate function function validateFields() { v ...

Include a function call within a ternary operator in JSX code

I am looking to call a function within a ternary operator condition. Here is what my code looks like: {snapshot.Bid[0].Price !== 'undefined' ? `(${initialOrderInfo.snapshot.Bid[0].Price}` {renderCurrencySymb ...

What is an example scenario where Async Storage can be tested using Jest-expo?

To better understand the testing of Mock-async-storage for reactjs, I decided to replicate an example. If you have any suggestions on a different approach to testing, please feel free to share. I attempted to mimic a use case illustrated on this stack over ...

Is there a way to continuously switch a CSS animation class without needing a second click?

I am seeking a solution to animate the color and size of a div box, then return it to its original state when a button is clicked. Here is an example of my code: document.getElementById("andAction").addEventListener("click", function() { document.getE ...

Verify the presence of blank space with javaScript

I currently have a text box on my website. <input type="text" name="FirstName" value="Mickey"> My goal is to prevent the user from entering empty spaces, tabs, or new lines in the text box. However, I want to allow spaces between characters. Does a ...

Finding the IP address of a server in Angular: A Comprehensive Guide

Is there a way to dynamically retrieve the server host IP address in an Angular application launched with ng serve --host 0.0.0.0? This IP address will be necessary for communication with the backend server. As each coworker has their own unique IP addres ...

Querying data elements using Graphql mutations: a step-by-step guide

const MUTATION_QUERY = gql` mutation MUTATION_QUERY( $name: bigint! ) { insert_name( objects: { name: $name } ) { returning { id name } } } `; const [onClick, { error, data }] = useMut ...

I'd like to know how to retrieve the start and end dates of a specific month using JavaScript

How can I retrieve the start and end date of the current month? const currentDate = new Date(); const startOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1); const endOfMonth = new Date(currentDate.getFullYear(), currentD ...

JavaScript - continuously update the image marked as "active"

I have a collection of 4 pictures that I want to rotate through in my web application. Each picture should have the "active" class applied to it, similar to when you hover over an image. .active, .pic:hover{ position: absolute; border: 1px solid ...

Is there a way to modify AJAX response HTML and seamlessly proceed with replacement using jQuery?

I am working on an AJAX function that retrieves new HTML content and updates the form data in response.html. However, there is a specific attribute that needs to be modified before the replacement can occur. Despite my best efforts, I have been struggling ...

Leveraging ng-repeat within ng-view

I am facing an issue with using ng-repeat inside ng-view as the data is not being displayed. I have come across suggestions on forums to use a factory, but I am hesitant to utilize a service because my $scope data relies on $routeParams for querying. var ...

Dynamic mouse path

Currently, I am in the process of creating a mouse trail similar to what is found on this particular website. I have been using JavaScript, jQuery, and various libraries in my attempt to achieve this effect; however, it has proven to be more challenging th ...

Interacting with the header component within the renderHeader property of the MUI Data Grid Pro will update the sortModel

Currently, I am utilizing the Material UI DataGridPro component to construct a React Js application. I am interested in developing a customized filtering feature. In the image below, you can see a red box representing an IconButton for the filtering view ...

Storing Vue.js components as objects in a database: A step-by-step guide

Is there a way to serialize Vue.js components and store them in a database? For example, I am looking to save components like the HelloWorld component typically found in a fresh Vue installation. Any suggestions on a serialization process or package that ...

Encountering issues with resolving dependency tree post updating node, specifically with node-sass dependency causing failure

Following the update to the latest version of Node.js, I encountered error messages when attempting to use npm audit fix --force. It appears that resolving dependency tree issues is proving to be difficult. Despite extensive research and trying various s ...

Should mutators be encapsulated within a class contained in a JS Module for better code organization and maintainability?

In order to maximize functionality of our new product using JavaScript, we have implemented an Authentication module that manages a tokenPromise which is updated upon user logins or token refreshes. It seems imperative to allow for mutation in this process ...

Executing an external JavaScript function from within an internal JavaScript code block

Currently, I am dealing with 2 JavaScript blocks. One is contained within my HTML and handles touch functionality, while the other is an external file serving as a content slider. My goal is to utilize touch events to control the slider - allowing users to ...

Update the ngView content on the fly

My project requires dynamic routes to be generated when specific URLs are requested in order to customize the view and display corresponding data uniformly. While adding manual routes with the same templateUrl and controller would have made this task simpl ...

We encountered a sudden termination of JSON data while parsing near '...w2BfLygJAO9ZBvYIqZTld'

Encountered an error when trying to initialize a new React App. command: $npx create-react-app yourblog Node --version v12.16.2 npx --version 6.14.4 Click here to view the error ...

Angular project facing issues during Maven build process

Hi there, I'm currently facing some challenges while trying to deploy my Angular and Spring Boot application. Whenever I run the command mvn clean compile spring-boot:run, I encounter a build failure from my Angular pom file. The error message I am r ...