Is there a way to streamline this generator without using recursion?

I need to develop a unique value generator that produces values within a specified range. The criteria are:

  • all generated values must be distinct
  • the order of values remains consistent upon each run of the generator
  • each value should be significantly different from previously emitted values
  • the number of values to be generated is unknown

To achieve this, I have decided to represent the problem as a tree structure and utilize a breadth-first search algorithm to divide the range into evenly-sized sections. Then, I plan to traverse each layer systematically in a manner that avoids visiting adjacent nodes.

While my current solution involves recursion, I am exploring ways to rewrite it without recursion, perhaps using a queue instead. I'm a bit stuck at the moment. This is what I have so far:

function* orderedSubdivisor(start: number, end: number): Generator<number> {

    const mid = (end - start) / 2 + start
    
    yield mid

    const left = orderedSubdivisor(start, mid)
    const right = orderedSubdivisor(mid, end)

    while (true) {
      yield left.next().value
      yield right.next().value  
    }
}

const iter = orderedSubdivisor(0, 64)

console.log(Array.from({length: 63}, () => iter.next().value))

Any suggestions or alternative approaches would be greatly appreciated. Thank you!

Answer №1

To visualize this concept, you can utilize a binary counter to represent the position or path within your tree structure. The significance of each bit determines whether you are in the left or right section of each branch as you traverse through the levels.

function* orderedSubdivisor(start, end) {
    for (let i=1; true; i++) {
        let sum = start;
        let part = end-start;
        for (let j=i; j; j=j>>>1) {
            part /= 2;
            if (j & 1) sum += part;
        }
        yield sum;
    }
}

const iter = orderedSubdivisor(0, 64)

console.log(Array.from({length: 63}, () => iter.next().value))

Essentially, what you have created is a form of counter but with the bit order reversed for every value yielded:

function* orderedSubdivisor(start, end) {
  const mid = (end - start) / 2 + start
  yield mid
  const left = orderedSubdivisor(start, mid)
  const right = orderedSubdivisor(mid, end)
  while (true) {
    yield left.next().value
    yield right.next().value  
  }
}

let i=0;
for (const v of orderedSubdivisor(0, 64)) {
  if (i++ >= 63) break;
  document.body.appendChild(document.createElement('pre')).textContent = v.toString(10).padStart(2)+': 0b'+v.toString(2).padStart(6, '0');
}

Answer №2

I'm currently working on a generator that will produce values within a specified range, ensuring each value is sufficiently distant from the ones generated before it.
This is particularly important for my project involving mapping hues on a color wheel.

To achieve this, I suggest utilizing the fibonacci hashing technique along with the golden ratio/golden angle, as it ensures a uniform distribution of output around the color wheel:

function* orderedSubdivisor(start, end) {
  for (let i=0; true; i+=0.6180339887498951) {
    yield start+(i%1)*(end-start);
  }
}

let i=0;
for (const v of orderedSubdivisor(0, 360)) {
  if (i++ >= 100) break;
  const p = document.body.appendChild(document.createElement('p'));
  p.textContent = v;
  p.style = `background-color: hsl(${v}deg, 100%, 50%)`;
}

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

Modifying the src attribute of an object tag on click: A step-by

So I have an embedded video that I want to dynamically change when clicked on. However, my attempt at doing this using JavaScript doesn't seem to be working. <object id ="video" data="immagini/trailer.png" onclick="trailer()"></object> H ...

Can you please explain the process of retrieving the value of an item from a drop-down menu using JavaScript?

I am currently developing a basic tax calculator that requires retrieving the value of an element from a drop-down menu (specifically, the chosen state) and then adding the income tax rate for that state to a variable for future calculations. Below is the ...

Tips for running a dry default with Angular CLI

Query: Can dry-run be set as the default in a configuration? Purpose: Enabling dry-run by default simplifies the learning process by minimizing clean-up tasks if the command is not correct. This can encourage users to always perform a test run before exec ...

Trouble with the filter function in the component array

