Locate the closest K points to the center of coordinates at (0, 0)

Given a list of coordinates, the task is to find the k closest coordinates to the origin.

While I successfully calculated the distances between the points and the origin, determining the closest k points presented an issue. To solve this, I implemented logic in a secondary for loop where I sorted the array of distances from closest to furthest, then filtered out the values less than k.

function kClosest(points, k) {
    let length = [];
    let arr = [];
    let result = [];
    let a = 0;
    let b = 0;

    for (let i = 0; i < points.length; i++) {
        a = points[i][0]; //x coord
        b = points[i][1]; //y coord (y will always be second number or '1')
        length.push(parseFloat(calcHypotenuse(a, b).toFixed(4)))
        arr.push([points[i], length[i]])
    }

    function calcHypotenuse(a, b) {
        return (Math.sqrt((a * a) + (b * b)));
    }

    for (let i = 0; i < k; i++) {
        arr = arr.sort();
        result.push(arr[i][0])
    }
    return result;
}



console.log(kClosest([
    [-5, 4],
    [-6, -5],
    [4, 6]
], K = 2))

Expected output: [-5, 4], [4, 6] // The initial prediction was [-5, 4], [-6, -5]

Answer №1

Sorting the entire array may not be efficient or even feasible in some cases. This is because the question only requires ordering a subset of elements, not all k elements. Using a comparison-based sort for sorting takes O(n log(n)) time. In scenarios where the input is a continuous stream of numbers, storing and sorting them all may not be practical.

Although I am not well-versed in JavaScript, from an algorithmic perspective, we can tackle this problem more efficiently using one of these two methods:

  1. Utilizing a Max Priority Queue: Establish a max PQ with an order based on distance from the origin. Continuously insert elements into the max PQ, removing the top element (maximum) once the size surpasses k. Ultimately, the PQ will contain the k smallest elements. Space complexity: O(k), time complexity: O(n log(k)), which can approximate O(n) for k << n.
  2. Implementing Quick-select: Execute quick-select k times on the input. This method assumes the input fits in memory (space O(n)) but operates in O(nk) time, potentially reducing to O(n) for k << n.

Answer №2

If you're looking to implement a personalized sorting method, consider utilizing a custom sort function. You can achieve this by passing a comparison function to the Array.sort() method as demonstrated below:

function kClosest(points, k) {

    // Sorts the array in place
    points.sort((point1, point2) => {
        const distanceFromOrigin1 = getDistanceFromOrigin(point1);
        const distanceFromOrigin2 = getDistanceFromOrigin(point2);

        // Sort by distance from origin, starting with the lowest value
        return distanceFromOrigin1 - distanceFromOrigin2;
    });

    // Returns the first k elements
    return points.slice(0, k);
}

function getDistanceFromOrigin(point) {
    const [x, y] = point; // Using array destructuring
    return (x*x) + (y*y);
}

console.log(kClosest([
    [-5, 4],
    [-6, -5],
    [4, 6]
], 2))

For further information on implementing custom sorting methods in JavaScript, check out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort.

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

In a functional component in Typescript, what data type should be used for a parameter that accepts an array of objects?

