Utilize various algorithms to identify the predominant object based on multiple parameters in TypeScript

Having collected student profiles with scores in various subjects such as physics, chemistry, and math, I am looking to identify a group of dominant students based on their individual subject scores. For instance:

let students = [{name: "A", phy: 70, chem: 80, math: 90},
              {name: "B", phy: 75, chem: 85, math: 60},
              {name: "C", phy: 78, chem: 81, math: 92},
              {name: "D", phy: 75, chem: 85, math: 55}]; 

A student is considered dominant over another if they meet the following two conditions: 1. student_1 >= student_2 for all parameters 2. student_1 > student_2 for at least one parameter

I initially attempted to use a nested loop, which resulted in a brute-force algorithm. I introduced a new parameter called "passed" to keep track of dominance. Below is the code:


let students = [{ name: "A", phy: 70, chem: 80, math: 90, passed: true },
{ name: "B", phy: 75, chem: 85, math: 60, passed: true },
{ name: "C", phy: 78, chem: 81, math: 92, passed: true },
{ name: "D", phy: 75, chem: 85, math: 55, passed: true }];

let weak_student: any;

// logic and code here...

console.log(students);

After running the code, I identified students A and D as having their "passed" flag set to false. Now, I am looking to achieve the same results using alternative algorithms such as Divide & Conquer, Nearest Neighbor, Branch & Bound, or any other efficient methods. I also aim to compare the time and space complexity of the different algorithms for larger datasets.

Answer №1

To organize the array, you can sort it by extracting the keys, calculating the difference between all values, and standardizing the value to [-1, 0, 1] through the use of Math.sign. Then, add up the values and return this total as the sorting result.

The group at the top will consist of entries with the highest values.

let students = [{ name: "A", phy: 70, chem: 80, math: 90 }, { name: "B", phy: 75, chem: 85, math: 60 }, { name: "C", phy: 78, chem: 81, math: 92 }, { name: "D", phy: 75, chem: 85, math: 55 }];

students.sort((a, b) => ['phy', 'chem', 'math']
    .map(k => Math.sign(b[k] - a[k]))
    .reduce((a, b) => a + b)
);

console.log(students);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Prevent redundancy by caching svg icons to minimize repeated requests

I have a collection of info cards on my page, each featuring its own unique illustration along with a set of common icons (SVG) for options such as edit, delete, and more. While the illustrations vary from card to card, the icons remain consistent across a ...

A function in Typescript designed to take in two objects that possess identical keys

I am looking to define a function that takes two parameters, each being an object. These objects have the same keys, but the data types of the values under those keys should be different (yet the same within each object). I attempted to achieve this using ...

Issue with Ionic Native File: File.writeFile function - file is not being created and there is no callback response

I've exhausted all the different solutions I could find, but unfortunately, the file isn't getting saved and nothing seems to be happening. The callback functions aren't being called - neither success nor error. Here are the solutions I&apo ...

TS2304: 'Omit' is a mysterious being that cannot be located

Encountered an issue while compiling my Angular project. This is a project that has remained unchanged for some time and is built daily by Jenkins. However, today it started failing and I'm struggling to determine the cause. ERROR in [at-loader] ./no ...

Using React.Fragment in VS Code with TypeScript error 2605 while having checkJs enabled

While utilizing the JS type checking feature in VScode, I encountered an issue with React.Fragment that is being linted with an error: JSX element type 'ReactElement<any>' is not a constructor function for JSX elements. Type 'ReactEle ...

Mongodb Dynamic Variable Matching

I am facing an issue with passing a dynamic BSON variable to match in MongoDB. Here is my attempted solutions: var query = "\"info.name\": \"ABC\""; and var query = { info: { name: "ABC" } } However, neither of thes ...

Issue: MUI Autocomplete and react-hook-form failing to show the chosen option when using retrieved information

The MUI Autocomplete within a form built using react hook form is causing an issue. While filling out the form, everything works as expected. However, when trying to display the form with pre-fetched data, the Autocomplete only shows the selected option af ...

Testing Angular HTTP error handlers: A comprehensive guide

Below, you will find an example of code snippet: this.paymentTypesService.updatePaymentTypesOrder('cashout', newOrder).subscribe(() => { this.notificationsService.success( 'Success!', `Order change saved successfully`, ...

The ts-jest node package's spyOn method fails to match the specified overload

Currently, I'm exploring the usage of Jest alongside ts-jest for writing unit tests for a nodeJS server. My setup is quite similar to the snippet below: impl.ts export const dependency = () => {} index.ts import { dependency } from './impl.t ...

How can I change the CSS class of my navbar component in Angular 2 from a different component?

Here is a custom progress bar component I created: @Component ({ selector: 'progress-bar', templateUrl: './progress-bar.component.html', styleUrls: ['./progress-bar.component.css'] }) export class ProgressBarComponent ...

Exclude the key-value pair for any objects where the value is null

Is there a way to omit one key-value pair if the value is null in the TypeScript code snippet below, which creates a new record in the Firestore database? firestore.doc(`users/${user.uid}`).set({ email: user.email, name: user.displayName, phone: ...

Sharing markdown through a REST API and displaying it in the frontend (React): Tips and Tricks

I'm facing a challenge while attempting to convert a markdown file, send it through a rest API, and display it on the frontend. During the conversion process, I noticed that certain elements, such as newlines, were not being preserved. Can someone ad ...

Using the `forwardRef` type in TypeScript with JSX dot notation

Currently, I am exploring the different types for Dot Notation components using forwardRef. I came across an example that showcases how dot notation is used without forwardRef: https://codesandbox.io/s/stpkm This example perfectly captures what I want to ...

What is the best way to retry an action stream observable in Angular/RxJS after it fails?

Kindly disregard the variable names and formatting alterations I've made. I've been attempting to incorporate RxJS error handling for an observable that triggers an action (user click) and then sends the request object from our form to execute a ...

Encountering difficulty when integrating external JavaScript libraries into Angular 5

Currently, I am integrating the community js library version of jsplumb with my Angular 5 application (Angular CLI: 1.6.1). Upon my initial build without any modifications to tsconfig.json, I encountered the following error: ERROR in src/app/jsplumb/jspl ...

Angular CLI: Trouble with building in production mode due to errors in "Abstract class" while using Angular 4

Within my app.resolver.service.ts file, I have an Abstract class. During development, everything works fine, but I encounter an error in the PROD build. import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/commo ...

Application fails to launch after disabling unsafe-eval in the restricted Content Security Policy settings

Description My application is facing issues due to having a restricted CSP policy that does not allow unsafe-eval for scripts. When I add a Content-Security-Policy header without unsafe-eval, my application fails to load. Minimal Reproduction The restric ...

Module 'bcryptjs' could not be located

Recently, I added the @types/bcryptjs package to my Node.js project. Initially, there were no issues with importing it. However, when I attempted to use it in my code by including the line: console.log(bcrypt.hashSync(req.body.password)) I encountered an ...

SQL Exception: The value for the first parameter is not defined

I'm encountering an issue with a SqlError while trying to retrieve data from my database. It seems like the problem is within my fetchData function where I might not be passing the two parameters (startDate and endDate) correctly. The specific SqlErr ...

Is there a way to modify a suffix snippet and substitute the variable in VS Code?

While working on my Java project in VS Code, I stumbled upon some really helpful code snippets: suffix code snippets Once I type in a variable name and add .sysout, .cast, or similar, the snippet suggestion appears. Upon insertion, it translates to: res ...