Create a series of numbers with a symbol separating each set of every nth number

My goal is to create a string that includes numbers from 1 to 1000, with the character '*' inserted after every 5th number. For example:

1 2 3 4 5 * 6 7 8 9 10 * 11 12 13 14 15 * 16 17 18 19 20 * …

I made an attempt at solving this problem, but it's not quite working as expected:

const insertCharacter = () => {
    let contain = [];
    let new_value;
    for (let i = 1; i <= 1000; i++) {
         contain += [i];
         if (contain.length)
         contain.toString()
         let parts = contain.match(/.{0,5}/g);
         new_value = parts.join("*");
    }
    return new_value;
}
console.log(insertCharacter());

Answer №1

One potential solution could involve utilizing the modulus operator in this scenario:

let result = "";
for (let j=1; j <= 1000; ++j) {
    if (j > 1 && j % 5 === 1) result += " *";
    if (j > 1) result += " ";
    result += j;
}
console.log(result);

Answer №2

Outdated JavaScript format version, still relevant.

The % represents a Remainder which is crucial in this context.

An example code that simply counts up to 50.

Edit: Updated to the commented version by mplungjan.

Another edit due to comment by georg. To avoid having a trailing Asterisk, consider these alternatives:

  • count up to 999, then append 1000 afterwards
  • utilize
    result.substring(0,result.length-2)

var i, result = "";
for(i=1;i<51;i++){
  result += i + (i % 5 ? " " : " * ");
}
console.log(result);

Answer №3

Take a look at the following code snippet.

const numbers = [...Array(1000)].map((value, index) => (index + 1) % 5 === 0 ? index + 1 + " *" : index + 1);
console.log(numbers.join(' '));

Answer №4

To exclude the trailing character, a simple solution would be:

Array.from(Array(1000 / 5),
  (_, i) => (i *= 5, `${i+1} ${i+2} ${i+3} ${i+4} ${i+5}`))
    .join(' * ');

We don't have to loop through 1000 times as we already know all the numbers and that there will be 200 groups of 5 numbers each. The task is to generate these groups and combine them.

However, there are some issues with this approach:

  • The interval is fixed
  • The separator is fixed
  • What if we can't evenly divide the numbers?

For example, let's say we need to add a | after every 4th number out of 10:

1 2 3 4 | 5 6 7 8 | 9 10

We have 2 sets of 4 numbers each and 1 set containing the last two numbers.

