A step-by-step guide to implementing uniform crossover in JavaScript

As someone who is new to javascript, I find the concept of uniform crossover quite confusing.

Could you please explain what uniform crossover entails?https://i.sstatic.net/gqdfw.png

I currently have two arrays that look like this:

var ParentOne = ["j1","j2","j3","j4","j5"];
var ParentTwo = ["j3","j4","j2","j1","j4"];

How can I implement uniform crossover with these arrays?

So far, I've only managed to create a random selection array:

function uniqueRandomInts(upperLimit, amount) {
    var possibleNumbers = _.range(upperLimit + 1);
    var shuffled = _.shuffle(possibleNumbers);
    return shuffled.slice(0, amount);
}

Answer №1

http://codepen.io/anon/pen/BpBOoB

If you're new to JavaScript, the code on the linked CodePen uses ES6 syntax, specifically incorporating destructuring for array manipulation and distinguishing between const and var.

An important scenario not addressed in the existing answer is what happens when the parent arrays are of unequal lengths.

Merging two parents with different sizes using a simple iteration can result in loss of data from the longer parent or errors due to mismatched indices. To handle this, the code first sorts the parents by length, places the shortest as the first parent, creates the child array, and then appends any additional data from the longer parent to complete the child array.

const parentOne = ['j1','j2','j3','j4','j5'];
const parentTwo = ['j3','j4','j2','j1','j4'];

const parentThree = ['j1','j2','j3','j4','j5', '#', '##', '###'];
const parentFour = ['j3','j4','j2','j1','j4'];

const parentFive = ['j1','j2','j3','j4','j5', '#', '##', '###'];
const parentSix = ['j3','j4','j2','j1','j4'];

// Ensure parentOne is the shortest
const fn = (...parents) => {
  // Ensure the shortest parent comes first
  [parents] = parents[1].length < parents[0].length ? [[parents[1], parents[0]]] : [[parents[0], parents[1]]];
  
  // Iterate over the shortest parent
  let child = parents[0].map((item, i) => parents[Math.round(Math.random())][i]);

  // Add remaining elements from the longest parent to the child
  if (parents[1].length > parents[0].length) {
    child = [...child, ...parents[1].slice(parents[0].length)];
  }

  return child;
}

console.log(fn(parentOne, parentTwo));
console.log(fn(parentThree, parentFour));
console.log(fn(parentFive, parentSix));
console.log('---');

Answer №2

If you can assume that both sets of parents have equal lengths, you can simply map the elements randomly to a new array.

var set1 = ["a1", "a2", "a3", "a4", "a5"],
    set2 = ["a3", "a4", "a2", "a1", "a4"],
    result = set1.map(function(_, i) {
        return [set1, set2][Math.round(Math.random())][i];
    });

console.log(result);

Using ES6:

var group1 = ["a1", "a2", "a3", "a4", "a5"],
    group2 = ["a3", "a4", "a2", "a1", "a4"],
    crossover = (s1, s2) => s1.map((_, i) => [s1, s2][Math.round(Math.random())][i]),
    output = crossover(group1, group2);

console.log(output);

Answer №3

If you're looking to generate an output array by randomly choosing elements from two different input arrays, you can achieve this by utilizing a combination of looping and basic randomization techniques.

var ArrayOne = ["apple","banana","cherry","date","fig"],
    ArrayTwo = ["orange","pear","grape","kiwi","melon"],
    arrays = [ArrayOne, ArrayTwo],
    output = []; output.length = ArrayOne.length;

for (var i = 0; i < output.length; i++) {
    output[i] = arrays[Math.round(Math.random())][i]
}

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

Encountering a TypeError when utilizing a npm hashtable within an object definition

I am currently working on setting up a basic stream to read and parse JSON data and then add key-value pairs to a hashtable. My end goal is to create a module that can be utilized in another program, but as I'm troubleshooting, I've hit a roadblo ...

Array Filtering Results in an Empty Array of Objects

I'm currently attempting to filter out all objects from the projects array that do not appear in the savedProjects array, but I'm ending up with an empty result. Could it be that I am approaching the filtering process incorrectly? Here's my ...

Update the picture and assign a class for the currently selected menu or button

I am currently working on creating interactive buttons that change an image when hovered over and clicked. The active button should have a specific class applied to it, which will be removed once another button is clicked. However, I have encountered some ...

Indeed, conditional validation is essential

