What is causing my sorting algorithm to produce inaccurate results?

After finding this sorting function as the best answer to my question, I tested it with example data and it worked perfectly. However, when I tried it with my actual data, it didn't work as expected and I'm not sure why.

You can view my data here: JSON

The data consists of objects like this:

"Montana": {
    "superiors": [
      "Massachusetts",
      "Oklahoma",
      "New Mexico"
    ],
    "inferiors": [
      "North Carolina"
    ]
  }

These objects serve as guidelines for the sorting function. For instance, in this case, Montana should be ranked higher than North Carolina, but below Massachusetts, Oklahoma, and New Mexico (note that this isn't related to geography).

Important Note:

  • This is not related to the order of object keys.

While the sorting algorithm mostly works, there are instances where it doesn't work as expected. For example,

states['North Carolina'].superiors.includes('Ohio') === true
so why is 'Ohio' listed below 'North Carolina'?

  fetch('https://api.npoint.io/7571e85ef470a2a7f189')
    .then(data => data.json())
    .then(states => {
      function mySort(arr) {
        const scores = Array(arr.length).fill(0);
        for (let i = 0; i < arr.length; i++) {
          for (let j = 0; j < arr.length; j++) {
            if (i === j) continue;
            const a = arr[i];
            const b = arr[j];
            if (states[a].inferiors.includes(b) || states[b].superiors.includes(a)) scores[j]++;
            else if (states[b].inferiors.includes(a) || states[a].superiors.includes(b)) scores[i]++;
          }
        }
        // Sort arr by scores:
        return arr.map((val, i) => [scores[i], val])
          .sort((a, b) => a[0] - b[0])
          .map(pair => pair[1]);
      }

      const names = Object.keys(states);

      console.log(mySort(names));

      /*
      // sorted output here...
      */
      // states['North Carolina'].superiors.includes('Ohio') === true
      // so why is 'Ohio' listed beneath 'North Carolina'?
    });

If you're unable to access the original data, here is the JSON for reference:

{"Iowa":{"inferiors":[],"superiors":["Alaska","Oklahoma","California","Hawaii","New Jersey","Virginia","Florida","Washington","Minnesota","Texas","Idaho","Alabama","Ohio"]},"Ohio":... (truncated for brevity)

Answer №1

Your system has a partial order, but it lacks a total order. This means that not all states list each other in their superiors/inferiors list, so the score calculation method you are using will not work accurately. Instead of determining scores based on relative order, states end up with scores based on how frequently they are mentioned. To fix this issue, you will need to implement a topological sorting algorithm.

Answer №2

While there are no conflicting pieces of information in your data, there are certainly inaccuracies present.

For instance, take the Iowa-Oklahoma comparison. Oklahoma is ranked higher than Iowa, yet Iowa is not acknowledged as lower than Oklahoma.

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 managing AngularJS / JavaScript dropdowns with Python and Selenium webdriver

I am looking to automate various browser tasks using Python and the Selenium WebDriver on the Chromium browser. My Python script is currently capable of logging in, navigating to a subpage, performing clicks, and entering information into a form. However, ...

Ways to invoke Java function using Javascript (Client-side)

I have a Java Swing application that handles the User Interface, but requires JavaScript files for hardware testing. The application calls a JavaScript engine to execute functions using the `InvokeFunction()` method. Currently, I am utilizing the LabJack ...

Differentiating Typescript will discard attributes that do not adhere to an Interface

Currently, I am working with an API controller that requires a body parameter as shown below: insertUser(@Body() user: IUser) {} The problem I'm facing is that I can submit an object that includes additional properties not specified in the IUser int ...

What is the best way to include a JavaScript variable within CSS styling?

I am currently implementing a dropdown menu system where the image of a parent div changes on mouse hover over a link, and reverts back when the mouse moves away. I have this functionality set up using a variable in my HTML code. Is there a way for me to m ...

Generate a .py file through an HTML button click and save it to your device

My current project involves developing HTML and JavaScript code for a chatbot. I need to implement a feature where, upon receiving a Python program from the chatbot, a download button should be displayed. When users click on this Download button, they shou ...

Retrieving the correct array from an SQL table using PHP and SQL

I have a table stored in a database that looks like this: - ID | successor - 01 | 02 - 01 | 04 - 01 | 08 - 02 | 03 - 04 | 05 - 05 | 06 This table serves as a simple assignment table for a module in an E-Learning system. The current PHP code I am using i ...

Monitoring the "signed in" status within an AngularJS platform

I'm feeling a bit lost as I navigate my way through Angular. As a newcomer, I find myself writing quite a bit of code to keep track of the logged-in state. However, this approach seems fragile and unreliable. Currently, I rely on a global variable to ...

When I modify the state in Vue.js, the two-way binding feature does not seem to function properly

I'm facing an issue with my dynamic array "slots" of objects which looks something like this: [{"availability": 1},{"availability": 3}] I render multiple inputs in Vue.js using v-for like so: <div v-for="slot in array"><input v-model="slot.av ...

Remove duplicate JSON records in JavaScript by comparing and filtering based on identical attributes

Looking to remove duplicates from a JSON object [{id:1,name:a, cat:1},{id:1, name:a, cat:2},{id:2, name:b, cat:8}] I want to keep only the first occurrence of each duplicated id [{id:1,name:a, cat:1},{id:2, name:b, cat:8}] ...

What is the benefit of using Array#to_enum when Array itself is already an Enumerable?

From what I gather, the Array class includes the Enumerable module. If that's the case, then why isn't there a method like [:example].next available? Why do I have to use [:example].to_enum.next instead? ...

Utilizing Chart.js with Vue for dynamic time axis plots from JSON data through computed properties

Trying to generate a chart with a time axis in Vue using Chart.js has been a challenge. Initially, everything worked perfectly when the data was set directly in the Data object as shown below: chartData: { datasets: [ { backgroundC ...

Steps for correctly invoking a function based on input value conditions

Lately, I've been developing a new website geared towards serving as a platform for various travel agencies to showcase their tour packages. The homepage features a functional filter section that enables users to search for offers based on different ...

Issue with hidden event callback not functioning properly in Bootstrap 3 popover

After studying this example, I attempted to incorporate a hidden callback function. While the show callback is functioning perfectly, the hidden callback seems to be ineffective. Can someone shed light on why this issue is occurring? To showcase the probl ...

What is the method used by React or Next to prevent the <a> tag from refreshing the page while still loading content?

I'm currently diving into the world of NextJS and utilizing the Link component from the 'next/link' package. One thing that has been puzzling me is how the <Link> component ultimately renders an <a> tag with a href='/tosomew ...

View the picture in a web browser

Currently, I am faced with the challenge of displaying an image that is stored in an MSSQL database created by another person. The column was originally of type IMAGE, but I converted it to varbinary(MAX) using Sequelize. Although I lost some data during ...

Looking to verify the existence of a div using jQuery once other jQuery functions have executed and created HTML?

Is there a way to verify if a specific element exists within newly added HTML after clicking a button? I attempted this code snippet: $(document).on('click', '#add-html-code', function() { if ($('#something').length ...

Can you explain the functionality of the Recursion algorithm in this particular code snippet?

I am having trouble understanding the purpose of the code snippet below. It involves a recursive algorithm, particularly the line: if tail else head. Let's say we have a list defined and separated into head and tail components items=[1,10,7,4,5,9] ...

Steps for designing a movable image

I'm looking to implement a feature where the user can drag and drop an image anywhere on the page. Once the user places the image, its position will be saved so that when they revisit the page, it will be in the same location. Thank you! ...

`Modified regions determined by cursor location`

I am working with a split layout featuring two columns, and I need the ability to make each column separately scrollable. Due to using a specialized scroll-to function, I cannot use overflow-y: scroll; or overflow: auto;. I am looking for alternative solut ...

Filtering Jquery datatable results by text

In order to filter records from a jQuery data table, I have utilized the following code. The format for my data table is as follows: var aDataSet = [['1', 'GOld', 'G-110,G-112,G-123', 'G1-001,G1-005,G1-008'], ...