Tally of number series in an array

If my array looks like

[0, 2, 4, 10, 10, 10, 10, 2, 5, 3, 2, 10, 10, 5, 7, 4, 10, 10, 10, 10]

How do I determine the number of times a sequence of 10's occurs with at least 3 repetitions.

In this example, the output would be 2 because there are 2 sequences of 10's with four 10's in each sequence.

const values = [0, 2, 4, 10, 10, 10, 10, 2, 5, 3, 2, 10, 10, 5, 7, 4, 10, 10, 10, 10];
const MAX = 10;
const threshold = 3;
let count= 0;

let numberInSeq = 0;

values.forEach(x => {
  if (x === MAX) {
    numberInSeq++;
  } else {
    if (numberInSeq >= threshold) {
      count++
    }
    numberInSeq = 0;
  }
})
return count;

This code should work as intended, but I am open to suggestions for optimizing it further.

Thank you!

Answer №1

Your forEach loop contains some minor mistakes that need to be corrected in order to accurately count sequences. It is important to check the threshold only if the current value matches the specified value, such as MAX in your scenario, and then reset the numberInSeq when the threshold is reached. Additionally, I included a flagger variable, sequenceFound, to prevent counting long sequences more than once.

This approach offers the advantage of being a single pass through the data, resulting in a complexity of O(n) in Big O Notation, unlike multiple pass through solutions.

var sequenceFound = false;

values.forEach(x => {
  if (x === MAX) {
    numberInSeq++;
    if (numberInSeq >= threshold && sequenceFound === false) {
      count++;
      sequenceFound = true;
      numberInSeq = 0;
    }
  } else {
    numberInSeq = 0;
    sequenceFound = false;
  }
});

Answer №2

There is a method that involves combining an array into a string with a single character and then using regex to match 10 followed by that character, checking the length of each match, and reducing it to a single value.

let arr = [0, 2, 4, 10, 10, 10, 10, 2, 5, 3, 2, 10, 10, 5, 7, 4, 10, 10, 10, 10]

let op = arr
        .join('-')
        .match(/(10-)+/g)
        .reduce((o,e)=> (o = e.split('-').length-1 >= 3 ? o+1 : o)  , 0)

console.log(op)

As a side note - It may not be the most efficient way in terms of performance compared to using a for loop.

Answer №3

One approach utilizing regular expressions is shown below:

/, 10{3,}/g

The regex pattern captures all the necessary criteria, but the array must first be converted to a string. This method may differ in efficiency compared to other solutions.

Demonstration

let values = [0, 2, 4, 10, 10, 10, 10, 2, 5, 3, 2, 10, 10, 5, 7, 4, 10, 10, 10, 10];
let str = values.join(', ');
let count = 0;
const rgx = /(, 10){3,}/g;
let result = rgx.exec(str);
while (result !== null) {
  count++;
  console.log(result[0]);
  result = rgx.exec(str);
}

console.log(`count: ${count}`);

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

create a custom data type in RAML that includes an array of diverse objects

I am currently working with two distinct Datatypes (and potentially more may be added in the future): #%RAML 1.0 DataType type: object properties: sftp: type: object properties: directory: type: string example: /upload ...

Merge rxjs streams, identify modifications, and yield a single result

In the context of using Angular with .net Core WebApi, let's consider the development of a time management application designed to monitor task durations. The user initiates a task on the front end which triggers a timer displaying elapsed time. The ...

Simple guide on how to use AJAX (without jQuery) and PHP to count the number of records

As a novice programmer, I am attempting to tally the number of records in a table. Despite perusing various code snippets, I am unable to seamlessly integrate them to pass the PHP result to my javascript code. Here is the current state of my code: showsca ...

Having trouble with window.setInterval in AngularJS?

My coding snippet involves the use of the setInterval method: function MyController($scope) { $scope.clock = new Date(); var updateClock = function() { $scope.clock = new Date(); }; setInterval(updateClock, 1000); }; The HTML asso ...

Assigning array materials in ThreeJS allows you to create complex