I have encountered an issue with my schema validation where I am trying to validate one field based on another. For example, if the carType is "SUV", then the maximum number of passengers should be 6; otherwise, it should be 4. However, despite setting u ...

"How can you enhance the performance of JavaScript and CSS in a Chrome Extension without using exclude_matches/globs or excluding domains

I have been in the process of creating a Chrome Extension, and unfortunately, when I tried to make it work on specific URLs, I encountered an issue. While Chrome has options like exclude_matches and exclude_globs for this purpose, there seems to be a bug i ...

Convert file_get_contents from PHP to JavaScript

I previously developed a webpage using php along with a webAPI, but now I am looking to transition it to javascript. The issue at hand: The current site takes about 5-7 seconds to load due to loading a large amount of data, which is not ideal. I want to ...

Utilizing JavaScript to extract JSON data containing unique attributes

I have a JSON object structured like this: "facet_counts": { "facet_pivot": { "title,host,content,anchor,id": [ { "field": "title", "value": "biglobe", "count": 192 } ] }} Usually, I would pa ...

Guide for transmitting a 2D float array from JavaScript to Python using Flask

I am currently working on a web application where users can draw MNIST style digits on a 28*28 p5 canvas. The application then utilizes a CNN that I developed in Python to classify the drawn digit. To achieve this, I have implemented a function that transf ...

Utilizing Mongoose aggregation for counting and grouping operations

I am trying to search for records that correspond to a specific URL but want to return a customized object instead. Here is the model I am working with: const ReactionSchema = mongoose.Schema({ url: { type: String, required: true }, emoji: ...

Automated form with built-in calculations

Whenever a product is selected from the dropdown menu, the price value should be automatically filled in the input field with ID #price. Then, the user can enter the quantity in the input field with ID #quantity, and the total sum of price multiplied by qu ...

What is the best way to ensure that any modifications made to an item in a table are appropriately synced

Utilizing xeditable.js, I am able to dynamically update the content of a cell within a table. My goal is to capture these changes and send them via an HTTP request (PUT) to the backend in order to update the database. Below is the table that can be edited ...

Troubleshooting problems with form submission through the combination of jQuery and Ajax

Hi there! I've got a couple of questions regarding form submission using jQuery and Ajax. Currently, I'm working on validating a login form using jQuery/Ajax requests. My goal is to disable the login submit button after a successful login. Howev ...

Modify the CSS class of a <TD> element depending on the value of the column using JavaScript

I am working on a grid where I need to dynamically change the CSS of one of the columns based on the value from another field in the result set. Instead of simply assigning a class like <td class='class1'> ${firstname} </td> I ...

What are the steps to modify the source of a Javascript audio object?

I'm in the process of developing a customized HTML5 audio player. Within my script, I currently have the following code snippet. var curAudio = new Audio('Audio.mp3'); $("#play").on("click", function(e) { e.preventDefault(); curAudi ...

Is there a way to create a new prettyphoto window by clicking on a link within the original prettyphoto window?

I have an HTML table that is dynamically constructed on the server side using AJAX. The table is displayed using prettyphoto, everything works fine up to this point. However, the last column of the table contains a link that should open an image using pret ...

Best Practices for Angular and Managing Database Access

By now, I have a good understanding that angular.js is a client-side framework, which means any database communication involves sending requests to a server-side script on the server using methods like get/post (with node, php, asp.net, or other technologi ...

"Ensuring Security with Stripe Connect: Addressing Content Security Policy Challenges

Despite using meta tags to address it, the error persists and the Iframe remains non-functional. <meta http-equiv="Content-Security-Policy" content=" default-src *; style-src 'self' 'unsafe-inline'; ...

Gathering user information through Javascript to dynamically populate an HTML document

Looking to utilize JavaScript to extract the value entered in a search bar and then display it in HTML. function pullValue() { var search = document.getElementById("search-bar") } How can the extracted data be inserted into the following: <h3 class ...

Fetch data from Firestore when the page loads using the useEffect hook

Below is the simplified code snippet I am currently using: import { useState, useEffect, useContext } from 'react' import { useRouter } from 'next/router' import { firestore } from './firebase-config' import { getDoc, doc } f ...

Exploring the dynamic loading of components within routes

Just starting out with Vue and experimenting with vue-router, I'm trying my hand at dynamically loading components without relying on additional libraries like webpack. So far, I've set up an index page and a router. Upon initial page load, I not ...