├── 3D Earth Rotation.html
├── 3D Earth Rotation
├── index.html
└── script.js
├── Audio_Music_Player.js
├── BMI_Calculator.js
├── Camera_Color_Detection_and_Tracking_with_OpenCV.js
├── Coding_Challenges.js
├── Color Game
├── index.html
└── script.js
├── Complex_Number_Calculator.js
├── Complex_Square_Root_Calculator.js
├── Drug_Management_System.js
├── Electric Circuit Visualization
├── index.html
├── script.js
└── style.css
├── Max_Heap_Priority_Queue.js
├── Microsoft_Windows_10_Logo.html
├── Planetary_Weights.js
├── Pose_Estimation
├── index.html
├── sketch.js
└── style.css
├── README.md
├── Real-time_Object_Detection_and_Tracking.js
├── Real-time_Object_Tracking.js
├── Reverse_Array_Elements_Program.js
├── Rock_Paper_Scissors_Game.js
├── Rotated_Array_Search.js
├── Satellite_Orbit_Visualization_in_3D_with_TLE_Data.js
├── Satellite_Orbits.js
├── Satellite_Updates.js
├── Satellite_Updates_Projects.js
├── Singly_Linked_List_Traversal.js
├── Sort_Income_List.js
├── Sudoku_Solver.js
├── Symbolic_Mathematics_with_Sympy.js
├── Voter_Eligibility_Check.js
├── armstrong_number.js
├── bit_manipulation.js
├── english_voice_assistant.js
├── factorial.js
├── kaprekar_constant.js
├── knapsack.js
├── minimum_difficulty_of_a_job_schedule.js
├── most_occuring_character.js
├── palindrome.js
├── sorting_array.js
└── wifi_password.js
/3D Earth Rotation.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | 3D Earth Rotation
6 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
51 |
52 |
53 |
--------------------------------------------------------------------------------
/3D Earth Rotation/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | 3D Earth Rotation
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/3D Earth Rotation/script.js:
--------------------------------------------------------------------------------
1 | const FRAME_WIDTH = 800;
2 | const FRAME_HEIGHT = 600;
3 | const ROTATION_INTERVAL = 20;
4 |
5 | function drawFrame(ctx, frame) {
6 | ctx.clearRect(0, 0, FRAME_WIDTH, FRAME_HEIGHT);
7 | ctx.save();
8 | ctx.translate(FRAME_WIDTH / 2, FRAME_HEIGHT / 2);
9 | ctx.rotate((frame * Math.PI) / 180);
10 |
11 | // Draw the Earth marker (blue square)
12 | ctx.fillStyle = 'blue';
13 | ctx.fillRect(-50, -50, 100, 100);
14 |
15 | ctx.restore();
16 | }
17 |
18 | function rotateEarth() {
19 | const canvas = document.getElementById('canvas');
20 | const ctx = canvas.getContext('2d');
21 | let frame = 0;
22 |
23 | function updateRotation() {
24 | drawFrame(ctx, frame);
25 | frame += 2;
26 | if (frame > 360) {
27 | frame = 0;
28 | }
29 | }
30 |
31 | setInterval(updateRotation, ROTATION_INTERVAL);
32 | }
33 |
34 | rotateEarth();
35 |
--------------------------------------------------------------------------------
/Audio_Music_Player.js:
--------------------------------------------------------------------------------
1 | const { dialog } = require('electron').remote;
2 | const { app } = require('electron');
3 | const path = require('path');
4 | const { spawn } = require('child_process');
5 |
6 | // Function to select a file
7 | function selectFile() {
8 | const file = dialog.showOpenDialogSync({
9 | title: 'Select an audio file',
10 | filters: [
11 | { name: 'Audio Files', extensions: ['mp3', 'wav', 'ogg'] }
12 | ]
13 | });
14 |
15 | if (file && file.length > 0) {
16 | return file[0];
17 | }
18 | return '';
19 | }
20 |
21 | // Function to play the selected file
22 | function playMusic(filePath) {
23 | const player = spawn('ffplay', ['-nodisp', '-autoexit', filePath]);
24 | player.on('exit', () => {
25 | player.kill();
26 | });
27 | }
28 |
29 | // Function to stop the music
30 | function stopMusic() {
31 | spawn('taskkill', ['/IM', 'ffplay.exe', '/F']);
32 | }
33 |
34 | let filePath = selectFile();
35 | if (filePath) {
36 | playMusic(filePath);
37 | }
38 |
39 | while (true) {
40 | console.log('1. Select a file');
41 | console.log('2. Stop music');
42 | console.log('3. Exit');
43 | const choice = prompt('Enter your choice: ');
44 |
45 | switch (choice) {
46 | case '1':
47 | filePath = selectFile();
48 | if (filePath) {
49 | playMusic(filePath);
50 | }
51 | break;
52 | case '2':
53 | stopMusic();
54 | break;
55 | case '3':
56 | app.quit();
57 | break;
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/BMI_Calculator.js:
--------------------------------------------------------------------------------
1 | const readline = require('readline');
2 |
3 | const rl = readline.createInterface({
4 | input: process.stdin,
5 | output: process.stdout
6 | });
7 |
8 | rl.question("Enter your height in centimeters: ", (height) => {
9 | rl.question("Enter your weight in Kg: ", (weight) => {
10 | height = parseFloat(height);
11 | weight = parseFloat(weight);
12 |
13 | height = height / 100;
14 | const bmi = weight / (height * height);
15 |
16 | console.log(`Your Body-Mass index is: ${bmi.toFixed(2)}`);
17 |
18 | if (bmi > 0) {
19 | if (bmi <= 16) {
20 | console.log("You are severely under-weight.");
21 | } else if (bmi <= 18.5) {
22 | console.log("You are under-weight.");
23 | } else if (bmi <= 25) {
24 | console.log("You are Healthy.");
25 | } else if (bmi <= 30) {
26 | console.log("You are overweight.");
27 | } else {
28 | console.log("You are severely overweight.");
29 | }
30 | } else {
31 | console.log("Please enter valid details.");
32 | }
33 |
34 | rl.close();
35 | });
36 | });
37 |
--------------------------------------------------------------------------------
/Camera_Color_Detection_and_Tracking_with_OpenCV.js:
--------------------------------------------------------------------------------
1 | let videoElement = document.createElement('video');
2 | videoElement.width = 640;
3 | videoElement.height = 480;
4 | document.body.appendChild(videoElement);
5 |
6 | let canvasElement = document.createElement('canvas');
7 | canvasElement.width = 640;
8 | canvasElement.height = 240;
9 | document.body.appendChild(canvasElement);
10 | let ctx = canvasElement.getContext('2d');
11 |
12 | function emptyFunction() {
13 | let threshold1 = cv.getTrackbarPos("Threshold1", "Parameters");
14 | let threshold2 = cv.getTrackbarPos("Threshold2", "Parameters");
15 | let area = cv.getTrackbarPos("Area", "Parameters");
16 | console.log("Threshold1:", threshold1);
17 | console.log("Threshold2:", threshold2);
18 | console.log("Area:", area);
19 | }
20 |
21 | cv.onRuntimeInitialized = () => {
22 | let cap = new cv.VideoCapture(videoElement);
23 | let frame = new cv.Mat();
24 | let imgHsv = new cv.Mat();
25 | let mask = new cv.Mat();
26 | let result = new cv.Mat();
27 | let hStack = new cv.Mat();
28 |
29 | cv.namedWindow("HSV");
30 | cv.resizeWindow("HSV", 640, 240);
31 | cv.createTrackbar("HUE Min", "HSV", 0, 179, emptyFunction);
32 | cv.createTrackbar("HUE Max", "HSV", 179, 179, emptyFunction);
33 | cv.createTrackbar("SAT Min", "HSV", 0, 255, emptyFunction);
34 | cv.createTrackbar("SAT Max", "HSV", 255, 255, emptyFunction);
35 | cv.createTrackbar("VALUE Min", "HSV", 0, 255, emptyFunction);
36 | cv.createTrackbar("VALUE Max", "HSV", 255, 255, emptyFunction);
37 |
38 | function processVideo() {
39 | cap.read(frame);
40 |
41 | if (frame.empty()) {
42 | console.log("Failed to capture frame from the camera.");
43 | return;
44 | }
45 |
46 | cv.cvtColor(frame, imgHsv, cv.COLOR_RGBA2RGB);
47 | cv.cvtColor(imgHsv, imgHsv, cv.COLOR_RGB2HSV);
48 |
49 | let hMin = cv.getTrackbarPos("HUE Min", "HSV");
50 | let hMax = cv.getTrackbarPos("HUE Max", "HSV");
51 | let sMin = cv.getTrackbarPos("SAT Min", "HSV");
52 | let sMax = cv.getTrackbarPos("SAT Max", "HSV");
53 | let vMin = cv.getTrackbarPos("VALUE Min", "HSV");
54 | let vMax = cv.getTrackbarPos("VALUE Max", "HSV");
55 |
56 | let lower = new cv.Scalar(hMin, sMin, vMin, 0);
57 | let upper = new cv.Scalar(hMax, sMax, vMax, 255);
58 |
59 | cv.inRange(imgHsv, lower, upper, mask);
60 | cv.bitwise_and(frame, frame, result, mask);
61 |
62 | cv.cvtColor(mask, mask, cv.COLOR_GRAY2BGR);
63 |
64 | cv.hconcat([frame, mask, result], hStack);
65 |
66 | cv.imshow('Horizontal Stacking', hStack);
67 | requestAnimationFrame(processVideo);
68 | }
69 |
70 | videoElement.onloadedmetadata = () => {
71 | videoElement.play();
72 | requestAnimationFrame(processVideo);
73 | };
74 | };
75 |
--------------------------------------------------------------------------------
/Coding_Challenges.js:
--------------------------------------------------------------------------------
1 | //-------------------------------------------------------------JavaScript Coding Challenges-----------------------------------------------------
2 |
3 | // JavaScript Coding Challenges on Numbers
4 | // Write a program in JavaScript to -
5 |
6 | // 1. Convert decimal numbers to octal numbers.
7 | // 2. Reverse an integer.
8 | // 3. Print the Fibonacci series using the recursive method.
9 | // 4. Return the Nth value from the Fibonacci sequence.
10 | // 5. Find the average of numbers (with explanations).
11 | // 6. Convert Celsius to Fahrenheit.
12 |
13 | //----------------------------------------------------------------Solution of Problem:----------------------------------------------------------
14 |
15 | // 1. Converting Decimal Numbers to Octal Numbers:
16 |
17 | let decimal_number = 25;
18 | let octal_number = [];
19 |
20 | while (decimal_number > 0) {
21 | octal_number.push(decimal_number % 8);
22 | decimal_number = Math.floor(decimal_number / 8);
23 | }
24 |
25 | process.stdout.write("Octal number: ");
26 |
27 | for (let i = octal_number.length - 1; i >= 0; i--) {
28 | process.stdout.write(octal_number[i].toString());
29 | }
30 |
31 | //----------------------------------------------------------------------------------------------------------------------------------------------
32 |
33 | // 2. Reversing an Integer:
34 |
35 | let number = 12345;
36 | let reversed_number = 0;
37 |
38 | while (number !== 0) {
39 | reversed_number = reversed_number * 10 + number % 10;
40 | number = Math.floor(number / 10);
41 | }
42 |
43 | console.log(reversed_number);
44 |
45 | //----------------------------------------------------------------------------------------------------------------------------------------------
46 |
47 | // 3. Printing the Fibonacci Series using Recursion:
48 |
49 | function fibonacci(n) {
50 | if (n <= 1) {
51 | return n;
52 | } else {
53 | return fibonacci(n - 1) + fibonacci(n - 2);
54 | }
55 | }
56 |
57 | let n = 10;
58 | process.stdout.write("Fibonacci series: ");
59 |
60 | for (let i = 0; i < n; i++) {
61 | process.stdout.write(fibonacci(i) + " ");
62 | }
63 |
64 | //----------------------------------------------------------------------------------------------------------------------------------------------
65 |
66 | // 4. Returning the Nth Value from the Fibonacci Sequence:
67 |
68 | function fibonacci(n) {
69 | if (n <= 1) {
70 | return n;
71 | } else {
72 | return fibonacci(n - 1) + fibonacci(n - 2);
73 | }
74 | }
75 |
76 | let n = 10;
77 | let fibonacci_number = fibonacci(n);
78 | console.log(fibonacci_number);
79 |
80 | //----------------------------------------------------------------------------------------------------------------------------------------------
81 |
82 | // 5. Finding the Average of Numbers:
83 |
84 | let numbers = [10, 20, 30, 40, 50];
85 | let sum = numbers.reduce((acc, curr) => acc + curr, 0);
86 | let average = sum / numbers.length;
87 | console.log("Average: " + average);
88 |
--------------------------------------------------------------------------------
/Color Game/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Color Game
5 |
46 |
47 |
48 |
49 |
Game Description: Enter the color of the words displayed below. And keep in mind not to enter the word text itself
50 |
Your Score: 0
51 |
52 |
Game Ends in: -
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/Color Game/script.js:
--------------------------------------------------------------------------------
1 | const COLORS = ["Red", "Orange", "White", "Black", "Green", "Blue", "Brown", "Purple", "Cyan", "Yellow", "Pink", "Magenta"];
2 |
3 | let score = 0;
4 | let displayedWordColor = "";
5 | let gameRunning = false;
6 |
7 | function printScore() {
8 | document.getElementById("game-score").textContent = "Your Score: " + score;
9 | }
10 |
11 | function printTimeLeft(secondsLeft) {
12 | document.getElementById("time-left").textContent = "Game Ends in: " + secondsLeft + "s";
13 | }
14 |
15 | function printGameDescription() {
16 | document.getElementById("game-description").textContent = "Game Description: Enter the color of the words displayed below. And keep in mind not to enter the word text itself";
17 | }
18 |
19 | function startGame() {
20 | if (!gameRunning) {
21 | gameRunning = true;
22 | score = 0;
23 | displayedWordColor = "";
24 | document.getElementById("color-entry").value = "";
25 | document.getElementById("color-entry").focus();
26 | printGameDescription();
27 | printScore();
28 | printTimeLeft(60);
29 | nextWord();
30 | startTimer();
31 | }
32 | }
33 |
34 | function stopGame() {
35 | gameRunning = false;
36 | clearInterval(timerInterval);
37 | document.getElementById("displayed-words").textContent = "";
38 | }
39 |
40 | function nextWord() {
41 | if (gameRunning) {
42 | const displayedWordText = COLORS[Math.floor(Math.random() * COLORS.length)];
43 | displayedWordColor = COLORS[Math.floor(Math.random() * COLORS.length)];
44 | document.getElementById("displayed-words").textContent = displayedWordText;
45 | document.getElementById("displayed-words").style.color = displayedWordColor;
46 | }
47 | }
48 |
49 | function checkWord() {
50 | if (gameRunning) {
51 | const inputColor = document.getElementById("color-entry").value.trim().toLowerCase();
52 | if (inputColor === displayedWordColor.toLowerCase()) {
53 | score++;
54 | printScore();
55 | }
56 | document.getElementById("color-entry").value = "";
57 | nextWord();
58 | }
59 | }
60 |
61 | function startTimer() {
62 | let secondsLeft = 60;
63 | printTimeLeft(secondsLeft);
64 | timerInterval = setInterval(() => {
65 | secondsLeft--;
66 | if (secondsLeft >= 0) {
67 | printTimeLeft(secondsLeft);
68 | } else {
69 | stopGame();
70 | }
71 | }, 1000);
72 | }
73 |
74 | document.getElementById("start-button").addEventListener("click", startGame);
75 | document.getElementById("reset-button").addEventListener("click", stopGame);
76 | document.getElementById("color-entry").addEventListener("keypress", (event) => {
77 | if (event.key === "Enter") {
78 | checkWord();
79 | }
80 | });
81 |
--------------------------------------------------------------------------------
/Complex_Number_Calculator.js:
--------------------------------------------------------------------------------
1 | class Complex {
2 | constructor() {
3 | this.real = 0.0;
4 | this.imag = 0.0;
5 | }
6 |
7 | set_data() {
8 | this.real = parseFloat(prompt("Enter the real value of the complex number: "));
9 | this.imag = parseFloat(prompt("Enter the imaginary value of the complex number: "));
10 | }
11 |
12 | add(a, b, c, d) {
13 | this.real = a + c;
14 | this.imag = b + d;
15 | }
16 |
17 | subtract(a, b, c, d) {
18 | this.real = a - c;
19 | this.imag = b - d;
20 | }
21 |
22 | multiply(a, b, c, d) {
23 | this.real = a * c - b * d;
24 | this.imag = a * d + b * c;
25 | }
26 |
27 | divide(a, b, c, d) {
28 | this.real = (a * c + b * d) / (c * c + d * d);
29 | this.imag = (b * c - a * d) / (c * c + d * d);
30 | }
31 |
32 | get_data() {
33 | if (this.imag >= 0) {
34 | console.log(`${this.real}+${this.imag}i`);
35 | } else {
36 | console.log(`${this.real}${this.imag}i`);
37 | }
38 | }
39 | }
40 |
41 | const x1 = new Complex();
42 | const x2 = new Complex();
43 | const addition = new Complex();
44 | const subtraction = new Complex();
45 | const multiplication = new Complex();
46 | const division = new Complex();
47 |
48 | x1.set_data();
49 | x2.set_data();
50 |
51 | console.log("Complex number 1 is:");
52 | x1.get_data();
53 | console.log("Complex number 2 is:");
54 | x2.get_data();
55 |
56 | let ans = 1;
57 | while (ans === 1) {
58 | console.log("Choose the operation to perform:");
59 | console.log("1. Addition\n2. Subtraction\n3. Multiplication\n4. Division");
60 | const a = parseInt(prompt());
61 |
62 | if (a === 1) {
63 | addition.add(x1.real, x1.imag, x2.real, x2.imag);
64 | console.log("Addition of Complex 1 and Complex 2 is:");
65 | addition.get_data();
66 | } else if (a === 2) {
67 | subtraction.subtract(x1.real, x1.imag, x2.real, x2.imag);
68 | console.log("Subtraction of Complex 2 from Complex 1 is:");
69 | subtraction.get_data();
70 | } else if (a === 3) {
71 | multiplication.multiply(x1.real, x1.imag, x2.real, x2.imag);
72 | console.log("Multiplication of Complex 1 and Complex 2 is:");
73 | multiplication.get_data();
74 | } else if (a === 4) {
75 | if (x2.real === 0 && x2.imag === 0) {
76 | console.log("Can't divide by zero");
77 | } else {
78 | division.divide(x1.real, x1.imag, x2.real, x2.imag);
79 | console.log("On division of Complex 1 by Complex 2, we get:");
80 | division.get_data();
81 | }
82 | } else {
83 | console.log("Invalid option chosen!");
84 | }
85 |
86 | ans = parseInt(prompt("Do you want to check more? (1 for yes / 2 for no): "));
87 | if (ans === 2) {
88 | break;
89 | }
90 | }
91 |
92 | console.log("\nThank you");
93 |
--------------------------------------------------------------------------------
/Complex_Square_Root_Calculator.js:
--------------------------------------------------------------------------------
1 | const readline = require('readline-sync');
2 |
3 | const num = parseFloat(readline.question('Enter a number: '));
4 |
5 | // Find the square root of the number
6 | const realPart = Math.sqrt(Math.abs(num));
7 | const imaginaryPart = Math.sqrt(-num);
8 |
9 | // Display the result
10 | if (imaginaryPart === 0) {
11 | console.log(`The square root of ${num} is ${realPart.toFixed(3)}`);
12 | } else {
13 | console.log(`The square root of ${num} is ${realPart.toFixed(3)}+${imaginaryPart.toFixed(3)}i`);
14 | }
15 |
--------------------------------------------------------------------------------
/Drug_Management_System.js:
--------------------------------------------------------------------------------
1 | const readline = require('readline');
2 |
3 | const rl = readline.createInterface({
4 | input: process.stdin,
5 | output: process.stdout
6 | });
7 |
8 | class PharmacyManagementSystem {
9 | constructor() {
10 | this.drugInventory = {};
11 | }
12 |
13 | addDrug() {
14 | rl.question("Enter drug name: ", (name) => {
15 | rl.question("Enter price: ", (price) => {
16 | rl.question("Enter quantity: ", (quantity) => {
17 | this.drugInventory[name] = { price: parseFloat(price), quantity: parseInt(quantity) };
18 | console.log("Drug added successfully!");
19 | this.menu();
20 | });
21 | });
22 | });
23 | }
24 |
25 | updateDrug() {
26 | rl.question("Enter drug name: ", (name) => {
27 | if (this.drugInventory.hasOwnProperty(name)) {
28 | rl.question("Enter new price: ", (price) => {
29 | rl.question("Enter new quantity: ", (quantity) => {
30 | this.drugInventory[name].price = parseFloat(price);
31 | this.drugInventory[name].quantity = parseInt(quantity);
32 | console.log("Drug information updated successfully!");
33 | this.menu();
34 | });
35 | });
36 | } else {
37 | console.log("Drug not found in the inventory!");
38 | this.menu();
39 | }
40 | });
41 | }
42 |
43 | viewDrug() {
44 | rl.question("Enter drug name (leave blank to view all drugs): ", (name) => {
45 | if (name.trim() === "") {
46 | if (Object.keys(this.drugInventory).length === 0) {
47 | console.log("No drugs in the inventory!");
48 | } else {
49 | for (let [drug, info] of Object.entries(this.drugInventory)) {
50 | console.log(`Drug Name: ${drug}`);
51 | console.log(`Price: ${info.price}`);
52 | console.log(`Quantity: ${info.quantity}`);
53 | }
54 | }
55 | } else {
56 | if (this.drugInventory.hasOwnProperty(name)) {
57 | console.log(`Drug Name: ${name}`);
58 | console.log(`Price: ${this.drugInventory[name].price}`);
59 | console.log(`Quantity: ${this.drugInventory[name].quantity}`);
60 | } else {
61 | console.log("Drug not found in the inventory!");
62 | }
63 | }
64 | this.menu();
65 | });
66 | }
67 |
68 | recordPurchase() {
69 | rl.question("Enter drug name: ", (name) => {
70 | if (this.drugInventory.hasOwnProperty(name)) {
71 | rl.question("Enter quantity purchased: ", (quantity) => {
72 | if (parseInt(quantity) <= this.drugInventory[name].quantity) {
73 | this.drugInventory[name].quantity -= parseInt(quantity);
74 | console.log("Purchase recorded successfully!");
75 | } else {
76 | console.log("Insufficient quantity in the inventory!");
77 | }
78 | this.menu();
79 | });
80 | } else {
81 | console.log("Drug not found in the inventory!");
82 | this.menu();
83 | }
84 | });
85 | }
86 |
87 | searchDrug() {
88 | rl.question("Enter a keyword to search for drugs: ", (keyword) => {
89 | const searchResults = Object.keys(this.drugInventory).filter(drug =>
90 | drug.toLowerCase().includes(keyword.toLowerCase())
91 | );
92 | if (searchResults.length > 0) {
93 | console.log("Search Results:");
94 | searchResults.forEach(result => console.log(result));
95 | } else {
96 | console.log("No drugs found matching the keyword.");
97 | }
98 | this.menu();
99 | });
100 | }
101 |
102 | deleteDrug() {
103 | rl.question("Enter drug name to delete: ", (name) => {
104 | if (this.drugInventory.hasOwnProperty(name)) {
105 | delete this.drugInventory[name];
106 | console.log(`${name} deleted from the inventory.`);
107 | } else {
108 | console.log("Drug not found in the inventory!");
109 | }
110 | this.menu();
111 | });
112 | }
113 |
114 | setExpirationDate() {
115 | rl.question("Enter drug name: ", (name) => {
116 | if (this.drugInventory.hasOwnProperty(name)) {
117 | rl.question("Enter expiration date (YYYY-MM-DD): ", (expirationDate) => {
118 | this.drugInventory[name].expirationDate = expirationDate;
119 | console.log("Expiration date set successfully!");
120 | this.menu();
121 | });
122 | } else {
123 | console.log("Drug not found in the inventory!");
124 | this.menu();
125 | }
126 | });
127 | }
128 |
129 | checkLowStockAlert() {
130 | rl.question("Enter the minimum quantity threshold: ", (threshold) => {
131 | const lowStockDrugs = Object.entries(this.drugInventory)
132 | .filter(([_, info]) => info.quantity <= parseInt(threshold))
133 | .map(([drug, _]) => drug);
134 |
135 | if (lowStockDrugs.length > 0) {
136 | console.log("Low Stock Drugs:");
137 | lowStockDrugs.forEach(drug => console.log(drug));
138 | } else {
139 | console.log("No drugs are below the quantity threshold.");
140 | }
141 | this.menu();
142 | });
143 | }
144 |
145 | generateSalesReport() {
146 | let totalSales = 0;
147 | for (let [drug, info] of Object.entries(this.drugInventory)) {
148 | const price = info.price;
149 | const quantitySold = info.quantity - this.drugInventory[drug].quantity;
150 | totalSales += price * quantitySold;
151 | }
152 |
153 | console.log(`Total Sales: $${totalSales.toFixed(2)}`);
154 |
155 | const sortedDrugs = Object.entries(this.drugInventory)
156 | .sort((a, b) => b[1].quantity - a[1].quantity)
157 | .slice(0, 5);
158 |
159 | console.log("Top Selling Drugs:");
160 | for (let [drug, info] of sortedDrugs) {
161 | const quantitySold = info.quantity - this.drugInventory[drug].quantity;
162 | console.log(`Drug Name: ${drug}`);
163 | console.log(`Quantity Sold: ${quantitySold}`);
164 | }
165 | this.menu();
166 | }
167 |
168 | userAuthentication() {
169 | rl.question("Enter username: ", (username) => {
170 | rl.question("Enter password: ", (password) => {
171 | if (username === "admin" && password === "password") {
172 | console.log("Authentication successful. Access granted.");
173 | } else {
174 | console.log("Authentication failed. Access denied.");
175 | }
176 | this.menu();
177 | });
178 | });
179 | }
180 |
181 | saveData() {
182 | const data = JSON.stringify(this.drugInventory, null, 2);
183 | fs.writeFile("drug_inventory.json", data, (err) => {
184 | if (err) {
185 | console.log("Failed to save data.");
186 | } else {
187 | console.log("Data saved successfully.");
188 | }
189 | this.menu();
190 | });
191 | }
192 |
193 | loadData() {
194 | fs.readFile("drug_inventory.json", (err, data) => {
195 | if (err) {
196 | console.log("No previous data found.");
197 | } else {
198 | this.drugInventory = JSON.parse(data);
199 | console.log("Data loaded successfully.");
200 | }
201 | this.menu();
202 | });
203 | }
204 |
205 | menu() {
206 | console.log("\nPharmacy Management System");
207 | console.log("1. Add Drug");
208 | console.log("2. Update Drug Information");
209 | console.log("3. View Drug Information");
210 | console.log("4. Record Purchase");
211 | console.log("5. Search Drug");
212 | console.log("6. Delete Drug");
213 | console.log("7. Set Expiration Date");
214 | console.log("8. Check Low Stock Alert");
215 | console.log("9. Generate Sales Report");
216 | console.log("10. User Authentication");
217 | console.log("11. Save Data");
218 | console.log("12. Load Data");
219 | console.log("13. Quit");
220 |
221 | rl.question("Enter your choice: ", (choice) => {
222 | switch (choice) {
223 | case "1":
224 | this.addDrug();
225 | break;
226 | case "2":
227 | this.updateDrug();
228 | break;
229 | case "3":
230 | this.viewDrug();
231 | break;
232 | case "4":
233 | this.recordPurchase();
234 | break;
235 | case "5":
236 | this.searchDrug();
237 | break;
238 | case "6":
239 | this.deleteDrug();
240 | break;
241 | case "7":
242 | this.setExpirationDate();
243 | break;
244 | case "8":
245 | this.checkLowStockAlert();
246 | break;
247 | case "9":
248 | this.generateSalesReport();
249 | break;
250 | case "10":
251 | this.userAuthentication();
252 | break;
253 | case "11":
254 | this.saveData();
255 | break;
256 | case "12":
257 | this.loadData();
258 | break;
259 | case "13":
260 | rl.close();
261 | break;
262 | default:
263 | console.log("Invalid choice. Try again!");
264 | this.menu();
265 | break;
266 | }
267 | });
268 | }
269 | }
270 |
271 | const pharmacyManagementSystem = new PharmacyManagementSystem();
272 | pharmacyManagementSystem.menu();
273 |
--------------------------------------------------------------------------------
/Electric Circuit Visualization/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | Electrical Circuit Visualization
9 |
10 |
11 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/Electric Circuit Visualization/script.js:
--------------------------------------------------------------------------------
1 | document.addEventListener("DOMContentLoaded", function () {
2 | const currentSlider = document.getElementById("current-slider");
3 | const resistanceSlider = document.getElementById("resistance-slider");
4 | const visualization = document.getElementById("visualization");
5 |
6 | function updateVisualization() {
7 | const current = parseFloat(currentSlider.value);
8 | const resistance = parseFloat(resistanceSlider.value);
9 | const voltage = current * resistance;
10 |
11 | const data = [
12 | {
13 | type: "surface",
14 | z: [[voltage]],
15 | colorscale: "Viridis",
16 | },
17 | ];
18 |
19 | const layout = {
20 | title: "Voltage as a Function of Current and Resistance",
21 | scene: {
22 | xaxis_title: "Current (A)",
23 | yaxis_title: "Resistance (Ω)",
24 | zaxis_title: "Voltage (V)",
25 | },
26 | };
27 |
28 | Plotly.newPlot(visualization, data, layout);
29 | }
30 |
31 | currentSlider.addEventListener("input", updateVisualization);
32 | resistanceSlider.addEventListener("input", updateVisualization);
33 |
34 | // Initial visualization update
35 | updateVisualization();
36 | });
37 |
--------------------------------------------------------------------------------
/Electric Circuit Visualization/style.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: Arial, sans-serif;
3 | margin: 0;
4 | padding: 0;
5 | }
6 |
7 | .container {
8 | display: flex;
9 | justify-content: center;
10 | align-items: center;
11 | height: 100vh;
12 | background-color: #f0f0f0;
13 | }
14 |
15 | .visualization {
16 | width: 60%;
17 | }
18 |
19 | .controls {
20 | margin-top: 20px;
21 | }
22 |
23 | input[type="range"] {
24 | width: 100%;
25 | }
26 |
--------------------------------------------------------------------------------
/Max_Heap_Priority_Queue.js:
--------------------------------------------------------------------------------
1 | class MaxHeap {
2 | constructor() {
3 | this.heap = [];
4 | }
5 |
6 | heapify(n, i) {
7 | let largest = i;
8 | const leftChild = 2 * i + 1;
9 | const rightChild = 2 * i + 2;
10 |
11 | if (leftChild < n && this.heap[i] < this.heap[leftChild]) {
12 | largest = leftChild;
13 | }
14 |
15 | if (rightChild < n && this.heap[largest] < this.heap[rightChild]) {
16 | largest = rightChild;
17 | }
18 |
19 | if (largest !== i) {
20 | [this.heap[i], this.heap[largest]] = [this.heap[largest], this.heap[i]];
21 | this.heapify(n, largest);
22 | }
23 | }
24 |
25 | insert(newNum) {
26 | const size = this.heap.length;
27 | if (size === 0) {
28 | this.heap.push(newNum);
29 | } else {
30 | this.heap.push(newNum);
31 | for (let i = Math.floor(size / 2) - 1; i >= 0; i--) {
32 | this.heapify(size, i);
33 | }
34 | }
35 | }
36 |
37 | deleteNode(num) {
38 | const size = this.heap.length;
39 | let i = 0;
40 | for (i = 0; i < size; i++) {
41 | if (num === this.heap[i]) {
42 | break;
43 | }
44 | }
45 |
46 | [this.heap[i], this.heap[size - 1]] = [this.heap[size - 1], this.heap[i]];
47 | this.heap.pop();
48 |
49 | for (let i = Math.floor(this.heap.length / 2) - 1; i >= 0; i--) {
50 | this.heapify(this.heap.length, i);
51 | }
52 | }
53 |
54 | printHeap() {
55 | console.log("Max-Heap array:", this.heap);
56 | }
57 | }
58 |
59 | const maxHeap = new MaxHeap();
60 | maxHeap.insert(3);
61 | maxHeap.insert(4);
62 | maxHeap.insert(9);
63 | maxHeap.insert(5);
64 | maxHeap.insert(2);
65 |
66 | maxHeap.printHeap();
67 |
68 | maxHeap.deleteNode(4);
69 | maxHeap.printHeap();
70 |
--------------------------------------------------------------------------------
/Microsoft_Windows_10_Logo.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Turtle Graphics
8 |
9 |
10 |
57 |
58 |
59 |
--------------------------------------------------------------------------------
/Planetary_Weights.js:
--------------------------------------------------------------------------------
1 | const MERCURY_GRAVITY = 0.376;
2 | const VENUS_GRAVITY = 0.889;
3 | const MARS_GRAVITY = 0.378;
4 | const JUPITER_GRAVITY = 2.36;
5 | const SATURN_GRAVITY = 1.081;
6 | const URANUS_GRAVITY = 0.815;
7 | const NEPTUNE_GRAVITY = 1.14;
8 |
9 | function capitalize(str) {
10 | return str.charAt(0).toUpperCase() + str.slice(1);
11 | }
12 |
13 | function isValidPlanet(planet) {
14 | const validPlanets = [
15 | "Mercury",
16 | "Venus",
17 | "Mars",
18 | "Jupiter",
19 | "Saturn",
20 | "Uranus",
21 | "Neptune",
22 | ];
23 | return validPlanets.includes(planet);
24 | }
25 |
26 | function calculatePlanetWeight(earthWeight, planet) {
27 | switch (planet) {
28 | case "Mercury":
29 | return earthWeight * MERCURY_GRAVITY;
30 | case "Venus":
31 | return earthWeight * VENUS_GRAVITY;
32 | case "Mars":
33 | return earthWeight * MARS_GRAVITY;
34 | case "Jupiter":
35 | return earthWeight * JUPITER_GRAVITY;
36 | case "Saturn":
37 | return earthWeight * SATURN_GRAVITY;
38 | case "Uranus":
39 | return earthWeight * URANUS_GRAVITY;
40 | case "Neptune":
41 | return earthWeight * NEPTUNE_GRAVITY;
42 | default:
43 | return 0;
44 | }
45 | }
46 |
47 | function main() {
48 | const earthWeight = parseFloat(prompt("Enter a weight on Earth:"));
49 | let planet = prompt("Enter a planet:");
50 | planet = capitalize(planet);
51 |
52 | while (!isValidPlanet(planet)) {
53 | if (planet === "Earth") {
54 | alert("Please select a planet other than Earth.");
55 | } else {
56 | alert(`Error: ${planet} is not a planet.`);
57 | }
58 | planet = prompt("Enter a planet:");
59 | planet = capitalize(planet);
60 | }
61 |
62 | const planetWeight = calculatePlanetWeight(earthWeight, planet);
63 | const roundedWeight = planetWeight.toFixed(2);
64 |
65 | alert(`The equivalent weight on ${planet}: ${roundedWeight}`);
66 | }
67 |
68 | main();
69 |
--------------------------------------------------------------------------------
/Pose_Estimation/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/Pose_Estimation/sketch.js:
--------------------------------------------------------------------------------
1 | let video;
2 | let poseNet;
3 | let noseX = 0;
4 | let noseY = 0;
5 | let eyelX = 0;
6 | let eyelY = 0;
7 | let eyerX = 0;
8 | let eyerY = 0;
9 |
10 | function setup() {
11 | createCanvas(640, 480);
12 | video = createCapture(VIDEO);
13 | video.hide();
14 | poseNet = ml5.poseNet(video, modelReady);
15 | poseNet.on('pose', gotPoses);
16 | }
17 |
18 | function gotPoses(poses) {
19 | // console.log(poses);
20 | if (poses.length > 0) {
21 | let nX = poses[0].pose.keypoints[0].position.x;
22 | let nY = poses[0].pose.keypoints[0].position.y;
23 | let eX = poses[0].pose.keypoints[1].position.x;
24 | let eY = poses[0].pose.keypoints[1].position.y;
25 | let EX = poses[0].pose.keypoints[2].position.x;
26 | let EY = poses[0].pose.keypoints[2].position.y;
27 | noseX = lerp(noseX, nX, 0.5);
28 | noseY = lerp(noseY, nY, 0.5);
29 | eyelX = lerp(eyelX, eX, 0.5);
30 | eyelY = lerp(eyelY, eY, 0.5);
31 | eyerX = lerp(eyerX, EX, 0.5);
32 | eyerY = lerp(eyerY, EY, 0.5);
33 | }
34 | }
35 |
36 | function modelReady() {
37 | console.log('model ready');
38 | }
39 |
40 | function draw() {
41 | image(video, 0, 0);
42 | let d = dist(noseX, noseY, eyelX, eyelY);
43 | fill(255, 0, 0);
44 | ellipse(noseX, noseY, d/3);
45 | fill(0,0,255);
46 | ellipse(eyelX, eyelY, d/3);
47 | fill(0,0,255);
48 | ellipse(eyerX, eyerY, d/3);
49 | }
50 |
--------------------------------------------------------------------------------
/Pose_Estimation/style.css:
--------------------------------------------------------------------------------
1 | html, body {
2 | margin: 0;
3 | padding: 0;
4 | }
5 | canvas {
6 | display: block;
7 | }
8 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # HTML_CSS_JavaScript
2 | Education Purpose Only
3 |
--------------------------------------------------------------------------------
/Real-time_Object_Detection_and_Tracking.js:
--------------------------------------------------------------------------------
1 | let videoElement = document.createElement('video');
2 | videoElement.width = 640;
3 | videoElement.height = 480;
4 | document.body.appendChild(videoElement);
5 |
6 | let canvasElement = document.createElement('canvas');
7 | canvasElement.width = 640;
8 | canvasElement.height = 240;
9 | document.body.appendChild(canvasElement);
10 | let ctx = canvasElement.getContext('2d');
11 |
12 | function emptyFunction() {
13 | let threshold1 = cv.getTrackbarPos("Threshold1", "Parameters");
14 | let threshold2 = cv.getTrackbarPos("Threshold2", "Parameters");
15 | let area = cv.getTrackbarPos("Area", "Parameters");
16 | console.log("Threshold1:", threshold1);
17 | console.log("Threshold2:", threshold2);
18 | console.log("Area:", area);
19 | }
20 |
21 | cv.onRuntimeInitialized = () => {
22 | let cap = new cv.VideoCapture(videoElement);
23 | let frame = new cv.Mat();
24 | let imgContour = new cv.Mat();
25 | let imgBlur = new cv.Mat();
26 | let imgGray = new cv.Mat();
27 | let imgCanny = new cv.Mat();
28 | let kernel = new cv.Mat();
29 | let imgDil = new cv.Mat();
30 | let imgStack = new cv.Mat();
31 |
32 | cv.namedWindow("Parameters");
33 | cv.resizeWindow("Parameters", 640, 240);
34 | cv.createTrackbar("Threshold1", "Parameters", 23, 255, emptyFunction);
35 | cv.createTrackbar("Threshold2", "Parameters", 20, 255, emptyFunction);
36 | cv.createTrackbar("Area", "Parameters", 5000, 30000, emptyFunction);
37 |
38 | function processVideo() {
39 | cap.read(frame);
40 |
41 | if (frame.empty()) {
42 | console.log("Failed to capture frame from the camera.");
43 | return;
44 | }
45 |
46 | imgContour = frame.clone();
47 | cv.GaussianBlur(frame, imgBlur, new cv.Size(7, 7), 1);
48 | cv.cvtColor(imgBlur, imgGray, cv.COLOR_BGR2GRAY);
49 |
50 | let threshold1 = cv.getTrackbarPos("Threshold1", "Parameters");
51 | let threshold2 = cv.getTrackbarPos("Threshold2", "Parameters");
52 | cv.Canny(imgGray, imgCanny, threshold1, threshold2);
53 | kernel = cv.getStructuringElement(cv.MORPH_RECT, new cv.Size(5, 5));
54 | cv.dilate(imgCanny, imgDil, kernel, new cv.Point(-1, -1), 1);
55 |
56 | getContours(imgDil, imgContour);
57 |
58 | imgStack = stackImages(0.8, [[frame, imgCanny], [imgDil, imgContour]]);
59 |
60 | cv.imshow("Result", imgStack);
61 | requestAnimationFrame(processVideo);
62 | }
63 |
64 | function getContours(img, imgContour) {
65 | let contours = new cv.MatVector();
66 | let hierarchy = new cv.Mat();
67 |
68 | cv.findContours(img, contours, hierarchy, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE);
69 |
70 | for (let i = 0; i < contours.size(); i++) {
71 | let area = cv.contourArea(contours.get(i));
72 | let areaMin = cv.getTrackbarPos("Area", "Parameters");
73 |
74 | if (area > areaMin) {
75 | cv.drawContours(imgContour, contours, i, new cv.Scalar(255, 0, 255, 255), 7);
76 |
77 | let perimeter = cv.arcLength(contours.get(i), true);
78 | let approx = new cv.Mat();
79 | cv.approxPolyDP(contours.get(i), approx, 0.02 * perimeter, true);
80 |
81 | let rect = cv.boundingRect(approx);
82 | cv.rectangle(imgContour, rect, new cv.Scalar(0, 255, 0, 255), 5);
83 |
84 | cv.putText(imgContour, "Points: " + approx.size(), new cv.Point(rect.x + rect.width + 20, rect.y + 20),
85 | cv.FONT_HERSHEY_COMPLEX, 0.7, new cv.Scalar(0, 255, 0, 255), 2);
86 | cv.putText(imgContour, "Area: " + Math.floor(area), new cv.Point(rect.x + rect.width + 20, rect.y + 45),
87 | cv.FONT_HERSHEY_COMPLEX, 0.7, new cv.Scalar(0, 255, 0, 255), 2);
88 |
89 | approx.delete();
90 | }
91 | }
92 |
93 | contours.delete();
94 | hierarchy.delete();
95 | }
96 |
97 | videoElement.onloadedmetadata = () => {
98 | videoElement.play();
99 | requestAnimationFrame(processVideo);
100 | };
101 | };
102 |
--------------------------------------------------------------------------------
/Real-time_Object_Tracking.js:
--------------------------------------------------------------------------------
1 | const cv = require('opencv4nodejs');
2 |
3 | // Create a tracker object
4 | const tracker = new cv.TrackerKCF();
5 |
6 | // Open the video capture
7 | const cap = new cv.VideoCapture(0);
8 |
9 | // Read the first frame from the video
10 | let frame = cap.read();
11 | if (frame.empty) {
12 | console.log('Failed to read video');
13 | process.exit(1);
14 | }
15 |
16 | // Create a window to display the video
17 | const window = new cv.NamedWindow('Tracking', cv.WindowFlags.NORMAL);
18 |
19 | // Select the region of interest (ROI) for tracking
20 | const bbox = cv.selectROI('Tracking', frame, false);
21 |
22 | // Initialize the tracker with the selected ROI
23 | tracker.init(frame, bbox);
24 |
25 | // Main loop for video processing
26 | while (true) {
27 | // Read a frame from the video
28 | frame = cap.read();
29 | if (frame.empty) {
30 | console.log('Failed to read video');
31 | break;
32 | }
33 |
34 | // Update the tracker with the current frame
35 | const success = tracker.update(frame);
36 |
37 | // If tracking is successful, draw the bounding box
38 | if (success) {
39 | const trackedRect = tracker.getRegion();
40 | frame.drawRectangle(trackedRect, new cv.Vec(0, 255, 255), 3);
41 | frame.putText('Tracking', new cv.Point2(trackedRect.x, trackedRect.y - 10), cv.FONT_HERSHEY_SIMPLEX, 0.9, new cv.Vec(0, 255, 255), 2, cv.LINE_AA);
42 | } else {
43 | // If tracking is lost, display "Lost" message
44 | frame.putText('Lost', new cv.Point2(20, 40), cv.FONT_HERSHEY_SIMPLEX, 0.9, new cv.Vec(0, 0, 255), 2, cv.LINE_AA);
45 | }
46 |
47 | // Display the image with tracking results
48 | window.show(frame);
49 |
50 | // Exit the loop if 'q' is pressed
51 | if (cv.waitKey(1) === 'q'.charCodeAt(0)) {
52 | break;
53 | }
54 | }
55 |
56 | // Release the video capture and close windows
57 | cap.release();
58 | window.destroyAllWindows();
59 |
--------------------------------------------------------------------------------
/Reverse_Array_Elements_Program.js:
--------------------------------------------------------------------------------
1 | const readline = require('readline-sync');
2 |
3 | const number = parseInt(readline.question('Please enter the total number you want to enter: '));
4 |
5 | const array = [];
6 | for (let i = 0; i < number; i++) {
7 | const element = parseInt(readline.question(`Enter the element ${i + 1}: `));
8 | array.push(element);
9 | }
10 |
11 | for (let i = 0; i < Math.floor(number / 2); i++) {
12 | const temp = array[i];
13 | array[i] = array[number - 1 - i];
14 | array[number - 1 - i] = temp;
15 | }
16 |
17 | console.log('\nReverse all elements of the array:');
18 | for (const element of array) {
19 | console.log(element);
20 | }
21 |
--------------------------------------------------------------------------------
/Rock_Paper_Scissors_Game.js:
--------------------------------------------------------------------------------
1 | const readline = require('readline');
2 |
3 | function userInputChecker() {
4 | const rl = readline.createInterface({
5 | input: process.stdin,
6 | output: process.stdout
7 | });
8 |
9 | return new Promise((resolve) => {
10 | rl.question('Enter your choice: ', (userChoice) => {
11 | if (userChoice === 'r' || userChoice === 'p' || userChoice === 's') {
12 | rl.close();
13 | resolve(userChoice);
14 | } else {
15 | console.log('Wrong Input!!');
16 | resolve('');
17 | }
18 | });
19 | });
20 | }
21 |
22 | function gameLogic(computerChoice, userChoice, userScore, computerScore) {
23 | return new Promise((resolve) => {
24 | if (computerChoice === 'rock' && userChoice === 'p') {
25 | console.log('Player Wins');
26 | console.log('Enter 1 to continue and 0 to leave the game');
27 | userScore += 1;
28 | const rl = readline.createInterface({
29 | input: process.stdin,
30 | output: process.stdout
31 | });
32 | rl.question('', (i) => {
33 | rl.close();
34 | resolve([parseInt(i), userScore, computerScore]);
35 | });
36 | } else if (computerChoice === 'rock' && userChoice === 's') {
37 | console.log('Computer Wins');
38 | console.log('Enter 1 to continue and 0 to leave the game');
39 | computerScore += 1;
40 | const rl = readline.createInterface({
41 | input: process.stdin,
42 | output: process.stdout
43 | });
44 | rl.question('', (i) => {
45 | rl.close();
46 | resolve([parseInt(i), userScore, computerScore]);
47 | });
48 | } else if (computerChoice === 'paper' && userChoice === 'r') {
49 | console.log('Computer Wins');
50 | console.log('Enter 1 to continue and 0 to leave the game');
51 | computerScore += 1;
52 | const rl = readline.createInterface({
53 | input: process.stdin,
54 | output: process.stdout
55 | });
56 | rl.question('', (i) => {
57 | rl.close();
58 | resolve([parseInt(i), userScore, computerScore]);
59 | });
60 | } else if (computerChoice === 'paper' && userChoice === 's') {
61 | console.log('Player Wins');
62 | console.log('Enter 1 to continue and 0 to leave the game');
63 | userScore += 1;
64 | const rl = readline.createInterface({
65 | input: process.stdin,
66 | output: process.stdout
67 | });
68 | rl.question('', (i) => {
69 | rl.close();
70 | resolve([parseInt(i), userScore, computerScore]);
71 | });
72 | } else if (computerChoice === 'scissors' && userChoice === 'r') {
73 | console.log('Player Wins');
74 | console.log('Enter 1 to continue and 0 to leave the game');
75 | userScore += 1;
76 | const rl = readline.createInterface({
77 | input: process.stdin,
78 | output: process.stdout
79 | });
80 | rl.question('', (i) => {
81 | rl.close();
82 | resolve([parseInt(i), userScore, computerScore]);
83 | });
84 | } else if (computerChoice === 'scissors' && userChoice === 'p') {
85 | console.log('Computer Wins');
86 | console.log('Enter 1 to continue and 0 to leave the game');
87 | computerScore += 1;
88 | const rl = readline.createInterface({
89 | input: process.stdin,
90 | output: process.stdout
91 | });
92 | rl.question('', (i) => {
93 | rl.close();
94 | resolve([parseInt(i), userScore, computerScore]);
95 | });
96 | } else if (computerChoice === userChoice) {
97 | console.log('Draw');
98 | console.log('Enter 1 to continue and 0 to leave the game');
99 | userScore += 1;
100 | computerScore += 1;
101 | const rl = readline.createInterface({
102 | input: process.stdin,
103 | output: process.stdout
104 | });
105 | rl.question('', (i) => {
106 | rl.close();
107 | resolve([parseInt(i), userScore, computerScore]);
108 | });
109 | }
110 | });
111 | }
112 |
113 | function playGame() {
114 | const choices = ['rock', 'paper', 'scissors'];
115 |
116 | console.log('Welcome to the game!');
117 | console.log('Enter:');
118 | console.log('r for rock');
119 | console.log('p for paper');
120 | console.log('s for scissors');
121 |
122 | const rl = readline.createInterface({
123 | input: process.stdin,
124 | output: process.stdout
125 | });
126 |
127 | rl.question('Enter your name: ', (playerName) => {
128 | let i = 1;
129 | let userScoreTotal = 0;
130 | let computerScoreTotal = 0;
131 |
132 | const loop = () => {
133 | if (i === 1) {
134 | userInputChecker().then((userInput) => {
135 | if (userInput === '') {
136 | loop();
137 | return;
138 | }
139 |
140 | const computerChoice = choices[Math.floor(Math.random() * choices.length)];
141 | console.log('Computer chooses: ' + computerChoice);
142 |
143 | gameLogic(computerChoice, userInput, userScoreTotal, computerScoreTotal).then(([input, userScore, computerScore]) => {
144 | i = input;
145 | userScoreTotal = userScore;
146 | computerScoreTotal = computerScore;
147 |
148 | if (i === 0) {
149 | console.log('Scores for this match are as follows:');
150 | console.log(playerName + "'s score: " + userScoreTotal);
151 | console.log('Computer\'s score: ' + computerScoreTotal);
152 | console.log('Thank you for playing the game.');
153 | console.log('Have a nice day!');
154 | rl.close();
155 | } else if (i !== 0 && i !== 1) {
156 | console.log('Invalid Input!');
157 | rl.question('Please enter 1 to continue or 0 to leave the game: ', (input) => {
158 | i = parseInt(input);
159 | loop();
160 | });
161 | } else {
162 | loop();
163 | }
164 | });
165 | });
166 | }
167 | };
168 |
169 | loop();
170 | });
171 | }
172 |
173 | playGame();
174 |
--------------------------------------------------------------------------------
/Rotated_Array_Search.js:
--------------------------------------------------------------------------------
1 | function searchInRotatedArray(nums, target) {
2 | const n = nums.length;
3 |
4 | // Logic
5 | let start = 0;
6 | let end = n - 1;
7 |
8 | while (start <= end) {
9 | let mid = Math.floor((start + end) / 2);
10 |
11 | if (nums[mid] === target) {
12 | return mid;
13 | }
14 |
15 | // Two cases
16 | if (nums[start] <= nums[mid]) {
17 | // Left
18 | if (target >= nums[start] && target <= nums[mid]) {
19 | end = mid - 1;
20 | } else {
21 | start = mid + 1;
22 | }
23 | } else {
24 | // Right
25 | if (target >= nums[mid] && target <= nums[end]) {
26 | start = mid + 1;
27 | } else {
28 | end = mid - 1;
29 | }
30 | }
31 | }
32 |
33 | return -1;
34 | }
35 |
36 | const nums = [4, 5, 6, 7, 0, 1, 2, 3];
37 | const target = 0;
38 |
39 | const result = searchInRotatedArray(nums, target);
40 | console.log(result);
41 |
--------------------------------------------------------------------------------
/Satellite_Orbit_Visualization_in_3D_with_TLE_Data.js:
--------------------------------------------------------------------------------
1 | // Import necessary modules from Three.js library
2 | import * as THREE from 'three';
3 | import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
4 |
5 | // Define satellite data class
6 | class SatelliteData {
7 | constructor(name, line1, line2, color) {
8 | this.name = name;
9 | this.line1 = line1;
10 | this.line2 = line2;
11 | this.color = color;
12 | }
13 | }
14 |
15 | const satelliteDataList = [];
16 |
17 | function readTLEData(tleFile) {
18 | const fileReader = new FileReader();
19 | fileReader.addEventListener('load', function (e) {
20 | const lines = e.target.result.split('\n');
21 | for (let i = 0; i < lines.length; i += 3) {
22 | const name = lines[i].trim();
23 | const line1 = lines[i + 1].trim();
24 | const line2 = lines[i + 2].trim();
25 | const color = new THREE.Color(0, 0, 0); // Set default color to black
26 | const satelliteData = new SatelliteData(name, line1, line2, color);
27 | satelliteDataList.push(satelliteData);
28 | }
29 | visualizeOrbits();
30 | });
31 | fileReader.readAsText(tleFile);
32 | }
33 |
34 | function visualizeOrbits() {
35 | // Set up Three.js scene
36 | const scene = new THREE.Scene();
37 | const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
38 | const renderer = new THREE.WebGLRenderer();
39 | renderer.setSize(window.innerWidth, window.innerHeight);
40 | document.body.appendChild(renderer.domElement);
41 |
42 | // Set up orbit controls
43 | const controls = new OrbitControls(camera, renderer.domElement);
44 |
45 | // Add Earth to the scene
46 | const earthGeometry = new THREE.SphereGeometry(1, 32, 32);
47 | const earthMaterial = new THREE.MeshBasicMaterial({ color: 0x0000ff });
48 | const earthMesh = new THREE.Mesh(earthGeometry, earthMaterial);
49 | scene.add(earthMesh);
50 |
51 | // Add satellite paths to the scene
52 | for (const satelliteData of satelliteDataList) {
53 | const orbitGeometry = new THREE.BufferGeometry();
54 | const positions = [];
55 | const orbitMaterial = new THREE.LineBasicMaterial({ color: satelliteData.color });
56 | const orbit = new TLE(satelliteData.name, satelliteData.line1, satelliteData.line2).orbit;
57 | let t = 0.0;
58 | const dt = 5.0;
59 | for (let i = 0; i < 72; i++) {
60 | const date = AbsoluteDate.J2000_EPOCH.shiftedBy(t);
61 | const pvCoordinates = orbit.getPVCoordinates(date);
62 | const x = pvCoordinates.getPosition().getX() / 1000.0; // Scale the coordinates
63 | const y = pvCoordinates.getPosition().getY() / 1000.0;
64 | const z = pvCoordinates.getPosition().getZ() / 1000.0;
65 | positions.push(x, y, z);
66 | t += dt;
67 | }
68 | orbitGeometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
69 | const orbitLine = new THREE.Line(orbitGeometry, orbitMaterial);
70 | scene.add(orbitLine);
71 | }
72 |
73 | // Set up camera position and controls
74 | camera.position.z = 5;
75 | controls.update();
76 |
77 | // Animation loop
78 | function animate() {
79 | requestAnimationFrame(animate);
80 | renderer.render(scene, camera);
81 | }
82 | animate();
83 | }
84 |
85 | // Read TLE data from a file
86 | const tleFileInput = document.getElementById('tleFileInput');
87 | tleFileInput.addEventListener('change', (e) => {
88 | const tleFile = e.target.files[0];
89 | readTLEData(tleFile);
90 | });
91 |
--------------------------------------------------------------------------------
/Satellite_Orbits.js:
--------------------------------------------------------------------------------
1 | const canvas = document.getElementById('canvas');
2 | const ctx = canvas.getContext('2d');
3 |
4 | const SCREEN_WIDTH = 800;
5 | const SCREEN_HEIGHT = 600;
6 | const EARTH_RADIUS = 6371;
7 | const NUM_SATELLITES = 10;
8 | const SATELLITE_RADIUS = 100;
9 | const SATELLITE_COLOR = 'red';
10 |
11 | function SatelliteOrbit() {
12 | this.semi_major_axis = 800 + Math.random() * 700;
13 | this.eccentricity = 0.1 + Math.random() * 0.3;
14 | }
15 |
16 | const satellites = [];
17 | for (let i = 0; i < NUM_SATELLITES; i++) {
18 | satellites.push(new SatelliteOrbit());
19 | }
20 |
21 | function drawEarth() {
22 | ctx.fillStyle = 'lightblue';
23 | for (let i = 0; i < 100; i++) {
24 | for (let j = 0; j < 50; j++) {
25 | const u = (i * 2 * Math.PI) / 100;
26 | const v = (j * Math.PI) / 50;
27 | const x = EARTH_RADIUS * Math.cos(u) * Math.sin(v) + SCREEN_WIDTH / 2;
28 | const y = EARTH_RADIUS * Math.sin(u) * Math.sin(v) + SCREEN_HEIGHT / 2;
29 | ctx.fillRect(x, y, 1, 1);
30 | }
31 | }
32 | }
33 |
34 | function drawSatelliteOrbit(satellite, time) {
35 | ctx.beginPath();
36 | for (let i = 0; i < time.length; i++) {
37 | const r =
38 | (satellite.semi_major_axis * (1 - satellite.eccentricity ** 2)) /
39 | (1 + satellite.eccentricity * Math.cos(time[i]));
40 | const x = r * Math.cos(time[i]) + SCREEN_WIDTH / 2;
41 | const y = r * Math.sin(time[i]) + SCREEN_HEIGHT / 2;
42 | if (i === 0) {
43 | ctx.moveTo(x, y);
44 | } else {
45 | ctx.lineTo(x, y);
46 | }
47 | }
48 | ctx.strokeStyle = 'gray';
49 | ctx.stroke();
50 | }
51 |
52 | function drawSatelliteMarker(satellite, time) {
53 | const r =
54 | (satellite.semi_major_axis * (1 - satellite.eccentricity ** 2)) /
55 | (1 + satellite.eccentricity * Math.cos(time[time.length - 1]));
56 | const x = r * Math.cos(time[time.length - 1]) + SCREEN_WIDTH / 2;
57 | const y = r * Math.sin(time[time.length - 1]) + SCREEN_HEIGHT / 2;
58 | ctx.fillStyle = SATELLITE_COLOR;
59 | ctx.beginPath();
60 | ctx.arc(x, y, SATELLITE_RADIUS, 0, 2 * Math.PI);
61 | ctx.fill();
62 | }
63 |
64 | function draw() {
65 | ctx.clearRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
66 |
67 | drawEarth();
68 |
69 | const numFrames = 100;
70 | const time = new Array(numFrames).fill(0).map((_, i) => (i * 2 * Math.PI) / numFrames);
71 |
72 | for (const satellite of satellites) {
73 | drawSatelliteOrbit(satellite, time);
74 | drawSatelliteMarker(satellite, time);
75 | }
76 |
77 | requestAnimationFrame(draw);
78 | }
79 |
80 | draw();
81 |
--------------------------------------------------------------------------------
/Satellite_Updates.js:
--------------------------------------------------------------------------------
1 | const axios = require('axios');
2 | const THREE = require('three');
3 |
4 | // Step 1: Retrieve satellite data from the API
5 | const satelliteDataApiUrl = 'API_URL_HERE';
6 |
7 | axios.get(satelliteDataApiUrl)
8 | .then(response => {
9 | const satelliteData = response.data;
10 |
11 | // Step 2: Parse TLE data using skyfield
12 | const tleData = satelliteData.map(satellite => [satellite.tle_line1, satellite.tle_line2]);
13 |
14 | // Step 3: Visualize satellite orbits in 3D
15 | const scene = new THREE.Scene();
16 | const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
17 | const renderer = new THREE.WebGLRenderer();
18 |
19 | renderer.setSize(window.innerWidth, window.innerHeight);
20 | document.body.appendChild(renderer.domElement);
21 |
22 | const orbits = [];
23 |
24 | tleData.forEach(tle => {
25 | const satellite = new Satrec();
26 | satellite.sgp4init(Constants.wgs84, tle[0], tle[1]);
27 |
28 | const positionAndVelocity = satellite.propagate(2023, 7, 11, 0, 0, 0);
29 | const positionEci = positionAndVelocity.position;
30 |
31 | const satelliteOrbit = [];
32 | for (let i = 0; i < 3600; i += 60) {
33 | const time = 2023 * 24 * 60 + 7 * 24 * 60 + 11 * 24 * 60 + i;
34 | const positionAndVelocity = satellite.propagate(2023, 7, 11, 0, i, 0);
35 | const positionEci = positionAndVelocity.position;
36 |
37 | const gmst = satellite.gstimeFromDate(2023, 7, 11, 0, i, 0);
38 | const positionGd = satellite.eciToGeodetic(positionEci, gmst);
39 |
40 | satelliteOrbit.push({
41 | latitude: satellite.degreesLat(positionGd.latitude),
42 | longitude: satellite.degreesLong(positionGd.longitude),
43 | altitude: positionGd.height,
44 | });
45 | }
46 |
47 | orbits.push(satelliteOrbit);
48 | });
49 |
50 | orbits.forEach(satelliteOrbit => {
51 | const material = new THREE.LineBasicMaterial({ color: 0x00ff00 });
52 | const points = satelliteOrbit.map(coords => {
53 | const radius = coords.altitude + 6371;
54 | const phi = (90 - coords.latitude) * Math.PI / 180;
55 | const theta = (180 - coords.longitude) * Math.PI / 180;
56 | return new THREE.Vector3(
57 | radius * Math.sin(phi) * Math.cos(theta),
58 | radius * Math.cos(phi),
59 | radius * Math.sin(phi) * Math.sin(theta)
60 | );
61 | });
62 |
63 | const geometry = new THREE.BufferGeometry().setFromPoints(points);
64 | const line = new THREE.Line(geometry, material);
65 | scene.add(line);
66 | });
67 |
68 | camera.position.z = 500;
69 |
70 | const animate = function () {
71 | requestAnimationFrame(animate);
72 |
73 | // Rotate the scene if needed
74 | // scene.rotation.y += 0.01;
75 |
76 | renderer.render(scene, camera);
77 | };
78 |
79 | animate();
80 | })
81 | .catch(error => {
82 | console.error('Error retrieving satellite data:', error);
83 | });
84 |
--------------------------------------------------------------------------------
/Satellite_Updates_Projects.js:
--------------------------------------------------------------------------------
1 | const axios = require('axios');
2 | const Skyfield = require('skyfield');
3 | const { linspace } = require('mathjs');
4 |
5 | class SatelliteData {
6 | constructor(name, tle_line1, tle_line2, angle) {
7 | this.name = name;
8 | this.tle_line1 = tle_line1;
9 | this.tle_line2 = tle_line2;
10 | this.angle = angle;
11 | }
12 | }
13 |
14 | class SatelliteDbEntry {
15 | constructor(name, country) {
16 | this.name = name;
17 | this.country = country;
18 | }
19 | }
20 |
21 | async function sendGetRequest(url) {
22 | try {
23 | const response = await axios.get(url);
24 | return response.data;
25 | } catch (error) {
26 | console.log(`Error in sendGetRequest: ${error.message}`);
27 | throw error;
28 | }
29 | }
30 |
31 | (async function () {
32 | try {
33 | // Step 1: Retrieve satellite data from the API
34 | const satelliteDataApiUrl = 'API_URL_HERE';
35 | const satelliteDataJson = await sendGetRequest(satelliteDataApiUrl);
36 | const satelliteData = JSON.parse(satelliteDataJson).map(
37 | (data) => new SatelliteData(data.name, data.tle_line1, data.tle_line2, data.angle)
38 | );
39 |
40 | // Step 2: Parse TLE data using Skyfield
41 | const tleData = satelliteData.map((satellite) => [satellite.tle_line1, satellite.tle_line2]);
42 |
43 | // Step 3: Visualize satellite orbits in 3D
44 | const loader = new Skyfield.Loader('path_to_data_directory');
45 | const ephemeris = loader.load('de421.bsp');
46 | const satellites = loader.parseTleFile(tleData);
47 |
48 | const fig = plt.figure();
49 | const ax = fig.add_subplot(111, { projection: '3d' });
50 |
51 | for (const satellite of satellites) {
52 | // Calculate the satellite's position over time
53 | const ts = loader.makeTimescale();
54 | const t = ts.utc(2023, 7, 11, 0, linspace(0, 3600 * 60, 3600));
55 | const geocentric = satellite.at(t);
56 | const subpoint = geocentric.subpoint();
57 |
58 | // Extract latitude, longitude, and altitude
59 | const latitude = subpoint.latitude.degrees;
60 | const longitude = subpoint.longitude.degrees;
61 | const altitude = subpoint.elevation.km;
62 |
63 | // Plot the satellite's trajectory in 3D
64 | ax.plot(longitude, latitude, altitude);
65 | }
66 |
67 | ax.set_xlabel('Longitude');
68 | ax.set_ylabel('Latitude');
69 | ax.set_zlabel('Altitude (km)');
70 |
71 | // Step 4: Map satellites to countries using the satellite database API
72 | const satelliteDbApiUrl = 'SATELLITE_DB_API_URL_HERE';
73 | const satelliteDbJson = await sendGetRequest(satelliteDbApiUrl);
74 | const satelliteDb = JSON.parse(satelliteDbJson).map(
75 | (entry) => new SatelliteDbEntry(entry.name, entry.country)
76 | );
77 |
78 | // Mapping satellite names to countries
79 | const satelliteCountryMap = {};
80 | for (const satellite of satelliteData) {
81 | const entry = satelliteDb.find((dbEntry) => dbEntry.name === satellite.name);
82 | const country = entry ? entry.country : 'Unknown';
83 | satelliteCountryMap[satellite.name] = country;
84 | }
85 |
86 | // Printing satellite information
87 | for (const satellite of satelliteData) {
88 | const name = satellite.name;
89 | const angle = satellite.angle;
90 | const country = satelliteCountryMap[name];
91 |
92 | console.log(`Satellite Name: ${name}`);
93 | console.log(`Orbital Angle: ${angle} degrees`);
94 | console.log(`Country: ${country}`);
95 | console.log();
96 | }
97 |
98 | // Show the 3D plot
99 | plt.show();
100 | } catch (error) {
101 | console.log(`Error: ${error.message}`);
102 | }
103 | })();
104 |
--------------------------------------------------------------------------------
/Singly_Linked_List_Traversal.js:
--------------------------------------------------------------------------------
1 | class Node {
2 | constructor(data) {
3 | this.dataval = data;
4 | this.nextval = null;
5 | }
6 | }
7 |
8 | class SLinkedList {
9 | constructor() {
10 | this.headval = null;
11 | }
12 |
13 | listprint() {
14 | let printval = this.headval;
15 | while (printval !== null) {
16 | console.log("Value: " + printval.dataval);
17 | printval = printval.nextval;
18 | }
19 | }
20 | }
21 |
22 | const list = new SLinkedList();
23 | list.headval = new Node("Monday");
24 | const e2 = new Node("Tuesday");
25 | const e3 = new Node("Wednesday");
26 |
27 | list.headval.nextval = e2;
28 | e2.nextval = e3;
29 |
30 | list.listprint();
31 |
--------------------------------------------------------------------------------
/Sort_Income_List.js:
--------------------------------------------------------------------------------
1 | const readline = require('readline');
2 |
3 | const rl = readline.createInterface({
4 | input: process.stdin,
5 | output: process.stdout
6 | });
7 |
8 | let incomeList = [];
9 |
10 | rl.question("Enter the income of 10 people:\n", function() {
11 | askIncome(0);
12 | });
13 |
14 | function askIncome(person) {
15 | if (person >= 10) {
16 | rl.close();
17 | sortAndPrintIncome();
18 | return;
19 | }
20 |
21 | rl.question(`Enter income for person ${person + 1}: `, function(income) {
22 | incomeList.push(parseInt(income));
23 | askIncome(person + 1);
24 | });
25 | }
26 |
27 | function sortAndPrintIncome() {
28 | for (let firstIndex = 0; firstIndex < 9; firstIndex++) {
29 | let swapCount = 0;
30 | let minIncome = incomeList[firstIndex];
31 | let minIndex = firstIndex;
32 |
33 | for (let secondIndex = firstIndex + 1; secondIndex < 10; secondIndex++) {
34 | if (minIncome > incomeList[secondIndex]) {
35 | minIncome = incomeList[secondIndex];
36 | swapCount++;
37 | minIndex = secondIndex;
38 | }
39 | }
40 |
41 | if (swapCount !== 0) {
42 | let temp = incomeList[firstIndex];
43 | incomeList[firstIndex] = minIncome;
44 | incomeList[minIndex] = temp;
45 | }
46 | }
47 |
48 | console.log("Sorted income list:");
49 | incomeList.forEach(income => {
50 | console.log(income);
51 | });
52 | }
53 |
--------------------------------------------------------------------------------
/Sudoku_Solver.js:
--------------------------------------------------------------------------------
1 | const grid_size = 9;
2 |
3 | // A utility function to print the grid
4 | function printGrid(grid) {
5 | for (let row = 0; row < grid_size; row++) {
6 | let rowStr = "";
7 | for (let col = 0; col < grid_size; col++) {
8 | rowStr += grid[row][col] + " ";
9 | }
10 | console.log(rowStr);
11 | }
12 | }
13 |
14 | // Checks whether it will be legal to assign num to the given row, col
15 | function isSafe(grid, row, col, num) {
16 | // Check if we find the same num in the same row, return false
17 | for (let checkCol = 0; checkCol < grid_size; checkCol++) {
18 | if (grid[row][checkCol] === num) {
19 | return false;
20 | }
21 | }
22 |
23 | // Check if we find the same num in the same column, return false
24 | for (let checkRow = 0; checkRow < grid_size; checkRow++) {
25 | if (grid[checkRow][col] === num) {
26 | return false;
27 | }
28 | }
29 |
30 | // Check if we find the same num in the particular 3x3 matrix, return false
31 | const startRow = row - (row % 3);
32 | const startCol = col - (col % 3);
33 | for (let checkRow = 0; checkRow < 3; checkRow++) {
34 | for (let checkCol = 0; checkCol < 3; checkCol++) {
35 | if (grid[checkRow + startRow][checkCol + startCol] === num) {
36 | return false;
37 | }
38 | }
39 | }
40 |
41 | return true;
42 | }
43 |
44 | // Takes a partially filled-in grid and attempts to assign values to all unassigned locations
45 | function solveSudoku(grid, row, col) {
46 | // Check if we have reached the last row and column, return true to avoid further backtracking
47 | if (row === grid_size - 1 && col === grid_size) {
48 | return true;
49 | }
50 |
51 | // Check if column value becomes grid_size, move to the next row and column start from 0
52 | if (col === grid_size) {
53 | row++;
54 | col = 0;
55 | }
56 |
57 | // Check if the current position of the grid already contains a value > 0, iterate for the next column
58 | if (grid[row][col] > 0) {
59 | return solveSudoku(grid, row, col + 1);
60 | }
61 |
62 | for (let num = 1; num <= grid_size; num++) {
63 | // Check if it is safe to place the num (1-9) in the given row, col
64 | if (isSafe(grid, row, col, num)) {
65 | // Assign the num in the current (row, col) position of the grid and assume it is correct
66 | grid[row][col] = num;
67 |
68 | // Check for the next possibility with the next column
69 | if (solveSudoku(grid, row, col + 1)) {
70 | return true;
71 | }
72 |
73 | // If the assumption was wrong, remove the assigned num and go for the next assumption with a different num value
74 | grid[row][col] = 0;
75 | }
76 | }
77 |
78 | return false;
79 | }
80 |
81 | // Driver Code
82 | // 0 means unassigned cells
83 | const grid = [
84 | [3, 0, 6, 5, 0, 8, 4, 0, 0],
85 | [5, 2, 0, 0, 0, 0, 0, 0, 0],
86 | [0, 8, 7, 0, 0, 0, 0, 3, 1],
87 | [0, 0, 3, 0, 1, 0, 0, 8, 0],
88 | [9, 0, 0, 8, 6, 3, 0, 0, 5],
89 | [0, 5, 0, 0, 9, 0, 6, 0, 0],
90 | [1, 3, 0, 0, 0, 0, 2, 5, 0],
91 | [0, 0, 0, 0, 0, 0, 0, 7, 4],
92 | [0, 0, 5, 2, 0, 6, 3, 0, 0]
93 | ];
94 |
95 | if (solveSudoku(grid, 0, 0)) {
96 | printGrid(grid);
97 | } else {
98 | console.log("No solution exists.");
99 | }
100 |
--------------------------------------------------------------------------------
/Symbolic_Mathematics_with_Sympy.js:
--------------------------------------------------------------------------------
1 | // Number of program 1
2 | let squareRoot2 = Math.sqrt(2);
3 | console.log(squareRoot2);
4 |
5 | // Number of program 2
6 | let half = 1 / 2;
7 | let third = 1 / 3;
8 | let sumResult = half + third;
9 | console.log(sumResult);
10 |
11 | // Number of program 3
12 | let varX, varY;
13 | let binomialExpr = Math.pow(varX + varY, 6);
14 | console.log(binomialExpr);
15 |
16 | // Number of program 4
17 | let trigExpr = Math.sin(varX) / Math.cos(varX);
18 | console.log(trigExpr);
19 |
20 | // Number of program 5
21 | let equation = (Math.sin(varX) - varX) / Math.pow(varX, 3);
22 | console.log(equation);
23 |
24 | // Number of program 6
25 | let logExpr = Math.log(varX);
26 | let logDerivative = 1 / varX;
27 | let inverseDerivative = 1 / Math.pow(varX, 2);
28 | let sinDerivative = Math.cos(varX);
29 | let cosDerivative = -Math.sin(varX);
30 | console.log(`Derivative of log(x) with respect to x: ${logDerivative}`);
31 | console.log(`Derivative of 1/x with respect to x: ${inverseDerivative}`);
32 | console.log(`Derivative of sin(x) with respect to x: ${sinDerivative}`);
33 | console.log(`Derivative of cos(x) with respect to x: ${cosDerivative}`);
34 |
35 | // Number of program 7
36 | let equation1 = varX + varY - 2;
37 | let equation2 = 2 * varX + varY;
38 | console.log(`x = ${equation1}`);
39 | console.log(`y = ${equation2}`);
40 |
41 | // Number of program 8
42 | let integratedExpr1 = (Math.pow(varX, 3)) / 3;
43 | console.log(`Integration of x^2: ${integratedExpr1}`);
44 |
45 | let integratedExpr2 = -Math.cos(varX);
46 | console.log(`Integration of sin(x): ${integratedExpr2}`);
47 |
48 | let integratedExpr3 = Math.sin(varX);
49 | console.log(`Integration of cos(x): ${integratedExpr3}`);
50 |
51 | // Number of program 9
52 | let functionF = Math.exp(varX);
53 | let differentialEquation = Math.pow(functionF, 2) + 9 * functionF;
54 | console.log(differentialEquation);
55 |
56 | // Number of program 10
57 | let varX, varY, varZ;
58 | let coefficientMatrix = [
59 | [3, 7, -12],
60 | [4, -2, -5]
61 | ];
62 | let constants = [0, 0];
63 |
64 | for (let i = 0; i < coefficientMatrix.length; i++) {
65 | for (let j = 0; j < coefficientMatrix[i].length; j++) {
66 | console.log(coefficientMatrix[i][j]);
67 | }
68 | }
69 |
70 | console.log(`x = ${constants[0]}`);
71 | console.log(`y = ${constants[1]}`);
72 |
--------------------------------------------------------------------------------
/Voter_Eligibility_Check.js:
--------------------------------------------------------------------------------
1 | // Program for checking voter age
2 |
3 | while (true) {
4 | try {
5 | const age = parseInt(prompt("Enter your age:"));
6 |
7 | if (Number.isNaN(age)) {
8 | throw new Error();
9 | }
10 |
11 | if (18 <= age && age <= 120) {
12 | console.log("Congratulations!");
13 | console.log("You are eligible to vote.");
14 | } else if (12 <= age && age < 18) {
15 | console.log("You are not yet eligible to vote.");
16 | console.log("Enjoy your teenage years!");
17 | } else if (0 <= age && age < 12) {
18 | console.log("You are too young to vote.");
19 | console.log("Make the most of your childhood!");
20 | } else if (age < 0) {
21 | console.log("Invalid age entered.");
22 | console.log("Please enter a positive value.");
23 | } else {
24 | console.log("You have surpassed the maximum voting age.");
25 | console.log("Thank you for your contribution to society!");
26 | }
27 |
28 | break;
29 | } catch (error) {
30 | console.log("Invalid age entered. Please enter a valid integer age.");
31 | }
32 | }
33 |
34 |
35 | // -------------------------------END---------------------------------
36 |
37 | // The program above is very dynamic while the program below is static
38 |
39 | // ------------------------------START--------------------------------
40 |
41 |
42 | // Program for checking voter age
43 |
44 | const age = parseInt(prompt("Enter your age:"));
45 |
46 | // Check if the age is within a valid range for voting
47 | if (age >= 18 && age <= 120) {
48 | console.log("Congratulations!");
49 | console.log("You are eligible to vote.");
50 | } else if (age >= 12 && age < 18) {
51 | console.log("You are not yet eligible to vote.");
52 | console.log("Enjoy your teenage years!");
53 | } else if (age >= 0 && age < 12) {
54 | console.log("You are too young to vote.");
55 | console.log("Make the most of your childhood!");
56 | } else if (age < 0) {
57 | console.log("Invalid age entered.");
58 | console.log("Please enter a positive value.");
59 | } else {
60 | console.log("You have surpassed the maximum voting age.");
61 | console.log("Thank you for your contribution to society!");
62 | }
63 |
--------------------------------------------------------------------------------
/armstrong_number.js:
--------------------------------------------------------------------------------
1 | function isArmstrongNumber(n) {
2 | const numDigits = String(n).length;
3 | let sumOfPowers = 0;
4 | let temp = n;
5 | while (temp > 0) {
6 | const digit = temp % 10;
7 | sumOfPowers += Math.pow(digit, numDigits);
8 | temp = Math.floor(temp / 10);
9 | }
10 | return n === sumOfPowers;
11 | }
12 |
13 | const user_input = prompt("Enter a number:");
14 | if (isArmstrongNumber(user_input)) {
15 | console.log('${user_input} is an Armstrong number.');
16 | } else {
17 | console.log('${user_input} is not an Armstrong number.');
18 | }
19 |
20 | //-----------------------------------------------------------------------
21 |
22 | function isArmstrongNumber(n) {
23 | const numDigits = String(n).length;
24 | let sumOfPowers = 0;
25 | let temp = n;
26 | while (temp > 0) {
27 | const digit = temp % 10;
28 | sumOfPowers += Math.pow(digit, numDigits);
29 | temp = Math.floor(temp / 10);
30 | }
31 | return n === sumOfPowers;
32 | }
33 |
34 | console.log(isArmstrongNumber(153));
35 |
36 | // Output: true
37 |
--------------------------------------------------------------------------------
/bit_manipulation.js:
--------------------------------------------------------------------------------
1 | let array = [1, 2, 3, 4];
2 | let length = 1 << array.length;
3 |
4 | for (let varValue = 0; varValue < length; varValue++) {
5 | let number = varValue;
6 | let position = 0;
7 | let storeArray = [];
8 |
9 | while (number !== 0) {
10 | if (number & (1 << 0)) {
11 | storeArray.push(array[position]);
12 | }
13 | number = number >> 1;
14 | position = position + 1;
15 | }
16 |
17 | console.log(storeArray);
18 | }
19 |
--------------------------------------------------------------------------------
/english_voice_assistant.js:
--------------------------------------------------------------------------------
1 | const readline = require('readline');
2 | const open = require('open');
3 | const axios = require('axios');
4 | const cheerio = require('cheerio');
5 |
6 | const rl = readline.createInterface({
7 | input: process.stdin,
8 | output: process.stdout
9 | });
10 |
11 | function openWeatherReport(city) {
12 | console.log(`Opening the weather report for ${city}.`);
13 | axios.get(`https://www.weather-forecast.com/locations/${city}/forecasts/latest`)
14 | .then(response => {
15 | const $ = cheerio.load(response.data);
16 | const weatherElements = $('.b-forecast__table-description-content');
17 | weatherElements.each((index, element) => {
18 | console.log($(element).text().trim());
19 | });
20 | })
21 | .catch(error => {
22 | console.log('Failed to fetch weather information. Please try again later.');
23 | });
24 | }
25 |
26 | function fatherOfTheNationOfBangladesh() {
27 | console.log('The Father of the Nation Bangabandhu Sheikh Mujibur Rahman is the architect of independent Bangladesh.');
28 | console.log('He played a vital role in the liberation movement and is revered as a national hero.');
29 | }
30 |
31 | function getIPAddress() {
32 | axios.get('https://checkip.amazonaws.com')
33 | .then(response => {
34 | const ipAddress = response.data.trim();
35 | console.log(`Your IP address is: ${ipAddress}`);
36 | })
37 | .catch(error => {
38 | console.log('Failed to retrieve IP address. Please try again later.');
39 | });
40 | }
41 |
42 | function openWikipedia() {
43 | open('https://www.wikipedia.org/')
44 | .catch(() => {
45 | console.log('Failed to open Wikipedia. Please try again later.');
46 | });
47 | }
48 |
49 | function searchOnWikipedia() {
50 | rl.question('What would you like to search on Wikipedia? ', query => {
51 | open(`https://en.wikipedia.org/wiki/${encodeURIComponent(query)}`)
52 | .catch(() => {
53 | console.log('Failed to search on Wikipedia. Please try again later.');
54 | });
55 | rl.close();
56 | });
57 | }
58 |
59 | function searchOnYouTube() {
60 | rl.question('What would you like to search on YouTube? ', query => {
61 | open(`https://www.youtube.com/results?search_query=${encodeURIComponent(query)}`)
62 | .catch(() => {
63 | console.log('Failed to search on YouTube. Please try again later.');
64 | });
65 | rl.close();
66 | });
67 | }
68 |
69 | function playOnYouTube() {
70 | rl.question('What would you like to play on YouTube? ', query => {
71 | open(`https://www.youtube.com/results?search_query=${encodeURIComponent(query)}`)
72 | .catch(() => {
73 | console.log('Failed to play on YouTube. Please try again later.');
74 | });
75 | rl.close();
76 | });
77 | }
78 |
79 | function openYouTube() {
80 | open('https://www.youtube.com/')
81 | .catch(() => {
82 | console.log('Failed to open YouTube. Please try again later.');
83 | });
84 | }
85 |
86 | function getDateAndTime() {
87 | const currentDate = new Date();
88 | const dateTime = currentDate.toLocaleString('en-US', { dateStyle: 'short', timeStyle: 'short' });
89 | console.log(`The current date and time is: ${dateTime}`);
90 | }
91 |
92 | function getLocalTime() {
93 | const currentTime = new Date().toLocaleTimeString('en-US');
94 | console.log(`The current local time is: ${currentTime}`);
95 | }
96 |
97 | function getTodayDate() {
98 | const currentDate = new Date();
99 | const todayDate = currentDate.toLocaleDateString('en-US');
100 | console.log(`Today's date is: ${todayDate}`);
101 | }
102 |
103 | function openFacebook() {
104 | open('https://www.facebook.com/')
105 | .catch(() => {
106 | console.log('Failed to open Facebook. Please try again later.');
107 | });
108 | }
109 |
110 | function openFacebookProfile() {
111 | open('https://www.facebook.com/profile.php')
112 | .catch(() => {
113 | console.log('Failed to open Facebook profile. Please try again later.');
114 | });
115 | }
116 |
117 | function openFacebookSettings() {
118 | open('https://www.facebook.com/settings')
119 | .catch(() => {
120 | console.log('Failed to open Facebook settings. Please try again later.');
121 | });
122 | }
123 |
124 | function openFacebookReel() {
125 | open('https://www.facebook.com/reels')
126 | .catch(() => {
127 | console.log('Failed to open Facebook Reels. Please try again later.');
128 | });
129 | }
130 |
131 | function openFacebookMessenger() {
132 | open('https://www.messenger.com/')
133 | .catch(() => {
134 | console.log('Failed to open Facebook Messenger. Please try again later.');
135 | });
136 | }
137 |
138 | function openFacebookVideo() {
139 | open('https://www.facebook.com/videos')
140 | .catch(() => {
141 | console.log('Failed to open Facebook videos. Please try again later.');
142 | });
143 | }
144 |
145 | function openFacebookNotification() {
146 | open('https://www.facebook.com/notifications')
147 | .catch(() => {
148 | console.log('Failed to open Facebook notifications. Please try again later.');
149 | });
150 | }
151 |
152 | function openGoogleBrowser() {
153 | open('https://www.google.com/')
154 | .catch(() => {
155 | console.log('Failed to open Google. Please try again later.');
156 | });
157 | }
158 |
159 | function openGoogleMail() {
160 | open('https://mail.google.com/')
161 | .catch(() => {
162 | console.log('Failed to open Google Mail. Please try again later.');
163 | });
164 | }
165 |
166 | function openGoogleEarth() {
167 | open('https://www.google.com/earth/')
168 | .catch(() => {
169 | console.log('Failed to open Google Earth. Please try again later.');
170 | });
171 | }
172 |
173 | function googleEarthSpecifyCity() {
174 | rl.question('Which city do you want to see on Google Earth? ', city => {
175 | open(`https://www.google.com/earth/geo/${encodeURIComponent(city)}/`)
176 | .catch(() => {
177 | console.log('Failed to open Google Earth for the specified city. Please try again later.');
178 | });
179 | rl.close();
180 | });
181 | }
182 |
183 | function openGoogleMap() {
184 | open('https://www.google.com/maps/')
185 | .catch(() => {
186 | console.log('Failed to open Google Map. Please try again later.');
187 | });
188 | }
189 |
190 | function googleMapSpecifyCity() {
191 | rl.question('Which city do you want to see on Google Map? ', city => {
192 | open(`https://www.google.com/maps/place/${encodeURIComponent(city)}/`)
193 | .catch(() => {
194 | console.log('Failed to open Google Map for the specified city. Please try again later.');
195 | });
196 | rl.close();
197 | });
198 | }
199 |
200 | function googleTranslateSpecifyWord() {
201 | rl.question('Which word or sentence do you want to translate to English? ', text => {
202 | open(`https://translate.google.com/#auto/en/${encodeURIComponent(text)}`)
203 | .catch(() => {
204 | console.log('Failed to open Google Translate. Please try again later.');
205 | });
206 | rl.close();
207 | });
208 | }
209 |
210 | function tellJoke() {
211 | axios.get('https://www.jokes4us.com/miscellaneousjokes/cleanjokes.html')
212 | .then(response => {
213 | const $ = cheerio.load(response.data);
214 | const jokeElements = $('div[style="font-size:medium;"]');
215 | jokeElements.each((index, element) => {
216 | console.log($(element).text().trim());
217 | });
218 | })
219 | .catch(error => {
220 | console.log('Failed to fetch a joke. Please try again later.');
221 | });
222 | }
223 |
224 | function translateLanguages() {
225 | rl.question('Which language do you want to translate from? ', fromLanguage => {
226 | rl.question('Which language do you want to translate to? ', toLanguage => {
227 | rl.question('What do you want to translate? ', text => {
228 | open(`https://translate.google.com/#${encodeURIComponent(fromLanguage)}/${encodeURIComponent(toLanguage)}/${encodeURIComponent(text)}`)
229 | .catch(() => {
230 | console.log('Failed to open Google Translate. Please try again later.');
231 | });
232 | rl.close();
233 | });
234 | });
235 | });
236 | }
237 |
238 | function availableCommands() {
239 | console.log('Available commands:');
240 | console.log('- Weather: Get the weather report of a city');
241 | console.log('- Father of the Nation of Bangladesh: Learn about the Father of the Nation of Bangladesh');
242 | console.log('- IP address: Get your IP address');
243 | console.log('- Opening Wikipedia: Open the Wikipedia homepage');
244 | console.log('- Search on Wikipedia: Search for a specific topic on Wikipedia');
245 | console.log('- Search on YouTube: Search for a video on YouTube');
246 | console.log('- Play on YouTube: Search and play a video on YouTube');
247 | console.log('- Open YouTube: Open the YouTube homepage');
248 | console.log('- Date and Time: Get the current date and time');
249 | console.log('- Today\'s Time: Get the current local time');
250 | console.log('- Today\'s Date: Get today\'s date');
251 | console.log('- Opening Facebook: Open the Facebook homepage');
252 | console.log('- Facebook Profile: Open your Facebook profile');
253 | console.log('- Facebook Settings: Open the Facebook settings page');
254 | console.log('- Facebook Reels: Open Facebook Reels');
255 | console.log('- Facebook Messenger: Open Facebook Messenger');
256 | console.log('- Facebook Video: Open Facebook videos');
257 | console.log('- Facebook Notification: Open Facebook notifications');
258 | console.log('- Opening Google: Open the Google homepage');
259 | console.log('- Opening Gmail: Open Google Mail');
260 | console.log('- Google Earth: Open Google Earth');
261 | console.log('- Google City: View a city on Google Earth');
262 | console.log('- Google Map: Open Google Map');
263 | console.log('- City from Map: View a city on Google Map');
264 | console.log('- Translate to English: Translate a word or sentence to English');
265 | console.log('- Listen a Joke: Listen to a joke');
266 | console.log('- Translation between two languages: Translate text between two languages');
267 | console.log('- What can you do: Get the list of available commands');
268 | console.log('- Who made you: Know who made this digital assistant');
269 | console.log('- What is your name: Know the name of this digital assistant');
270 | console.log('- Ask: Ask a computational or geographical question');
271 | }
272 |
273 | function whoMadeYou() {
274 | console.log('I was created by Sk. Salahuddin from Khulna, Bangladesh.');
275 | }
276 |
277 | function whatIsYourName() {
278 | console.log('My name is Digital Assistant.');
279 | }
280 |
281 | function computationalGeographicalQuestion() {
282 | console.log('Please ask your question:');
283 | rl.question('', question => {
284 | console.log('Sorry, I\'m unable to answer computational or geographical questions at the moment.');
285 | rl.close();
286 | });
287 | }
288 |
289 | console.log('Sk. Salahuddin - Khulna');
290 |
291 | rl.question('How may I assist you? ', userCommand => {
292 | userCommand = userCommand.toLowerCase();
293 |
294 | if (userCommand.includes('exit') || userCommand.includes('close') || userCommand.includes('off') ||
295 | userCommand.includes('good bye') || userCommand.includes('bye') || userCommand.includes('ok bye') ||
296 | userCommand.includes('turn off') || userCommand.includes('shutdown') || userCommand.includes('no thanks') ||
297 | userCommand.includes('stop')) {
298 | console.log('Assistant Shut Down');
299 | console.log('Take care and see you later');
300 | rl.close();
301 | } else {
302 | console.log('Please wait');
303 | performAction(userCommand);
304 | }
305 | });
306 |
--------------------------------------------------------------------------------
/factorial.js:
--------------------------------------------------------------------------------
1 | function calculateFactorial(n) {
2 | if (n > 1) {
3 | return n * calculateFactorial(n - 1);
4 | } else {
5 | return 1;
6 | }
7 | }
8 |
9 | let number = parseInt(prompt("Enter a non-negative number:"));
10 | let result = calculateFactorial(number);
11 | console.log(`Factorial of ${number} = ${result}`);
12 |
--------------------------------------------------------------------------------
/kaprekar_constant.js:
--------------------------------------------------------------------------------
1 | function kaprekarConstant(n) {
2 | let count = 0;
3 | while (n !== 6174) {
4 | count++;
5 | let digits = n.toString().padStart(4, '0');
6 | let ascending = Number(digits.split('').sort().join(''));
7 | let descending = Number(digits.split('').sort().reverse().join(''));
8 | n = descending - ascending;
9 | }
10 | return count;
11 | }
12 |
13 | const user_input = prompt("Enter a number:");
14 | const steps = kaprekarConstant(user_input);
15 | console.log(`Number of steps to reach Kaprekar constant: ${steps}`);
16 |
17 | //------------------------------------------------------------------------------------
18 |
19 | function kaprekarConstant(n) {
20 | let count = 0;
21 | while (n !== 6174) {
22 | count++;
23 | let digits = n.toString().padStart(4, '0');
24 | let ascending = Number(digits.split('').sort().join(''));
25 | let descending = Number(digits.split('').sort().reverse().join(''));
26 | n = descending - ascending;
27 | }
28 | return count;
29 | }
30 |
31 | console.log(kaprekarConstant(1234));
32 |
33 | // Output: 3
34 |
--------------------------------------------------------------------------------
/knapsack.js:
--------------------------------------------------------------------------------
1 | function stackSack(items, weight, value, number) {
2 | const knapsack = new Array(number + 1).fill(0).map(() => new Array(items + 1).fill(0));
3 |
4 | // Build table for knapsack[][] in bottom-up manner
5 | for (let i = 0; i <= number; i++) {
6 | for (let j = 0; j <= items; j++) {
7 | if (i === 0 || j === 0) {
8 | knapsack[i][j] = 0;
9 | } else if (weight[i - 1] <= j) {
10 | knapsack[i][j] = Math.max(value[i - 1] + knapsack[i - 1][j - weight[i - 1]], knapsack[i - 1][j]);
11 | } else {
12 | knapsack[i][j] = knapsack[i - 1][j];
13 | }
14 | }
15 | }
16 |
17 | return knapsack[number][items];
18 | }
19 |
20 | const value = [60, 100, 120];
21 | const weight = [10, 20, 30];
22 | const items = 50;
23 | const number = value.length;
24 |
25 | const result = stackSack(items, weight, value, number);
26 | console.log(result);
27 |
--------------------------------------------------------------------------------
/minimum_difficulty_of_a_job_schedule.js:
--------------------------------------------------------------------------------
1 | class Solution {
2 | minDifficulty(jobDifficulty, d) {
3 | const n = jobDifficulty.length;
4 | if (n < d) {
5 | return -1;
6 | }
7 |
8 | const memo = new Array(n).fill(null).map(() => new Array(d + 1).fill(-1));
9 |
10 | return this.dp(jobDifficulty, 0, d, memo);
11 | }
12 |
13 | dp(jobDifficulty, i, d, memo) {
14 | if (d === 1) {
15 | let maxDifficulty = -Infinity;
16 | for (let j = i; j < jobDifficulty.length; j++) {
17 | maxDifficulty = Math.max(maxDifficulty, jobDifficulty[j]);
18 | }
19 | return maxDifficulty;
20 | }
21 |
22 | if (i === jobDifficulty.length - 1) {
23 | return Infinity;
24 | }
25 |
26 | if (memo[i][d] !== -1) {
27 | return memo[i][d];
28 | }
29 |
30 | let curDifficulty = jobDifficulty[i];
31 | let minDifficulty = Infinity;
32 |
33 | for (let j = i; j < jobDifficulty.length - d + 1; j++) {
34 | curDifficulty = Math.max(curDifficulty, jobDifficulty[j]);
35 | const change = curDifficulty + this.dp(jobDifficulty, j + 1, d - 1, memo);
36 | minDifficulty = Math.min(minDifficulty, change);
37 | }
38 |
39 | memo[i][d] = minDifficulty;
40 | return minDifficulty;
41 | }
42 | }
43 |
44 | const jobDifficulty = [6, 5, 4, 3, 2, 1];
45 | const days = 2;
46 |
47 | const solution = new Solution();
48 | const result = solution.minDifficulty(jobDifficulty, days);
49 |
50 | console.log("Minimum difficulty:", result);
51 |
--------------------------------------------------------------------------------
/most_occuring_character.js:
--------------------------------------------------------------------------------
1 | function findMostOccChar(string) {
2 | const charCount = {};
3 |
4 | // Count the occurrence of each character in the string
5 | for (let char of string) {
6 | charCount[char] = (charCount[char] || 0) + 1;
7 | }
8 |
9 | let maxCount = 0;
10 | for (let count of Object.values(charCount)) {
11 | if (count > maxCount) {
12 | maxCount = count;
13 | }
14 | }
15 |
16 | const mostOccChars = [];
17 | for (let char in charCount) {
18 | if (charCount[char] === maxCount) {
19 | mostOccChars.push(char);
20 | }
21 | }
22 |
23 | // Printing the most occurring character(s) and its count
24 | for (let char of mostOccChars) {
25 | console.log(`Character: ${char}, Count: ${maxCount}`);
26 | }
27 | }
28 |
29 | // Driver program
30 | const inputString = 'helloworldmylovelypython';
31 | findMostOccChar(inputString);
32 |
--------------------------------------------------------------------------------
/palindrome.js:
--------------------------------------------------------------------------------
1 | function isPalindrome(s) {
2 | s = s.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
3 | return s === s.split('').reverse().join('');
4 | }
5 |
6 | const user_input = prompt("Enter a string:");
7 | if (isPalindrome(user_input)) {
8 | console.log(`'${user_input}' is a palindrome.`);
9 | } else {
10 | console.log(`'${user_input}' is not a palindrome.`);
11 | }
12 |
13 | //--------------------------------------------------------------
14 |
15 | function isPalindrome(s) {
16 | s = s.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
17 | return s === s.split('').reverse().join('');
18 | }
19 |
20 | console.log(isPalindrome("A man, a plan, a canal: Panama"));
21 |
22 | // Output: true
23 |
--------------------------------------------------------------------------------
/sorting_array.js:
--------------------------------------------------------------------------------
1 | function areArraysEqual(array1, array2) {
2 | const length1 = array1.length;
3 | const length2 = array2.length;
4 |
5 | if (length1 !== length2) {
6 | return false;
7 | }
8 |
9 | // Sort both arrays
10 | array1.sort((a, b) => a - b);
11 | array2.sort((a, b) => a - b);
12 |
13 | // Linearly compare elements
14 | for (let i = 0; i < length1; i++) {
15 | if (array1[i] !== array2[i]) {
16 | return false;
17 | }
18 | }
19 |
20 | // If all elements are the same
21 | return true;
22 | }
23 |
24 | const array1 = [3, 5, 2, 5, 2];
25 | const array2 = [2, 3, 5, 5, 2];
26 |
27 | if (areArraysEqual(array1, array2)) {
28 | console.log("The arrays are equal");
29 | } else {
30 | console.log("The arrays are not equal");
31 | }
32 |
--------------------------------------------------------------------------------
/wifi_password.js:
--------------------------------------------------------------------------------
1 | class WifiProfile {
2 | constructor(ssid, password) {
3 | this.ssid = ssid;
4 | this.password = password;
5 | }
6 |
7 | toString() {
8 | return `SSID: ${this.ssid}, Password: ${this.password}`;
9 | }
10 | }
11 |
12 | function getWifiProfiles() {
13 | const wifiList = [];
14 |
15 | const command = 'netsh wlan show profiles';
16 | const commandOutput = require('child_process').execSync(command).toString();
17 |
18 | const profileRegex = / All User Profile\s+: (.*)\r/g;
19 | let match;
20 | while ((match = profileRegex.exec(commandOutput))) {
21 | const profile = match[1];
22 |
23 | const profileCommand = `netsh wlan show profile "${profile}" key=clear`;
24 | const profileOutput = require('child_process').execSync(profileCommand).toString();
25 |
26 | if (!profileOutput.includes('Security key : Absent')) {
27 | const password = profileOutput.match(/Key Content\s+: (.*)\r/)[1];
28 | wifiList.push(new WifiProfile(profile, password));
29 | }
30 | }
31 |
32 | return wifiList;
33 | }
34 |
35 | const wifiList = getWifiProfiles();
36 |
37 | wifiList.forEach((wifiProfile) => {
38 | console.log(wifiProfile.toString());
39 | });
40 |
--------------------------------------------------------------------------------