I'm working on generating a numerical pattern that starts with an input number, decreases, and then increases back up to the original number one digit at a time

I am attempting to create a recursive function that can produce a pattern similar to the example below.

cascade(12345) //should print

12345
1234
123
12
1
12
123
1234
12345

While I have managed to achieve the descending part, I am now facing difficulty in ascending back up. Here is my current code:

function cascade(number) {
  let strNum = number.toString()
  let numLength = strNum.length;
  let lengthTracker = numLength
  let hasHit1 = false;
  console.log(strNum)
  if (lengthTracker > 1 && hasHit1 === false) { 
    strNum = strNum.substring(0, strNum.length - 1);
    lengthTracker--;
    return cascade(strNum)
  } else {
    return strNum;
  }
}

cascade(143)

This code successfully outputs:

'143'
'14'
'1'

Is there a way to incrementally add the numbers back onto the pattern afterwards?

Thank you for your assistance!

Answer №1

Exploring a different method involving recursion and strings.

function displayNumbers(s) {
    s = s.toString();
    console.log(s);
    if (s.length === 1) return; // base case
    displayNumbers(s.slice(0, -1));
    console.log(s);
}

displayNumbers(12345);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

ITERATIVE METHOD ⏯

function cascadeIterative(n) {
  const lasts = [];
  while (n) {
    lasts.push(n);
    console.log(n);
    n = Math.floor(n / 10);
  }
  lasts.length--;
  while (lasts.length) console.log(lasts.pop());
}

cascadeIterative(12345);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

RECURSIVE METHOD 🔁

function cascadeRecursive(n) {
  if (n === 0) return;
  const remain = Math.floor(n / 10);

  console.log(n);
  String(remain).length !== 1 ? cascadeRecursive(remain) : console.log(remain);
  console.log(n);
}

cascadeRecursive(12345);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

To retrieve these values, a basic recursive function can be used, with a separate step required to log them. The code might resemble the following:

const cascade = (n) =>
  n < 10 ? [n] : [n, ... cascade ((n - n % 10) / 10), n]

for (let n of cascade (12345)) console .log (n)
.as-console-wrapper {max-height: 100% !important; top: 0}

Note that there is a distinct line for printing the outcome, as the function generates an array like this:

[12345, 1234, 123, 12, 1, 12, 123, 1234, 12345]

The formula within the recursive call to the cascade function calculates the new number by removing the last digit and dividing by ten. This operation could also be achieved using different approaches, such as replacing the function body with one of the following:

  n < 10 ? [n] : [n, ... cascade (Math .floor (n / 10)), n]

or a slightly more obscure but shorter version:

  n < 10 ? [n] : [n, ... cascade (~~ (n / 10)), n]

Answer №4

Although it shares similarities with other methods, I had to tweak it to suit my specific needs. Hopefully, this variation can still be helpful to someone, even if it's a little late.

cascade(111);

function cascade(number) {
        if(number>9) {
          let newNumber =Math.floor(number/10);
          console.log(number);
          cascade(newNumber);
        };
          console.log(number);
        };
<p>check console for results</p>

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

What is the best way to control the amount of rows displayed in my gallery at any given time?

I need help with customizing my gallery that is dynamically generated from a directory using PHP. My goal is to display only 2 rows of 4 images each, totaling 8 images, with a "show more" button for loading additional rows. How can I set a limit on the n ...

Users are encountering timeout issues when attempting to connect to the Azure Postgres flexible database through the node.js server deployed on the Azure App Service

My node.js express server is deployed on Azure App Services, connecting to an Azure flexible Postgresql database. Strangely, everything works fine when running the server locally, but once it's deployed to Azure App Service, all requests time out: htt ...

Having difficulty retrieving the necessary information for manipulating the DOM using Express, Ajax, and Axios

When working on DOM manipulation based on AJAX calls, I've encountered an issue where the response is being displayed on my page instead of in the console.log output. This makes it difficult for me to view the data and determine what needs to be inser ...

NestJS WebSocketGateway fails to initialize due to a technical glitch

After following the instructions in the NestJS documentation, I set up the websockets gateway within the AppModule. The server is starting without any issues, and I'm able to serve static assets via HTTP successfully. However, I'm facing difficul ...

Display numerical values ranging from a to b based on a specific requirement

