What is the maximum number of groupings that can be created from a set of numbers within a

I'm trying to figure out how to handle a specific task, but I'm running into some obstacles.

When adding numbers to clusters, a number is considered to belong to a cluster if its distance to at least one existing number in the cluster is within a preconfigured spacing limit. If a new number does not fit any existing clusters, it forms a new cluster. In cases where a new number falls between two nearby clusters, it can be part of both, leading to their merge.

For example:

[100, 0, 7, -89, 80, 86, -100, 2, 81]

This input should result in 5 clusters.

I've managed to create a solution, but it only works when inputting numbers in ascending order:

accept = (value: number): void => {
    if (this.previous == undefined || Math.abs((this.previous) - value) > this.spacing) {
        this.counter++;
    }
    this.previous = value;
}

I have to enter data one by one because the tests are set up like this:

it("custom spacing test", () => {
    detector.accept(4);
    detector.accept(7);
    expect(detector.clusterCount()).toEqual(2);
});

Answer №1

Sure thing, I'll make sure to include all the details here.

In order to update the accept method, I am considering creating an array to sort each time and then checking if the value falls within the range of the previous and next numbers after placing it in the array. However, I have not yet written the implementation for this.

export class MyLinearClusterDetectorFactory implements LinearClusterDetectorFactory {
  create(spacing: number): LinearClusterDetector {
    return new MyLinearClusterDetector(spacing);
  }
}

class MyLinearClusterDetector implements LinearClusterDetector {
  constructor(readonly spacing: number) {}
  
  counter = 0;
  previous: number | undefined;
  
  accept = (value: number): void => {
    if (this.previous == undefined || Math.abs((this.previous) - value) > this.spacing) {
      this.counter++;
    }
    this.previous = value;
  }

  clusterCount = (): number => {
    return this.counter;
  }
}

}

I already have tests in place:

describe("Basic testing with spacing 2", () => {
  let detector: LinearClusterDetector;
  
  beforeEach(() => {
    detector = new MyLinearClusterDetectorFactory().create(2);
  });

  it("returns 0 if never called", () => {
    expect(detector.clusterCount()).toEqual(0);
  });

  it("returns 1 if called once", () => {
    detector.accept(1);
    expect(detector.clusterCount()).toEqual(1);
  });

  it("returns 1 if called with overlapping", () => {
    detector.accept(1);
    detector.accept(2);
    expect(detector.clusterCount()).toEqual(1);
  });

  it("returns 2 if called with evidently non-overlapping", () => {
    detector.accept(1);
    detector.accept(4);
    expect(detector.clusterCount()).toEqual(2);
  });
  
  it("mine spacing 2", () => {
    detector.accept(4);
    detector.accept(7);
    expect(detector.clusterCount()).toEqual(2);
  });
});

}

Answer №2

To find the longest cluster in arrays, you can combine them and return the count of the largest cluster.

const
    getMaxClusterSize = (array, space) => {
        return array
            .reduce((r, v) => {
                const [temp, filtered] = r.reduce((q, a) => {
                    q[+a.some(w => Math.abs(v - w) <= space)].push(a);
                    return q;
                }, [[], []]);

                temp.push(filtered.length
                    ? [...filtered.flat(), v]
                    : [v]
                );
                return temp;
            }, [])
            // .reduce((a, b) => a.length > b.length ? a : b)
            // .length; 
    };
    

console.log(getMaxClusterSize([100, 0, 7, -89, 80, 86, -100, 2, 81], 15)); // 4

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

Passing parameters to an Angular 2 component

When it comes to passing a string parameter to my component, I need the flexibility to adjust the parameters of services based on the passed value. Here's how I handle it: In my index.html, I simply call my component and pass the required parameter. ...

Removing duplicate entries from a dropdown menu can be achieved by implementing

As a newcomer to the world of PHP PDO, I've learned that the database connection should be in a separate PHP file. However, after spending an entire day trying different things, I'm still facing issues. I suspect that the duplicate entries are a ...

NgControl was not found in the NodeInjector provider. How can I resolve this error?

https://i.sstatic.net/z4h8J.png I am encountering a problem that I have been unable to resolve despite extensive searching. Could you please provide suggestions on how to fix this issue? I have already included the following line in the application modu ...