I am facing an issue with creating and deleting multiple components. I have successfully created the components, but for some reason, I am unable to delete them when I click on the "delete" button. state = { data: '', todoCard: [], id ...

Activate scroll function exclusively upon hovering over specific object

I am working on a page with an object that allows users to zoom in and out. I want to create a special zoom function that will be triggered when the user scrolls while their cursor is hovering over this object. If the cursor moves away from the object, th ...

Block users from viewing the image displayed within a JavaScript canvas

On my server, I have a path to an image that is accessed by a JavaScript to load the image onto a canvas. The script then proceeds to hide certain parts of the image using black layers. The issue arises when a user can easily view my JavaScript code, extr ...

"Encountering an Error with Route.get() when attempting to utilize an imported

I have a function that I exported in index.js and I want to use it in test.js. However, when I try to run node test, I encounter the following error message: Error: Route.get() requires a callback function but got a [object Undefined] What am I doing wro ...

eBay API request error: "You do not have the necessary permissions to complete the request."

While working on integrating the eBay API, I encountered an issue with creating a payment policy. Following the instructions provided in this guide , I generated a token and sent it using Postman. However, I received an error: { "errors": [ ...

Is there a way to adjust this callback function in order to make it return a promise instead?

This script is designed to continuously attempt loading an image until it is successful: function loadImage (url = '', callback = () => {}) { utils.loadImage(url, () => { callback() }, () => { loadImage(url, callback) }) } ...

What is the importance of having Express in the frontend?

As someone who is relatively new to the world of JavaScript and web applications, I recently came across an Express web application project that contained a public directory, client directory, and server directory. This has raised some questions for me. I ...

The size of objects on canvas is not consistent when loading with fabric.js loadFromJSON

Click here to view the code var canvas = new fabric.Canvas('canvas_1'); var canvas2 = new fabric.Canvas('canvas_2'); var imgObj = new Image(); imgObj.src = "https://gtaprinting.ca/wp-content/uploads/2021/05/blank-t-shirt-front-gre ...

Error message occurred stating "error running npm start due to spawn C:WINDOWSSystem32WindowsPowerShellv1.0powershell ENOENT"

Whenever I attempt to run npm start, this is the issue that arises. It seems like there might be a problem with PowerShell rather than npm because npm successfully starts the development server. By the way, I created a basic React app using npx create-reac ...

Which is better for integrating Google Maps API - JavaScript or PHP?

Is it better to use JavaScript or PHP with the Google Maps API? What are the advantages and disadvantages of each? If I have geocodes stored in a database, should I retrieve them using Ajax and process them with JavaScript, or is PHP a better option? The ...

Dynamic water filling effect with SVG

I'm trying to create a wipe animation that looks like water filling up inside of a drop shape. Currently, it is a square with a wave animation on top of the drop logo. The wave animation works correctly, but I am struggling to contain it within the dr ...

Grasping the idea of elevating state in React

I can't figure out why the setPostList([...postList, post]) is not working as expected in my code. My attempts to lift the state up have failed. What could be causing this issue? The postList array doesn't seem to be updating properly. I'v ...

React useEffect alert: Exceeding maximum update depth limit. Any solutions to bypass this issue?

In the code snippet below, I am utilizing the useEffect hook to monitor changes to a percentage variable and then initiating a timer to increment that variable every second. This process starts as soon as the page loads. The percentage variable is crucial ...

The error message "Uncaught (in promise) ReferenceError: dispatch is not defined" indicates that

Currently, I am utilizing vuex with index.js and auth.js stored in the store folder. My goal is to perform a basic sign-in operation within my signin.vue by calling an action from the store. However, I encountered the error 'Uncaught (in promise) Refe ...

Maintaining sequential order IDs for table rows even after removing records

I currently have a table structured as follows: <table> <tr> <td> <input type="hidden" name="help[0].id" /> </td> <td> <span class="tr-close">X</span> </tr> <tr ...

Inserting an icon into a particular class

I am new to JavaScript and I am eager to understand the code I write rather than just using it. That's why I'm turning to this forum with a question regarding adding an icon to a colored group. Here is the code snippet I have: <strong> ...

Top tips for accessing and modifying an immutable object within a component retrieved from an RXJS/NGRX store in Angular

This week we successfully updated our Angular v9 app to v11 and RXJS v6.6 with minimal issues. However, due to the store being in freeze mode, we are encountering errors when trying to update the store in certain areas of our code. While most of the issue ...