Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Code to flatten an array to a given depth in JavaScript


Here is the code to flatten an array to a given depth in JavaScript. There are many ways to code it but using recursion is perhaps the smartest way of them all.

//code1

let sample = [[1, 2, 3], [1, 2, [4, 5]], [2, 3, 78, [10, 11, 22]], 1, 3345];

function flattenArray(arr, depth = 1) {
  let flattenedArray = [];
  for (let j = 0; j < arr.length; j++) {
    if (Array.isArray(arr[j]) && depth > 0) {
      flattenedArray.push(...flattenArray(arr[j], depth - 1));
    } else {
      flattenedArray.push(arr[j]);
    }
  }
  return flattenedArray;
};
console.log(flattenArray(sample, 2));

//code2

let sample = [[1, 2, 3], [1, 2, [4, 5]], [2, 3, 78, [10, 11, 22]], 1, 3345];

Array.prototype.flattenArray = function (depth = 1) {
  let flattenedArray = [];
  for (let element of this) {
    if (Array.isArray(element) && depth > 0) {
      flattenedArray.push(...element.flattenArray(depth - 1));
    } else {
      flattenedArray.push(element);
    }
  }
  return flattenedArray;
};
console.log(sample.flattenArray(2));

Coding a popup box with more than 1 input in JavaScript

It is extremely simple to code a popup box with more than 1 input in JavaScript. Here is the code snippet for your reference. (Run Code)

var mywindow = window.open("", "_blank", "width=400, height=200");

mywindow.moveTo(450, 50);

function ok() {
var name = mywindow.document.getElementById('name').value;
var pass = mywindow.document.getElementById('pass').value;
mywindow.close();
alert('Name: ' + name + ' Password: ' + pass);
}

function cancel() {
mywindow.close();
}

mywindow.document.open();

mywindow.document.write("<html>
<head>
<title>Popup Box with 2 inputs | 10xCoderKids</title>
</head>
<body>
<p>Please enter your details:</p>
Name: <input id='name' /><br><br>
Password: <input id='pass' /><br><br>
<button id='submit'>Ok</button>
<button id='cancel'>Cancel</button>
</body>
</html>");

mywindow.document.getElementById('submit').addEventListener('click',function(){
ok();
})

mywindow.document.getElementById('cancel').addEventListener('click',function(){
cancel();
})

mywindow.document.close();

Bitwise in JavaScript

Please refer to the video to understand Bitwise in JavaScript.

The table below is referred to in the video and will be handy in understanding the signed binary numbers.

4-bit Signed Binary Number Comparison

DecimalSigned MagnitudeSigned One’s ComplementSigned Two’s Complement
+7011101110111
+6011001100110
+5010101010101
+4010001000100
+3001100110011
+2001000100010
+1000100010001
+0000000000000
-010001111
-1100111101111
-2101011011110
-3101111001101
-4110010111100
-5110110101011
-6111010011010
-7111110001001

Coding AddMul Series in JavaScript

This program takes 2 pair of numbers and we first add them and then multiply them. For example 11 and 11 = 4 because (1 + 1) * (1 + 1) = 4.


Code (Run Code) :

// This program takes 2 pair of numbers and we first add them and then multiply them. For example 11 and 11 = 4 because (1 + 1) * (1 + 1) = 4

function addMulSeries() {
var arr = [];
var num = [];
for (var i = 1; i < 11; i++) {
arr.push(i);
}

for (i of arr) {
num.push((i + i) * (i + i));
}

document.write(num);
}

addMulSeries();

JavaScript prototype to find co-primes

Co-primes are numbers whose common factor is only 1. For example :- 4, 9
Factors of 4 :- 2, 2, 1
Factors of 9 :- 3, 3, 1
Common Factor :- 1

Here is the JavaScript prototype to find co-primes. Here is the code snippet.


Code (
Run Code):

function factors(num) {
arr = [];
for (var i = 1; i < num; i++) {
if (num % i == 0) {
arr.push(i);
}
}
return arr;
}

function coPrime(num1, num2) {
arr1 = factors(num1);
arr2 = factors(num2);
for (var i = 1; i < arr1.length; i++) {
for (var j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
return num1 + ' and ' + num2 + ' are not co-prime';
}
}
}
return num1 + ' and ' + num2 + ' are co-prime';
}