Showing Variables in JavaScript

<!DOCTYPE HTML> <html> <body> <button onclick="question++">Increment</button> <script> function test() { var question = 0; } </script> </body> </html> Qu ...

`How can I extract HTMLElements from slots in vue3?`

When attempting to develop a Layer component, I encountered some challenges. Here is the code: // Wrapper.vue <template> <slot v-bind="attrs"></slot> </template> <script lang="ts" setup> import { defi ...

What is the best way to extract a value from a JSON object?

I am having trouble deleting data from both the table and database using multiple select. When I try to delete, it only removes the first row that is selected. To get the necessary ID for the WHERE condition in my SQL query, I used Firebug and found this P ...

Javascript encountering compatibility issues with certain versions of Internet Explorer; employing browser detection workaround

Unfortunately, Internet Explorer is causing issues when trying to execute this script (specifically the 'else' part). Despite numerous attempts, I have been unable to resolve it. $(document).ready(function(){ if (navigator.appName != "Micros ...

Adding images to your SVG using Bobril is a simple process that can add visual

I have been attempting to insert an image into an SVG using Bobril, but the following code is not functioning as expected: { tag: 'svg', children: { tag: 'image', attrs: { 'xlink:href': &ap ...

Click here to navigate to the same or a different page using an anchor

I'm currently implementing this code: $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostna ...

MongoDB facing difficulties in updating the database

Seeking help with my MongoDB setup as I am still new to it. I have a database where card data is stored and need to update counts when users like cards, resulting in a total likes number. I'm facing an issue where I keep getting a 400 error response ...

Broaden the default className attribute of the component

Greetings! I'm currently using Bootstrap with React and I am trying to figure out how to extend my component by passing className props deeper. Within my atom component, I have two separate files. The first one contains the component declaration. B ...

Navigating the parent navController in Ionic 2: A step-by-step guide

I'm currently honing my skills in Ionic 2 by creating a basic app, but I've encountered an issue that has me stumped. The app features an ion-nav element for the login page, then transitions to a tabs navigator after successful login. The struct ...

Different approach for searching and modifying nested arrays within objects

Here is an example of the object I am working with: { userId: 111, notes: [ { name: 'Collection1', categories: [ { name: 'Category1', notes: [ {data: 'This is the first note& ...

Maintain the fancybox open even in case of ajax errors

I'm having an issue with my code where the fancybox closes automatically after displaying the error message briefly. I want it to remain open so that users have more time to fix their errors. What could be causing this problem? $(document).ready(func ...

Silent response upon click event listener

I'm having an issue with a navbar item not calling the reverseService function on click as expected. Although my IDE is indicating that the reverseService function is never used, VueJS dev tool doesn't show any problems. However, manually changi ...

The contrast between FormData and jQuery's serialize() method: Exploring the distinctions

Recently I came across a situation where I needed to submit a form using AJAX. While researching the most efficient method, I discovered two popular approaches - some developers were utilizing jQuery#serialize() while others were opting for FormData. Here ...

Error: Uncaught ReferenceError: d3 is undefined. The script is not properly referenced

Entering the world of web development, I usually find solutions on Stack Overflow. However, this time I'm facing a challenge. I am using Firefox 32 with Firebug as my debugger. The webpage I have locally runs with the following HTML Code <!DOCTYP ...

Unit testing in JavaScript has its limitations, one of which is the inability to verify if a

Currently, I am working with an Angular application that includes a simple directive called animate. My goal is to use Jasmine to verify if the slideDown method is being called. Below is the current setup of my directive: animateDirective var animate = f ...

"Enhance your data management with Laravel and Vue.js by incorporating the powerful Matfish Vue-Table

Currently, I am utilizing matfish-vue-table2 along with server-side implementation. Below is my Laravel controller where I am able to retrieve the JSON response from the 'api/articles' URL: public function index() { $articles = Article::orde ...

Hydration has finished, but there are some discrepancies - Utilizing Ascii art within a vue component

I encountered an issue with displaying ascii art in the {{ name }} section of my component. While developing, a Vue warning popped up: Hydration text content mismatch in <pre> Followed by an error message: Hydration completed but contains mismatch ...