(I'll provide annotations to help you connect these examples with the final code below)

You can create the first two sets like this:

Array.from(Array(Math.floor(10 / 4)), (_, i) => (i*=4, [i+1, i+2, i+3, i+4].join(' ')))
//               ^^^^^^^^^^^^^^^^^^                    ^^^^^^^^^^^^^^^^^^^^
//               imax                                  tmpl
//                                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//                                              nseq
//
//=> ['1 2 3 4', '5 6 7 8']

The last set with:

Array(10 % 4).fill(0).map((_, i) => Math.floor(10 / 4) * 4 + i + 1).join(' ')
//    ^^^^^^                        ^^^^^^^^^^^^^^^^^^
//    tmax                          imax
//                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//                                  nseq
//
//=> '9 10'

Then you simply do:

['1 2 3 4', '5 6 7 8'].concat('9 10').join(' | ')
//=> '1 2 3 4 | 5 6 7 8 | 9 10'

Demo

console.log("sprintnums(10, 7, '|') -> " + sprintnums(10, 7, '|'));
console.log("sprintnums(10, 4, '|') -> " + sprintnums(10, 4, '|'));
console.log("sprintnums(10, 2, '|') -> " + sprintnums(10, 2, '|'));
console.log("sprintnums(10, 1, '|') -> " + sprintnums(10, 1, '|'));

console.log(`

  In your case:
  
${sprintnums(1000, 5, '*')}

`);
<script>
function sprintnums(n, x, c) {
  const tmpl = Array(x).fill(0);
  const nseq = (arr, mul) => arr.map((_, i) => mul * x + i + 1).join(' ');
  const imax = Math.floor(n / x);
  const tmax = n % x;
  const init = Array.from(Array(imax), (_, mul) => nseq(tmpl, mul));
  const tail = tmax ? nseq(Array(tmax).fill(0), imax) : [];
  return init.concat(tail).join(` ${c} `);
}
</script>

Answer №5

take a look at this piece of code

function addCharacter() {
  let result = '';
  for (let index = 0; index < 100; index++) {
    result += index;
    if (index % 5 == 0) {
      result += '*'
    }
  }
  return result;
}
console.log(addCharacter());

Answer №6

let string = '';
for(let index = 1; index <=1000; index++){
  string+=index;
  if(index - 1 % 5 ===0) string+='*';
}
console.log(string)

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

Guide on Minimizing ES6 with Gulp

I am new to creating a gulpfile.js manually for my project based on Backbone and Marionette. My initial gulp file had the following structure: var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var browserify = require ...

"An excessive number of indices was detected within an array during a loop execution

I'm just starting out with Python and I'm still getting the hang of writing code. Here's what I have so far: N = len(data) i = 0 j = 0 e = 10 while (i<N and j<339) : s[j] = data[i,1] i = i + 14 ...

Using the jqueryRotate plugin to rotate an image by 90 degrees

Is there a way to rotate images on a webpage using the JQueryRotate script? I have 10 images that I want to be able to rotate when clicked, but I'm not sure how to implement it. Any assistance would be welcomed. This is the HTML code for the images: ...

Modify the background color when hovering using jquery

In order to have buttons with variable colors and a different hover color, I have to apply inline CSS. Since the hover color cannot be added using inline CSS, I need to use JavaScript. I attempted to achieve this using the .hover() function, but the colors ...

Tips for executing getJSON requests one after the other

My goal is to showcase a weather forecast for a specific date on my website. Here are excerpts from the code I've used on a trial page that isn't functioning correctly: <script> function displayWeather(date){ $.getJSON(url + apiKey + "/" ...

Is there a way for me to use an ajax xmlhttprequest to submit all the selected values from my radio buttons?

Here's the situation: I have four input forms [A-D] and I have selected options A and B. I want to transfer this information to another page, but I'm not sure how to do it. I've tried searching for tutorials on AJAX, but most of them focus ...

What causes a string of numbers to transform into a string when used as an array key?

$arr['123'] = "test"; var_dump($arr); // Key is int $arr2['123a'] = "test"; var_dump($arr2); //Key is string Can anyone explain why this behavior is occurring? Is there a solution for setting a key as a string rather than a ...

What could be the reason for the absence of a setOwner method in the sequel object here?

Seeking guidance as a newcomer to sequelizer, I'm baffled by the error message indicating that setOwner is not recognized as a function. Despite my efforts to inspect the object it is called on and finding it resembles the large sequelize object, the ...

Pause for a moment before displaying the VueJS loading screen

When using VueJS, I have implemented a loader to be displayed on each route like this: router.beforeEach((to, from, next) => { store.commit('loading', true); next(); }) However, it seems unnecessary to show the loader for a request that ...

Remove any elements using jQuery that do not contain any content

I need to remove any empty elements from my HTML code. Here is an example of the HTML markup: The HTML markup is stored in a jQuery variable called 'myhtml' and it may contain various tags. <h1> <u> <strong></st ...

Arranging an Array by Two Distinct Characteristics

I currently have an array that is grouped and sorted based on the "Program" attribute, which is working well. However, I now need to sort by a different attribute (Deliverable) within each group. Is this possible? If so, how can I achieve it? Below is an ...

Populate DataGrid using an input through AJAX and jQuery technology

I've been grappling with a persistent issue that's been bothering me for days now. Here's the scenario: Currently, I have a DataGrid that is empty and an Input Text field in place that utilizes AJAX and jQuery to display a list of available ...

How to design a constructor function with various enum states for a card game?

Currently, I am working on developing a custom object in my coding project where I aim to link multiple letters to it. I am implementing a setup similar to where an Object can be attributed with various letters (or boolean flags). For instance, the Compa ...

GraphQL Shield throws an 'Unauthorized' error for a permitted mutation

I've been working on setting up a GraphQL API with apollo-server-express, and I'm trying to handle permissions using graphql-shield middleware. However, I'm running into some issues when it comes to allowing mutations to be executed. My aim ...

Exploring the capabilities of arrays within Ajax

Below is the original code I wrote in JavaScript: var wt_val = []; for (i = 0; i<human_wt.length; i++){ var mult; mult = data_list[basket_list[button_port_name][i]].map(x => x*(wt[i]/100)); wt_val.push(mult); ...

Is it possible to trigger JavaScript after loading a page in jqTouch with AJAX?

Similar to the kitchensink demo, I have successfully used jqtouch to call external .html pages into the index page. One of these external pages contains a video that is being played using sublime player. Everything is pretty basic so far, but my challenge ...

Is it possible for two distinct devices to generate the same HWID using Pushwoosh Cordova API?

Our app relies on HWIDs generated by Pushwoosh to distinguish between devices. After reviewing traffic logs, I noticed a peculiar pattern of what appears to be the same device sending HTTP requests from various ISPs within short time intervals. It seems t ...

When transferring data from Django rest framework to a JavaScript array, there may be issues with missing

Struggling to retrieve data from my API endpoint using AJAX. During the iteration of the JSON object to populate my JavaScript array, I seem to be overlooking some values. Here's a breakdown: API data: HTTP 200 OK Allow: GET, HEAD, OPTIONS Conte ...

I could really use some guidance on how to begin with the Node.JS app file in BlueMix

After delving into JS tutorials, I feel comfortable with the syntax and approach. Now, my focus is on utilizing Node.JS to develop an app using BlueMix. While I consider myself proficient in Java, web programming is uncharted territory for me, leaving me s ...

Sorting swiftly using pointers

For my homework assignment, I am tasked with coding a quick sort algorithm in C. The given prototype is as follows: static inline int* choose_pivot(int *left, int *right) { /* FIX ME */ } /* * partition(left, right, pivot): push value less than *piv ...