function main() {
document.getElementById('result').innerHTML =
(coPrime(document.getElementById('num1').value, document.getElementById('num2').value))
}

JavaScript prototype to find opposite primes

Opposite Primes are prime numbers that have the same digits but in reverse order.

Here is the JavaScript prototype to find opposite primes up to a maximum limit of 100. Here is the code snippet.


Code (
Run Code):

function checkPrime(num) {
if (num == 1) {
return false;
} else if (num == 2) {
return true;
}

for (var x = 2; x < num; x++) {
if (num % x == 0) {
return false;
}
}
return true;
}

function primeNumbers(num) {
var arr = [];
for (var j = 2; j < num; j++) {
if (checkPrime(j)) {
arr.push(j);
}
}
return arr;
}

function oppositePrimes() {
var num = Number(document.getElementById('num').value);
var arr = primeNumbers(num);
var text = '';
text += 'Prime numbers till ' + num + ' are: ';
text += '<br>' + arr;
text += '<br> Opposite Primes:'
for (var i = 0; i < arr.length; i++) {
for (var x = i + 1; x < arr.length; x++) {
if (arr[i].toString()[0] ===
arr[x].toString()[1] && arr[i].toString()[1] === arr[x].toString()[0]) {
text += '<br>' + arr[i] + ' and ' + arr[x];
}
}
}
document.getElementById('result').innerHTML = text;
}

JavaScript prototype to find twin primes

When 2 prime numbers are subtracted and their result is 2 then they are known as twin primes.

Here is the JavaScript prototype to find twin primes up to a given limit. Here is the code snippet.


Code (Run Code):

arr = [];

function checkPrime(num) {
if (num == 1) {
return false;
} else if (num == 2) {
return true;
}

for (var x = 2; x < num; x++) {
if (num % x == 0) {
return false;
}
}
return true;
}

function primeNumbers() {
num = Number(document.getElementById('number').value);
for (var j = 1; j < num; j++) {
if (checkPrime(j)) {
arr.push(j);
}
}
}

function twinPrimes() {
var text = '';
arr = [];
primeNumbers();
text += 'Prime Numbers:';
text += '<br>' + arr;
text += '<br> Twin Primes:'
for (var i = 0; i < arr.length; i++) {
for (var x = i + 1; x < arr.length; x++) {
if ((arr[i] - arr[x]) == -2) {
text += '<br>' + arr[x] + ' and ' + arr[i];
}
}
}
document.getElementById('result').innerHTML = text;
}

JavaScript 'For Loops'

A little glimpse into JavaScript 'For Loops'. 


Code:

arr = ['Fortran', 'Python', 'C++', 'Assembly', 'Binary'];

for (x in arr) {
document.write(x);
}
document.write('<br>');
for (var i = 0; i < arr.length; i++) {
document.write(i);
}
document.write('<br>');
for (x of arr) {
document.write(x + ' ');
}
document.write('<br>');
for (var i = 0; i < arr.length; i++) {
document.write(arr[i] + ' ');
}

Result:

01234
01234
Fortran Python C++ Assembly Binary
Fortran Python C++ Assembly Binary

JavaScript prototype to find two primes whose sum is the given number

This program finds two prime numbers whose sum is the number provided by the user.

Took 8 minutes and 3 seconds to code JavaScript prototype to find two primes whose sum is the given number. Here is the code snippet.


Code (Run Code):

function checkPrime(num) {
if (num == 1) {
return false;
} else if (num == 2) {
return true;
}

for (var x = 2; x < num; x++) {
if (num % x == 0) {
return false;
}
}
return true;
}

function primeSum(num) {
arr = [];
for (var i = 2; i < num; i++) {
if (checkPrime(i)) {
arr.push(i);
}
}
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr.length; j++) {
if (arr[i] + arr[j] == num) {
return arr[i] + ' + ' + arr[j] + ' = ' + num;
}
}
}
}

function main(){
document.getElementById("result").innerHTML =
primeSum(document.getElementById("num").value);
}

JavaScript prototype to calculate LCM of two numbers

LCM is Lowest Common Multiple. For example :- LCM of 4 and 6 is 12.
Prime Factors of 4 = 2, 2
Prime Factors of 6 = 2, 3
So the LCM of 4 and 6 is 2 x 2 x 3 = 12.