Seeking guidance as a beginner in JavaScript. I need help with finding the best approach to solve this problem: I have two integers, a and b, where a < b. I want to print all integers in the range [a;b] inclusive. The pattern should be such that integ ...

transferring images from JavaScript to PHP

I am attempting to use ajax to transfer an image from JavaScript to PHP. I have the following HTML input: <input type="file" class="input-field" id="photo" name="photo"> Here is the corresponding JavaScript code: var photo = document.getElementByI ...

What are the steps to update the title and creator details in the package.json file of an Openshift Node.js application?

Recently delving into the world of node.js and PaaS platforms like Openshift, I find myself faced with a perplexing issue. How exactly can I modify the values generated by Openshift in the package.json file without encountering any errors? Each time I at ...

Is there a way to toggle the slide effect of one 'div' without affecting another one?

Hey everyone! I am new to jquery and currently working on a project with two div elements that are slidetoggled. The issue I am facing is that when I open or close one div, the other div also moves along with it. I understand what is happening in the back ...

Is the API for remote asynchronous http calls (Ajax) in Vuejs comparable to that of jQuery?

While Vuejs is known for being more effective than jQuery for DOM manipulation and user interactions handling, I am curious about its performance when it comes to remote asynchronous HTTP (Ajax) calls. I'm looking for a specific Vue.js core API that c ...

Creating specific CSS classes for individual slides in a basic slider framework

So, I have a rather simple slider that is created using only CSS. Each slide has unique labels for navigation buttons. The main question here is: how can I dynamically add or remove classes to specific items on the slide only when that particular slide is ...

When transmitting data from the parent component to the child component, the data successfully passes through, yet the view fails to reflect the

I'm facing an issue with passing data from a parent component to a child component using props. Here is the code snippet I'm working with: <div id="root"> <my-component v-bind:account-types='accountTypes'> </my-c ...

I am unsure of the process for implementing an OnClick event to modify the colors of a square

Seeking guidance from the more experienced individuals here as I am just starting out. Any help would be greatly appreciated! This might seem simple to many of you, but for me it's quite challenging. This is how my HTML code looks: <html> < ...

Sending parameters to a PHP page using POST method when clicking on a dynamically generated <li> element

Here is my primary code: <div class="border_circular row"> <ul id="circulars_slider"> <?php while($row = mysql_fetch_array($circular)){ ?> <li> <p><?php echo $ro ...

C# implementation of the btoa function from JavaScript

I am in need of assistance recoding a JavaScript function to C# that makes use of the btoa method to convert a string of Unicode characters into base64. The challenge lies in ensuring that the encoding used in both languages is identical, as currently, the ...

Vue.JS has issued a warning indicating that the `util._extend` API is no longer supported. To address this, developers are advised to utilize Object

During the execution of a call API request, the Vue.JS application encountered an error. The API is hosted at Okta, and the request is successful when using cURL in the CLI. Error Message (node:82171) [DEP0060] DeprecationWarning: The `util._extend` API i ...

using db.eval() to call db.collection.find()

On my Node.js platform, I have created a JavaScript function that is executed within db.eval() on MongoDB. Here is the original JS function: function(data){ var d = { vehicle_id:data.vehicle_id, timestamp:{ $gte:data.start ...

Modify the appearance of a nested div using CSS hover on the main JSX container

Within the material-ui table component, I am dynamically mapping rows and columns. The className is set to clickableRow. The TableRow also includes a hover options div on the right side: const generateTableHoverOptions = () => { if (selected) { ...

Combine multiple arrays of JSON objects into a single array in PHP

I have organized a json array of results in php and here is the output: [{ "05-10-2018": "Seeing dads differently" }, { "05-10-2018": "Extraordinary ordinary Britain" }, { "05-10-2018": " Roll up for the Social Science Market!" }, { "05-10 ...

Incorporating base Tailwind CSS colors with the daisyUI theme: A simple guide

For my NextJS project, I'm utilizing Tailwind CSS in conjunction with daisyUI. In my configuration file tailwind.config.js, I have it set up as follows: /** @type {import('tailwindcss').Config} */ /* eslint-env node */ module.exports = { ...

Struggling to make divs reach the bottom of the page? Check out my jsFiddle for a solution!

I'm facing difficulty in extending the left and right divs to the bottom of the page, with no additional space above or below. You can view my progress here: http://jsfiddle.net/qggFz/26/ Appreciate any help, Dale ...