Is there a way to determine if every number in one array is the square of a number in another array?

Define a function comp(a, b) (also called compSame(a, b) in Clojure) that determines whether two arrays a and b have the same elements with the same multiplicities. In this case, "same" means that every element in array b is the square of an element in array a, regardless of the order.

Examples

Valid arrays

a = [121, 144, 19, 161, 19, 144, 19, 11]  
b = [121, 14641, 20736, 361, 25921, 361, 20736, 361]

The function comp(a, b) should return true because each element in b is the square of the corresponding element in a. For example, 121 is the square of 11, 14641 is the square of 121, 20736 is the square of 144, and so on.

Initially, I attempted to compare each item in one array to its squared version in the other array. Here's the code I used:

function comp(array1, array2){
  return array2.every((item)=>{
    let a = array1.indexOf((item ** 2));
    if(a >=0){
      return true;
    } else{
      return false;
    }
  })


}


console.log(comp([121, 144, 19, 161, 19, 144, 19, 11], [121, 14641, 20736, 361, 25921, 361, 20736, 361]));

It is expected that this example will return true, but the function does not work as intended. Additionally, when an empty array is used as the second argument, the function incorrectly returns false.

Answer №1

To create a concise one-liner solution using every and includes, follow this code snippet:

const a = [121, 144, 19, 161, 19, 144, 19, 11]
const b = [121, 14641, 20736, 361, 25921, 361, 20736, 361]

const comp = (a, b) => a.length === b.length && a.every(value => b.includes(value ** 2))

console.log(comp(a, b))

This function is straightforward, as it verifies if both arrays have the same length and if every squared value from array a is present in array b.

Answer №2

If you utilize a Set for storing array2, you can then iterate through each element of array1 and check if its square is present in the Set.

function compareArrays(array1, array2) {
    const set2 = new Set(array2);
    return array1.every(value => set2.has(value * value));
}

console.log(compareArrays([121, 144, 19, 161, 19, 144, 19, 11], [121, 14641, 20736, 361, 25921, 361, 20736, 361]));

Answer №3

Utilizing a unique method to eliminate duplicates

arr1 = [121, 144, 19, 161, 19, 144, 19, 11]  
arr2 = [121, 14641, 20736, 361, 25921, 361, 20736, 361]

function removeDuplicatesAndCompare(arr1, arr2){
 arr1 = [...new Set(arr1)]
 arr2 = new Set(arr2)
 
 return arr1.every(x => arr2.has(x*x))
}

console.log(removeDuplicatesAndCompare(arr1, arr2))

Answer №4

Your solution is very close to passing the test case. The only issue is that the arrays are swapped inside the function:

function comp(array1, array2){
  return array1.every((item)=>{
    let a = array2.indexOf((item ** 2));
    if(a >=0){
      return true;
    } else{
      return false;
    }
  })
}

However, it seems that this solution will return true even if the arrays have different lengths or if elements in the second array are not the squares of elements in the first one, as long as there is some similarity between the two arrays:

console.log(comp([2,4,4,2], [4,16]));
// -> true
console.log(comp([2,4], [4,16, 536]));
// -> true

To address this and improve efficiency by avoiding indexOf or includes, a revised solution that is faithful to the premise is suggested:

function comp2(A, B){
  if(A.length != B.length) return false;
  
  A.sort((a, b) => a-b);
  B.sort((a, b) => a-b);
  
  return A.every((a, i)=>{
    const b = B[i];
    if(a ** 2 == b){
      return true;
    } else{
      return false;
    }
  })
}

console.log(comp2([2,4,4,2], [4,16]));
// -> false
console.log(comp2([2,4], [4,16, 536]));
// -> false

Try out the revised solution here: https://jsfiddle.net/alotropico/9ukmL5g3/13/

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

When using RS256 with JWT, the private key will not be accepted

I've been attempting to generate a JWT using 'jsonwebtoken' with RS256. The keys were generated using the following command: ssh-keygen -t rsa -b 4096 -m PEM -f <filename> The private key output appears as follows: -----BEGIN RSA PRIV ...

Activate PHP using javascript

My PHP script is designed to capture a user's IP address, current webpage, screen resolution, and Date/Time when they visit my website. To implement this tracking functionality on another website, I plan to insert the following line of code: <scr ...

Is AJAX the Solution for Parsing XML: A Mystery?

While trying to parse XML data, I am facing an issue where I can't retrieve the image. Can someone assist me with this problem? Here is my code snippet below or you can view it at http://jsfiddle.net/4DejY/1/: HTML <ul data-role="listview" data-f ...