Took 15 minutes and 21 seconds to code JavaScript prototype to calculate LCM of two numbers. Here is the code snippet. 


Code (Run Code):

function checkPrime(num) {
if (num == 1) {
return false;
} else if (num == 2) {
return true;
}

for (var x = 2; x < num; x++) {
if (num % x == 0) {
return false;
}
}
return true;
}

function primeFactor(num) {
for (var i = 2; i < num; i++) {
if (num % i == 0) {
return i;
}
}
}

function primeFactors(num) {
arr = [];
x = num;
while (!checkPrime(x)) {
arr.push(primeFactor(x));
x = x / primeFactor(x);
}
arr.push(x);
return arr;
}

function calculateLCM(num1, num2) {
arr1 = primeFactors(num1);
arr2 = primeFactors(num2);
arr3 = [];
for (var i = 0; i < arr1.length; i++) {
arr3.push(arr1[i])
for (var j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
delete arr2[j];
break;
}
}
}
for (var i = 0; i < arr2.length; i++) {
if (arr2[i] != undefined) {
arr3.push(arr2[i]);
}
}
product = arr3[0];
for (var y = 1; y < arr3.length; y++) {
product *= arr3[y];
}
return product;
}

function main(){
document.getElementById("result").innerHTML =
calculateLCM(document.getElementById("num1").value, document.getElementById("num2").value);
}

JavaScript prototype to calculate HCF of two numbers

HCF is Highest Common Factor. For example :- HCF of 4 and 6 is 2.
Prime Factors of 4 = 2, 2 
Prime Factors of 6 = 2, 3 
So 2 is common in both, hence the HCF of 4 and 6 is 2.

Took  32 minutes and 25 seconds to code JavaScript prototype to calculate HCF of two numbers. Here is the code snippet.


Code (Run Code):

function checkPrime(num) {
if (num == 1) {
return false;
} else if (num == 2) {
return true;
}

for (var x = 2; x < num; x++) {
if (num % x == 0) {
return false;
}
}
return true;
}

function primeFactor(num) {
for (var i = 2; i < num; i++) {
if (num % i == 0) {
return i;
}
}
}

function primeFactors(num) {
arr = [];
x = num;
while (!checkPrime(x)) {
arr.push(primeFactor(x));
x = x / primeFactor(x);
}
arr.push(x);
return arr;
}

function calculateHCF(num1, num2) {
arr1 = primeFactors(num1);
arr2 = primeFactors(num2);
arr3 = [];
for (var i = 0; i < arr1.length; i++) {
for (var j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
arr3.push(arr1[i]);
delete arr1[i];
delete arr2[j];
}
}
}
product = arr3[0];
for (var y = 1; y < arr3.length; y++) {
product *= arr3[y];
}
if (product == undefined) {
return 1;
} else {
return product;
}
}

function main(){
document.getElementById("result").innerHTML =
calculateHCF(document.getElementById("num1").value, document.getElementById("num2").value);
}

JavaScript code to find prime factors

Took 4 minutes and 48 seconds to code JavaScript prototype to find prime factors of a given number. Here is the code snippet.

Code (Run Code):

function checkPrime(num) {
if (num == 1) {
return false;
} else if (num == 2) {
return true;
}

for (var x = 2; x < num; x++) {
if (num % x == 0) {
return false;
}
}
return true;
}

function primeFactor(num) {
for (var i = 2; i < num; i++) {
if (num % i == 0) {
return i;
}
}
}

function primeFactors(num) {
arr = [];
x = num;
while (!checkPrime(x)) {
arr.push(primeFactor(x));
x = x / primeFactor(x);
}
arr.push(x);
return arr;
}

function main() {
document.getElementById('demo').innerHTML =
primeFactors(document.getElementById('num').value);
}

JavaScript code to generate composite number series

Took only 59 seconds to code JavaScript prototype to generate composite number series. Here is the code snippet.

Code (Run Code):

arr = [];
function checkComposite(num) {
if (num == 1) {
return false;
} else if (num == 2) {
return false;
}

for (var x = 2; x < num; x++) {
if (num % x == 0) {
return true;
}
}
return false;
}

function compositeNumbers() {
num = Number(document.getElementById('number').value);
for (var j = 1; j < num; j++) {
if (checkComposite(j)) {
arr.push(j);
}
}
document.getElementById('result').innerHTML = arr;
}

