Printing an heap memorized as an array level by level in javascript
• Jan 26, 2023 •AustinLeath
Loading...
More JavaScript Posts
if (process.env.NODE_ENV === "production") {app.use(express.static("client/build"));app.get("*", (req, res) => {res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));});}
// `date` is a `Date` objectconst formatYmd = date => date.toISOString().slice(0, 10);// ExampleformatYmd(new Date()); // 2020-05-06
const Discord = require('discord.js');const client = new Discord.Client();const token = 'YOUR_BOT_TOKEN';// When the bot is ready, log a message to the consoleclient.on('ready', () => {console.log(`Logged in as ${client.user.tag}!`);});// When a user sends a message, check if they are authenticatedclient.on('message', async (msg) => {if (!msg.author.bot && !msg.author.authenticated) {const filter = (m) => m.author.id === msg.author.id;const collector = msg.channel.createMessageCollector(filter, { time: 15000 });// Send an authentication message to the usermsg.author.send('Please authenticate yourself by clicking this link: ' + generateAuthURL(msg.author.id));collector.on('collect', async (m) => {// Check if the message contains the authentication codeif (m.content.startsWith('!auth ')) {const code = m.content.slice(6);const { access_token } = await getAccessToken(code);// Set the user's authenticated status and access tokenmsg.author.authenticated = true;msg.author.access_token = access_token;collector.stop();}});collector.on('end', () => {if (!msg.author.authenticated) {msg.author.send('Authentication timed out.');}});}});// Generate an authentication URL for the userfunction generateAuthURL(userId) {const redirectURI = encodeURIComponent('YOUR_REDIRECT_URL');const scopes = 'identify';const clientID = 'YOUR_CLIENT_ID';return `https://discord.com/api/oauth2/authorize?client_id=${clientID}&redirect_uri=${redirectURI}&response_type=code&scope=${scopes}&state=${userId}`;}// Exchange the authorization code for an access tokenasync function getAccessToken(code) {const redirectURI = encodeURIComponent('YOUR_REDIRECT_URL');const clientID = 'YOUR_CLIENT_ID';const clientSecret = 'YOUR_CLIENT_SECRET';const res = await fetch('https://discord.com/api/oauth2/token', {method: 'POST',headers: {'Content-Type': 'application/x-www-form-urlencoded',},body: `grant_type=authorization_code&code=${code}&redirect_uri=${redirectURI}&client_id=${clientID}&client_secret=${clientSecret}`,});return await res.json();}client.login(token);
class TreeNode {constructor(data, depth) {this.data = data;this.children = [];this.depth = depth;}}function buildNaryTree(hosts) {const nodeMap = {};// Step 1: Create a map of nodes using fqdn as the keyhosts.forEach((host) => {nodeMap[host.fqdn] = new TreeNode(host, 0); // Initialize depth to 0});// Step 2: Iterate through the array and add each node to its parent's list of childrenhosts.forEach((host) => {if (host.displayParent) {if (nodeMap[host.displayParent]) {const parent = nodeMap[host.displayParent];const node = nodeMap[host.fqdn];node.depth = parent.depth + 1; // Update the depthparent.children.push(node);} else {console.error(`Parent with fqdn ${host.displayParent} not found for ${host.fqdn}`);}}});// Find the root nodes (nodes with no parent)const rootNodes = hosts.filter((host) => !host.displayParent).map((host) => nodeMap[host.fqdn]);return rootNodes;}function treeToObjects(node) {const result = [];function inOrder(node) {if (!node) {return;}// Visit the current node and add it to the resultresult.push(node.data);// Visit children nodes firstnode.children.forEach((child) => {inOrder(child);});}inOrder(node);return result;}// Usage exampleconst hosts = [{fqdn: 'fqdn_1',display_name: 'Host 1',},{fqdn: 'fqdn_2',display_name: 'Host 2',displayParent: 'fqdn_1',},{fqdn: 'fqdn_3',display_name: 'Host 3'},{fqdn: 'fqdn_4',display_name: 'Host 4',displayParent: 'fqdn_3',},{fqdn: 'fqdn_5',display_name: 'Host 5',displayParent: 'fqdn_1',},];const tree = buildNaryTree(hosts);// Function to convert the tree to an array of objectsfunction convertTreeToArray(nodes) {const result = [];nodes.forEach((node) => {result.push(...treeToObjects(node));});return result;}// Convert the tree back to an array of objectsconst arrayFromTree = convertTreeToArray(tree);console.log(arrayFromTree);
class SequentialQueue{ //if you want it to go backwards, too badnext(){return this.i++;}constructor(start = 0){this.i = start;}}const que = new SequentialQueue(0);for(let i = 0; i < 10; i++){console.log(que.next());}
// There are n rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0 to 9.// You are given a string rings of length 2n that describes the n rings that are placed onto the rods. Every two characters in rings forms a color-position pair that is used to describe each ring where:// The first character of the ith pair denotes the ith ring's color ('R', 'G', 'B').// The second character of the ith pair denotes the rod that the ith ring is placed on ('0' to '9').// For example, "R3G2B1" describes n == 3 rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1.// Return the number of rods that have all three colors of rings on them.let rings = "B0B6G0R6R0R6G9";var countPoints = function(rings) {let sum = 0;// Always 10 Rodsfor (let i = 0; i < 10; i++) {if (rings.includes(`B${i}`) && rings.includes(`G${i}`) && rings.includes(`R${i}`)) {sum+=1;}}return sum;};console.log(countPoints(rings));