When I assign framemat to createScene(ID, geometry, 1, framemat), everything works fine. But when I try createScene( ID, geometry, 1, materials[ID] ), it doesn't cooperate. var jsonLoader = new THREE.JSONLoader(), paths = [ "obj/jgd/ ...

Creating a variable that is named after an existing variable

Creating a new variable with a dynamic name can be tricky. Let's take a look at an example: function preloader(imglist) { var imgs = imglist.split("|"); for (i in imgs) { var img_{i} = new Image; img_{i}.src = imgs[i]; ...

Attempting to send a variable from JavaScript to PHP while inside an "if" statement

I've been attempting to pass a variable within an if statement, but for some reason the PHP file isn't receiving the variable. Below is the code I'm working with: JS: if(data.details.payment_type =="sofo") { var orderid = data.deta ...

Looking to incorporate jQuery Form Wizard with mandatory radio button groups?

Currently, I am utilizing the jQuery Form Wizard plugin from The Code Mine website to transform a form into a wizard format. Myform consists of five pages, each containing approximately four radio buttons. It is crucial that at least one radio button on ea ...

Tips for continuously randomizing colors in p5.js

I recently began exploring p5.js and I have a query regarding color randomization. Currently, it seems that the color only changes randomly when I restart the code. Is there a way to trigger this randomization every time the mouse is clicked? Below is the ...

Tips for retrieving the text enclosed within a <span> tag using jQuery

I am new to jQuery and came across this code online for a questionnaire. I want to save the selected options but I am not sure how to do it. " $.fn.jRadio = function (settings)" What is the purpose of this setting? " var options = $.extend(_de ...

Use JavaScript to dynamically add CSS styles to elements before and after a button wrapper

My code seems simple, but for some reason it's not working. I'm trying to add CSS styles to a button when there is a div with the class .wp-block-group both before and after the button. $(".btn-superimposed-wrapper").each(function () ...

Panel floating with Bootstrap framework

I have created a unique two-column layout using Bootstrap, utilizing the col-md-6 class. The layout consists of a row with a panel at the top containing a table, a left column panel displaying a list of media items, and a right column panel containing text ...

Autofill Text Input with React Material-UI

For my current project, I am utilizing Material UI and React. Each TextField in the project has a button next to it, and when the button is clicked, I want it to retrieve the value of its corresponding TextField and set that value as the input for another ...

What could be causing the npm install command to not save packages in the /node_modules directory?

After running npm install to add a package, npm indicates that the installation was successful. However, upon checking the node_modules folder, I'm unable to locate the installed package. In order to access the package, I have resorted to using npm in ...

Creating a new version of an existing method found within a component in a Vue store.js file

As I navigate through the learning curve of vue.js, a seemingly simple question has arisen: how can I achieve the following task? Within one of my vue components, I am facing challenges with the implementation of the "loadSuggestedUsers" method. Here is t ...

Sequencing code execution correctly in Node.js

I am currently working on a website that consolidates articles based on user interests. Although I have a backend set up, I am struggling to execute the code in the correct sequence. Essentially, my database consists of MongoDB containing user informatio ...

Is it impossible to generate a string exceeding 0x1fffffe8 characters in JSON parsing operations?

I am currently dealing with a JSON file that contains data of size 914MB. I am using the fs-extra library to load the file and parse it, but encountering an error during parsing: cannot create a string longer than 0x1fffffe8 characters Here is the code ...

Tips for assisting flow with managing the initialization of react component state

In my React components, I am initializing state like this: export default class LoginForm extends Component { state = { // (*) flash: { message: null, style: null } // initialiser for flash message: show no ...

Creating mutual reactivity between two inputs in Vue.js

I am in the process of creating a tool that calculates the cost of purchasing specific materials. One challenge I'm facing is that users sometimes buy by mass and other times by volume. My goal is to have two active input fields (one for mass and one ...

What is the process for saving appends to variables and converting them to PHP for storage in a database?

<html> <head> <meta charset="utf-8"> <title>Test page for Query YQL</title> <link rel="stylesheet" href="http://hail2u.github.io/css/natural.css"> <!--[if lt IE 9]><script src="http://hail2u.github.io ...