Seeking assistance with an algorithm

I have created a website that randomly generates the color of a div based on this array:

let pastelColor = [
    'ffaacc','ffbbcc','ffcccc','ffddcc','ffeecc','ffffcc','ffaadd','ffbbdd','ffccdd','ffdddd','ffeedd','ffffdd',
    'ffaaee','ffbbee','ffccee','ffddee','ffeeee','ffffee','ffaaff','ffbbff','ffccff','ffddff','ffeeff','ffffff',
    'ccaaff','ccbbff','ccccff','ccddff','cceeff','ccffff','ccaaee','ccbbee','ccccee','ccddee','cceeee','ccffee',
    'ccaadd','ccbbdd','ccccdd','ccdddd','cceedd','ccffdd','ccaacc','ccbbcc','cccccc','ccddcc','cceecc','ccffcc'
]

I experimented with various algorithms using Case Switch, but the function ended up taking too much space. I am curious if there is a more efficient algorithm to generate this array.

Thank you to anyone who can provide an answer!

Answer №1

Is it possible for an algorithm to generate this particular array?

Certainly. If you require the array to be in that specific order:

let pastelColor = Array.from("abcdef".repeat(8), (ch, i) => 
    (([a,...r]) => a+a+ch+ch+r[~~(i/6)%4].repeat(2))(i<24 ? "fcdef" : "cfedc")
);

console.log(pastelColor);

If your main interest is not on the array with color codes but rather on generating a random color from it, then:

let pick = str => str[Math.floor(Math.random() * str.length)].repeat(2);
let pastelColor = pick("cf") + pick("abcdef") + pick("cdef");

console.log(pastelColor);

Answer №2

To populate the array with a converted hexadecimal color using randomly generated integers within the range of 0 to 255, follow these steps:

const getRandomInt = (min, max) => {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min) + min);
}

const getRandomColorUnit = () => {
    const color = getRandomInt(0, 256).toString(16);
    if (color.length < 2) return '0' + color;
    return color;
};

const getRandomColor = () => `#${getRandomColorUnit()}${getRandomColorUnit()}${getRandomColorUnit()}`;

const colors = new Array(100).fill(0).map(getRandomColor);

console.log(colors);

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

Utilize JavaScript to parse JSON response data, calculate the average of a specified field while keeping track of

The data returned from the API call is structured as follows: var array = {"scores":[ { userid: "1", mark: 4.3 }, { userid: "1", mark: 3.8 }, { userid: "2", mark: 4.6 }, { userid: "2&quo ...

Determine the proportion of points using a Javascript algorithm

I am looking for a way to dynamically update a progress bar based on the points I have accumulated. The progress bar has 3 different levels, each with a specific point target that needs to be reached before progressing to the next level. The cost breakdown ...

Displaying an array as a column yields no visible results

Yesterday I posted a query regarding displaying an array with commas as columns. You can view the original question here. Today, my progress is as follows: <?php require_once("dbconnection.php"); ?> <?php $sql = "SELECT amount, ingredients FROM ...

How to use JavaScript to toggle datalabels on Highcharts?

Is it possible to make Highcharts show datalabels for a specific category when clicking on the legend item? I've attempted to enable datalabels using the code below, but it hasn't worked: chart.series[0].data.dataLabels.enabled = true; You can ...

A javascript text slider that dynamically updates text content sourced from PHP

Currently, I am in the process of developing a project that involves creating a dynamic slideshow of testimonials for my website. To achieve this, I am utilizing PHP and MySQL for the database backend. My goal is to use pure JavaScript to efficiently showc ...

Is there a method to reference the HTML element without utilizing the tagname?

Here's a straightforward query: Is it possible to reference the HTML element in JavaScript without using: document.getElementsByTagName('HTML')[0] If you want to access the body element, you can use: document.body Any simpler methods ava ...

ExpressJS encountered an error due to an unsupported MIME type ('text/html') being used as a stylesheet MIME type

Whenever I start my NodeJS server and enter localhost:8080, I encounter the mentioned error while the page is loading. The head section of my index.html file is provided below. It's puzzling to me why this error is happening, considering that my index ...

AJAX Username verification failing to validate

Working with PHP and MySQL, I created a basic form which includes a textfield for the username and a submit button. The page is named checkusername.php. Additionally, I implemented an AJAX function for handling this process. Subsequently, there is another ...

Accessing the req property beyond the route endpoints

const express = require('express'); const router = module.exports = express.Router(); const server = require("http").Server(express); const io = require("socket.io")(server); server.listen(5000); // Need a way to access user.id here router.g ...

How can one determine if the browser has language support?

How can I determine if a specific language is supported or installed on the user's machine using PHP or Javascript for my multilingual website? I would like to display a message to the user if the desired language is not available. Sincerely, Mark. ...

Steps for showing an error prompt when input is invalid:

In my Vue 3 application, I have implemented a simple calculator that divides a dividend by a divisor and displays the quotient and remainder. Users can adjust any of the four numbers to perform different calculations. <div id="app"> <inp ...

Simple HTML files on a local server are having trouble loading images and JavaScript, yet the CSS is loading

Having worked in web design for quite some time, I recently began working on a basic Angular app that is meant to be very simple. For this project, I am only using the angular files and a single html file as the foundation. As I started setting up the bas ...

Make sure that the iframe loads the next page with enough force to break out

My dilemma involves an iframe that loads the new tab page. When a user clicks on the thumbnail, it opens within the iframe. My goal is to have any subsequent load in the iframe redirected to window.top. Is there a way to achieve this without manually setti ...

Making alterations to the HTML code of a Tumblr theme in order to eliminate specific

Here is my custom Tumblr domain URL: http://intchauhan.com/ I would like to eliminate the "Follow intchauhan" and "tumblr." buttons located on the right side. Below is the HTML of the theme: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional// ...

Tips for handling catch errors in fetch POST requests in React Native

I am facing an issue with handling errors when making a POST request in React Native. I understand that there is a catch block for network connection errors, but how can I handle errors received from the response when the username or password is incorrec ...

What is the best way to dynamically disable choices in mat-select depending on the option chosen?

I was recently working on a project that involved using mat-select elements. In this project, I encountered a specific requirement where I needed to achieve the following two tasks: When the 'all' option is selected in either of the mat-select e ...

What is the best way to integrate cross-env with Expo?

I'm currently working on an expo app and hoping to integrate cross-env with it. To make this possible, I modified the start script in package.json to "cross-env LOCAL_IP_ADDRESS=TEST expo start", but unfortunately, the environment variable ...

Is there a way to update the options value using AngularJS?

One common issue that many people (myself included) are facing is with the ng-options directive in AngularJS when populating a <select> tag. Setting the value for an option seems to be unclear based on the documentation. For example, using ng-option ...

Having trouble retrieving JSON Data with PHP and Angular JS?

I am using AngularJS to fetch JSON-encoded data by passing an ID. Below is my controller: dhmsApp.controller('dhmsDetailsView',function($scope,$http, $routeParams){ $http.get("include/detailViewBg.php", {params: {id: $routeParams.id}}) .s ...

The jQuery each function in combination with the index function allows for

I'm struggling to make this jQuery script work properly: $(document).on('knack-scene-render.scene_126', function() { $('#view_498 > div.kn-list-content.columns.is-multiline').each(function(index) { if ($(this).eq(inde ...