The behavior of the select menu is erratic when interacting with AJAX

My dropdown menu is populated dynamically based on AJAX response: function populateDropdown(dropdownNum) { // invokeWebService using $.ajax json = invokeWebService("GET", "/webservice/dropwdownOptions"); optionsHtml = ""; $.each(json, function(count, jsO ...

What is the best way to transform a JSON array in text format into a JSON object array using NodeJS or JavaScript?

I have a RESTful API built with Node.JS and ExpressJS. I want to retrieve a JSON array from the FrontEnd and pass it into my API. api.post('/save_pg13_app_list', function (req, res) { var app_list = { list_object: req.body.li ...

Using JQuery to encapsulate the contents of a variable

I am working with a variable that stores HTML retrieved from an HTML5 SQL database. When I use the .append() method to add it to a DOM element, everything works as expected. However, I want to wrap the HTML contents before appending them, so I tried using ...

Expanding a class functionality by incorporating a method through .prototype

My goal is to define a class called "User" and then add a method to the class using the "prototype" keyword. I want the method "who_auto" to be accessible to all future instances of "User". When testing this code in JSFiddle, I encountered the error messa ...

Executing complex queries in mongoose using the $or operator

I'm in search of an efficient way to create clean code for executing multiple complex queries. Within my MongoDB database, I have two collections: followers and events. The first query involves retrieving all followers associated with a specific use ...

How can a passport npm package be utilized within a Node.js application?

Could someone please clarify for me, the purpose of using passport node_package_manager and when it is typically used? I was browsing the web and stumbled upon passport. npm install passport var passport = require('passport'); However, I am s ...

Has anybody successfully implemented the danfojs-node package on an Apple M1 chip?

I encountered an issue when trying to use danfojs-node on a Mac with an M1 chip - it kept crashing due to TensorFlow. I'm curious if anyone has managed to successfully integrate the npm package from this link (https://www.npmjs.com/package/danfojs-nod ...

Difficulty in displaying accurate visuals for Albers US Choropleth Map using d3.js and React

I'm currently troubleshooting my code as I'm only seeing a large square of one color when I attempt to create a colorScale for each element with the class "county" on this Albers US map. The desired outcome is something similar to this project: ...

Array goes blank after being sent to the controller via an AJAX request

I have a class called SOMEOBJECT that includes a list of extras. I am attempting to send data through an AJAX call to my controller. The array received by the MVC controller shows the correct length, but the data inside the array object is empty. Is ther ...

Toggle the checkbox to update the count

I am trying to implement a feature where the user can check a maximum of 4 checkboxes. I have managed to achieve this functionality in the code below. When the user unchecks a box, the count should decrease by one and they should be able to check another c ...

Animate sliding bar to move from the left using jQuery

I am currently experiencing an issue with a sliding animation on mouseover in the navigation. The animation works fine, but the problem arises when I hover over any menu item - the sliding bar starts from the very left instead of starting where the navigat ...

Update the content that corresponds to the regular expression in jQuery

I am on a quest to locate specific content that matches a regular expression across an entire webpage and then replace it with different text. Below is the code I have been utilizing for this task. var reg = /exam+ple/; $("body").html(function () { ...

Using Node, Express, and Swig Template to incorporate variables within HTML attributes

I have been utilizing as the template engine for my Node/Express application. Although I am able to pass data into the template successfully, I am encountering difficulties when trying to use variables. My code snippet looks like this: {% for person in ...

Is it possible to impose a different style on an element from another culture?

I am currently developing a themes library along with a demo page. The challenge I'm facing is that the demo page needs to showcase styles from the library without using all of the elements. For instance, consider the following style in an external s ...

Excellent JavaScript library for capturing screenshots of the entire screen

Is there a good JavaScript library that enables users to take a screenshot of a webpage and customize the size before saving it to their computer? I am specifically looking for a pure JS solution where users can simply click on a button and have a "save a ...

Error message from Angular development server: Channel is reporting an error in handling the response. The UNK/SW_UNREACHABLE options

After recently installing a new Angular app, I encountered an issue while running 'ng serve'. The application initially loads without any problems, but after a few seconds, I started seeing a strange error in the console. Channel: Error in handle ...

Automatically append version number to requests to avoid browser caching with Gulp

When deploying my project, I utilize gulp to build the source files directly on the server. In order to avoid caching issues, a common practice is to add a unique number to the request URL as explained in this article: Preventing browser caching on web app ...