JavaScript code to check for composite numbers

Took 5 minutes and 22 seconds to code JavaScript prototype to check for composite numbers. Here is the code snippet.

Code (Run Code):

function checkComposite(num) {
if (num == 1) {
return num + ' is not a prime number and not a composite number';
} else if (num == 2) {
return num + ' is not a composite number';
}

for (var x = 2; x < num; x++) {
if (num % x == 0) {
return num + ' is a composite number';
}
}
return num + ' is not a composite number';
}

function main(){
document.getElementById("result").innerHTML =
checkComposite(document.getElementById("num").value);
}

JavaScript code to generate prime number series

Took only 55 seconds to code JavaScript prototype to generate prime number series. Here is the code snippet.

Code (Run Code):

arr = [];

function checkPrime(num) {
if (num == 1) {
return false;
} else if (num == 2) {
return true;
}

for (var x = 2; x < num; x++) {
if (num % x == 0) {
return false;
}
}
return true;
}

function primeNumbers() {
num = Number(document.getElementById('number').value);
for (var j = 1; j < num; j++) {
if (checkPrime(j)) {
arr.push(j);
}
}
document.getElementById('result').innerHTML = arr;
}

JavaScript code to check for prime numbers

Took 10 minutes and 16 seconds to code JavaScript prototype to check for prime numbers. Here is the code snippet.

Code (Run Code):

function checkPrime(num) {
if (num == 1) {
return num + ' is not a prime number and not a composite number';
} else if (num == 2) {
return num + ' is a prime number';
}

for (var x = 2; x < num; x++) {
if (num % x == 0) {
return num + ' is not a prime number';
}
}
return num + ' is a prime number';
}

function main(){
document.getElementById("result").innerHTML =
checkPrime(document.getElementById("num").value);
}

A simple calculator coded in JavaScript

Took 19 minutes and 28 seconds to code a simple calculator in JavaScript. Here is the code snippet.


Code (Run Code):

function calculator() {
var operand1 = Number(document.getElementById('operand1').value);
var operator = document.getElementById('operator').value;
var operand2 = Number(document.getElementById('operand2').value);
switch(operator) {
case '+':
text = operand1 + ' + ' + operand2 + ' = ' + (operand1 + operand2);
break;
case '-':
text = operand1 + ' - ' + operand2 + ' = ' + (operand1 - operand2);
break;
case 'x':
case '*':
text = operand1 + ' x ' + operand2 + ' = ' + (operand1 * operand2);
break;
case '/':
text = operand1 + ' / ' + operand2 + ' = ' + (operand1 / operand2);
break;
case '**':
text = operand1 + ' ** ' + operand2 + ' = ' + (operand1 ** operand2);
break;
case '%':
text = operand1 + ' % ' + operand2 + ' = ' + (operand1 % operand2);
break;
default:
text = 'Sorry we could not calculate your equation';
}

if (isNaN(operand1) || isNaN(operand2)) {
text = 'Sorry we could not calculate your equation';
}

document.getElementById('result').innerHTML = text;
}

JavaScript method to return random number in a range (exclusive of the min limit)

Took 2 minutes and 6 seconds to code JavaScript method to return random number in a range exclusive of the min limit. Here is the code snippet.

Code:

function randomMaxInclusive(min, max) {
x = Math.floor(((Math.random() * max - min) + min) + 1);
return x;
}

x = randomMaxInclusive(0, 10)
document.write(x);

Result:

10

JavaScript method to return random number in a range (exclusive of the max limit)

Took 3 minutes and 21 seconds to code JavaScript method to return random number in a range exclusive of the max limit. Here is the code snippet.

Code:

function randomMaxExclusive(min, max) {
x = Math.floor((Math.random() * max - min) + min);
return x;
}

x = randomMaxExclusive(0, 10)
document.write(x);

Result:

4

JavaScript Boolean() method implementation

Took 1 minute and 3 seconds to code JavaScript Boolean() method. Here is the code snippet.

Code:

function boolean(condition) {
if (condition) {
return true;
} else {
return false;
}
}

document.write(boolean(0));

Result:

false

GITEX Dubai Talk by Saion Gupta and Saiasmi Gupta

Good morning, everyone. I'm Saion Gupta, the Founder of 10xCoderKids and the Guinness World Record holder for the youngest computer prog...