const FormData = ({ dataArray }: object[]): JSX.Element => { console.log("Array of Objects",dataArray) //This is a large form component.... }); The dataArray contains multiple objects, how can I specify a specific type for these components ...

Dynamic Array Rendering with Vue.js Computed Properties

As a newcomer to Vue, I've dedicated the last few hours to learning how to implement conditional logic in methods and computed properties for a practice birthday component project. While exploring different approaches, I noticed some developers utiliz ...

What is the most efficient way to arrange a multi-dimensional array by time values using PHP?

Currently, for a school project, I am working with a multi-dimensional array that includes the start_time and end_time of various courses. The array has already been sorted by day, but now I need to arrange it by time as well. I want the course with the l ...

Firestore Functions Error: An unexpected issue occurred while trying to obtain application default credentials

While working on Firestore functions, I encountered a log error import * as functions from 'firebase-functions' import * as admin from 'firebase-admin' var defaultApp = admin.initializeApp(functions.config().firebase) const fires ...

Using Jquery's append() method to dynamically alter the HTML content

I am attempting to create a table with rows that are added dynamically. The challenge I am encountering is that each row consists of form elements, including multiple inputs. I have a PHP function that generates the correct row, and I have been able to sen ...

Utilize titles and hrefs for images in an array of objects

In my Canvas, there is a map as the background image with markers placed in different cities. These markers are images duplicated from an Array of Objects and added to the Canvas using drawImage(). Now, I need to include href and title attributes in these ...

Creating a registration and authentication system using firebase

When using Google authentication with Firebase, is the Signup and Login logic the same? I am creating a page for user authentication but I'm unsure if I should have separate pages for signing up and logging in. This confusion arises from the fact that ...

Using jQuery to revert back to the original SRC after mouse is not hovering over an element

I've been working on a script to change the src attribute for an icon. The icon I'm loading is a different color and it's meant to notify the user about the link associated with it. Currently, I have the src changing to the second icon on h ...

Cart cannot function as a constructor

I'm currently learning express.js and trying to implement a shopping cart/session functionality into my project. Below is the code I have written so far, with a question at the end. Here is my cart.js: // Ensure that the file is required correctly b ...

Why am I experiencing a problem with my ajax call only working once when I submit forms that are rendered with @Html.Render

I have a scenario where my index page loads with two partial views, each containing an ajax call that filters content based on date. The issue I'm facing is that the ajax call only works once successfully, and subsequent attempts cause a full page ref ...

Strategies for creating a dynamic progress bar using jQuery and JavaScript

I'm currently working on a project that involves increasing a percentage number while filling up the background color inside it based on the percentage value. The current setup is functional in terms of animating the background, but I need it to dynam ...

Automatically customizable CSS border thickness

Consider the following example of a div element: <div style="height: 10%; width: 20%; border: 1px solid black"> Div Content </div> The div above has its height and width specified in percentages. I would like the border width to adjust a ...

Tips for sending a JavaScript variable to a PHP function in an Ajax URL

Can someone help me with inserting the parent value into the "getFaculties()" function when calling it using Ajax? function ajaxfunction(parent) { $.ajax({ type: 'GET', url: 'Connection.php?getFaculti ...

Conceal content upon clicking with JavaScript

Showing a form after clicking a link can be achieved using this code: $(function () { $('.msg').on('click', function (e) { e.preventDefault(); $(this).next('.msgarea').show(); }); }); <a href="" cl ...

I just obtained the height measurement of a dynamic table - now I must transfer this height value to a different element

Recently, I encountered a situation where I needed to get the height of a dynamic table using code like this: var table = document.getElementById("test"); document.write(table.offsetHeight); However, the challenge arose when I realized that I also needed ...

Exploring the Brilliance of MVC PHP/AJAX

I am currently in the process of developing a PHP website that will showcase statistics derived from an external source. To illustrate how the MVC (Model-View-Controller) architecture will be implemented, I have created this unique diagram. As someone wh ...

Firebase issue: The function ref.once is throwing an Uncaught TypeError and is not recognized

I am attempting to utilize Firebase for both uploading a file and storing it in my database simultaneously. I want to track the number of uploads so that I can rename each file uniquely. While I have successfully uploaded and stored a copy in the database, ...

Replace the current picture with a newly uploaded one and keep it consistent

On my webpage, there is an image that I want to be able to replace by clicking on it and selecting a new image from the file uploader without showing the upload button. Once the new image is uploaded, I'd like it to replace the current image, and for ...

Utilizing a jQuery click event to modify the placement of a table

I have a request regarding the tables within the #middlebox. I would like to be able to rearrange the table positions by clicking on the list items. For instance, if the current order of the tables is starter -> soup -> seafood, clicking on the #seaf ...

"Exploring the power of NodeJS with createServer, dealing with

Can instances of global.request potentially collide in this NodeJS scenario? I have a basic web server set up in NodeJS where I am globally exposing the request that is created: http.createServer(function(req, res) { global.request = req; // do ...