Is there a way to determine if two sets of integers in JavaScript are permutations? For example, given the arrays:
a = [1, 2, 3, 4, 5]
and
b = [2, 3, 5, 1, 4]
I want a function that will return true
if they are permutations of each other.
Is there a way to determine if two sets of integers in JavaScript are permutations? For example, given the arrays:
a = [1, 2, 3, 4, 5]
and
b = [2, 3, 5, 1, 4]
I want a function that will return true
if they are permutations of each other.
To keep track of occurrences, consider using a Map
. Update the count in the map whenever you encounter a matching element in the second array:
function checkPermutation(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
let occurrenceMap = new Map(arr1.map(item => [item, { count: 0 }]));
arr1.forEach(item => occurrenceMap.get(item).count++);
return arr2.every(item => {
let match = occurrenceMap.get(item);
return match && match.count--;
});
}
let arr1 =[1,2,3,4,5,1];
let arr2 = [2,3,1,5,1,4];
console.log(checkPermutation(arr1, arr2));
A simple solution that requires minimal effort:
let x = [5,4,3,2,1],
y = [4,2,3,1,5];
let result = JSON.stringify(x.sort()) === JSON.stringify(y.sort())
console.log(result)
An optimized approach:
function isPermutation (x,y) {
let map = x.reduce((acc,c) => {acc[c] = (acc[c] || 0) + 1; return acc},{})
for (element of y) {
if (!map[element] || map[element] == 0) {
return false;
} else {
map[element]--;
}
}
for (key in map) {
if (map[key] != 0) {
return false;
}
}
return true;
}
console.log(isPermutation([5, 4, 3, 2, 1],[4, 2, 3, 1, 5])) // => true
console.log(isPermutation([1, 2, 3],[3, 2, 2])) // => false
console.log(isPermutation([1,4,5],[5,1,4])) // => true
This method bears similarities to another solution, but it provides a slightly different perspective.
The logic behind this approach involves creating a map from the first array using reduce
, where the value represents the count of occurrences. The second array's elements are then used to subtract counts from the corresponding keys in the map. If a key doesn't exist or its value is already zero, the arrays are not permutations. Finally, the program checks if all values in the map are precisely zero.
let num1 = [1, 2, 3, 4, 5];
let num2 = [2, 3, 5, 1, 4];
return num1.filter(number => !num2.includes(number)).length === 0
This code snippet will yield true if all values in num1
are present in num2
, regardless of their order.
Success:
let x = [7,8,9,2,6,5];
let y = [8,9,5,2,6,7];
console.log(x.sort().toString() === y.sort().toString())
While attempting to fetch data on the client-side using axios in vue.js, I encountered a server-side error with the code 'GET/ 304 --' The reason for this occurrence is unclear to me and I am unsure of how to troubleshoot or resolve it. If I re ...
Just dipping my toes into Typescript and I've encountered a bit of a challenge. I have a generic class that looks like this: export class Sample { a: number; b: number; doSomething(): any { // return something } } My issue ari ...
I am currently working on a chatbot project and would like to add some features such as sending emails and popups. However, I am facing an issue with console logging elements in my code. Here is the snippet of my code: import React from "react"; ...
I'm currently working on a game and facing an issue where my "X" gets deleted when clicking twice on the same tile. I am able to move my "X" around, but the double-click deletion is causing trouble. I attempted using booleans but struggle with them. I ...
I am facing an issue with a form containing multiple input arrays, where I only want certain inputs to be mandatory and apply the class "ignore" to some. The problem is that jQuery validate checks all mandatory inputs. How can I avoid this? Here is a simp ...
I've been working on a Vue macro application for specific functionality in NetSuite. Since I can't utilize npm or other package installers, I've resorted to using CDN. The Vue app and Ant Design are both functioning properly, but the issue l ...
I have a file called common.js which holds all the necessary variables and methods used in my App, including a nav-bar module (nav-bar.js) among others. Typically, every module in my app will import the entire common.js module, except for the login module ...
Greetings to all who venture across the vast expanse of the internet! I am currently delving into the realm of typescript-code and transcending it into javascript. With the utilization of both --inlineSourceMap and --inlineSources flags, I have observed t ...
After conducting research, it has come to my attention that there are numerous document conflicts with couchdb. While exploring a potential solution in Updating a CouchDB document in nano, I discovered the following steps: Retrieve the document Store th ...
Attempting to utilize @types/stats with @angular/cli following the guidance at https://github.com/angular/angular-cli/wiki/stories-third-party-lib. However, encountering a tslint error when trying to import * as STATS from 'stats.js'. [ts] Modul ...
I am in the process of creating a bespoke react component library to be shared across various applications. To build this library, I am utilizing rollup and referencing resources such as this blog post along with others: https://dev.to/alexeagleson/how-to- ...
Here is the index.html code for a simple VueJS app that includes a widget from netvibes.com. The widget code is added in the html file and functioning properly. <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC " ...
Can someone help me trigger the modal('show') event using PHP code? I attempted the following: if(isset($_POST['Edit'])){ echo "<script> $('#Modal').modal('show') </script>"; } I tested this code, but i ...
I am encountering an issue in my React application where I am trying to set the state of a child component using this.props, but it is showing an error saying props is undefined. It seems like 'this' is not referencing the current object correctl ...
Currently, I am working on a project involving html and javascript. My issue lies in displaying multiple options on the same webpage without switching pages. Essentially, I have a plot and a few buttons on one page, and when a user clicks on any of these b ...
Can the file size of an uploading file be determined using Javascript without requiring an ActiveX object? The solution should work across all web browsers. ...
After exploring various examples of how to show/hide divs with a JavaScript timeout, I am still unable to resolve my specific issue. I currently have six divs that I want to cycle through sequentially every 10 seconds, starting with div #one. Although my ...
There is a feature to toggle between displaying "more" or "less" text, but currently the @click event affects all elements causing them to show all the text at once. I realize that I need to pass a unique value to distinguish each element, but I am curren ...
I am new to Javascript and Node JS. I have a challenge of uploading a zip file containing only pictures and creating permanent links for these pictures. Currently, I can upload a zip file and extract its contents using the following code snippet: var expr ...
Is there a way to automatedly extract CSS class definitions from Chrome Developer Tools? I want to retrieve the styles defined in a specific class name, similar to how it is displayed in the Styles tab on the right-hand side. I know about the getComputedS ...