Javascript - Creating number with specific formula modulo11 - javascript

I created following generator for Czech tax number (IฤŒO). I know that there is certainly better way how to code that in javascript. I am beginner and I would like to see how to write my code properly. The number is created with special formula and it has 8didgits, tha last digit is based on modulo11 as you can see below in code.
Thanks for your replies.
//Generation of single random numbers as variables
var a = Math.floor(Math.random() * 10);
var b = Math.floor(Math.random() * 10);
var c = Math.floor(Math.random() * 10);
var d = Math.floor(Math.random() * 10);
var e = Math.floor(Math.random() * 10);
var f = Math.floor(Math.random() * 10);
var g = Math.floor(Math.random() * 10);
//Formula for tax number
var formula = a * 8 + b * 7 + c * 6 + d * 5 + e * 4 + f * 3 + g * 2;
var modulo11 = formula % 11;
if (modulo11 === 0) {
var h = 1;
} else if (modulo11 === 1) {
var h = 0;
} else {
var h = 11 - modulo11;
};
//Completing tax number
var identificationNumber = "" + a + b + c + d + e + f + g + h;
//displaying number in console
console.log(identificationNumber);

Take benefit from Array data structure to store a, b,...g.
Then "map" this array by (8- indexOfItem) * item
๐Ÿ‘‰๐Ÿผ so , for the 1หขแต— item which has index = 0 , we will have (8 - 0) * a -โžก 8* a.
๐Ÿ‘‰๐Ÿผ for the 2โฟแตˆ item โžก (8 -1) * b โžก 7 *b
๐Ÿ‘‰๐Ÿผ....so on.
Then use "reduce" to calculate the sum .
Then use "join" instead of ""+ a +b + ....+ g+ h
function getH(modulo11) {
if (modulo11 === 0) return 1;
if (modulo11 === 1) return 0;
return 11 - modulo11;
}
//Generation of single random numbers as variables
const numbers= Array.from({length: 7},(v, k) =>Math.floor(Math.random() * 10))
//Formula for tax number
const formula= numbers.map((n, i) => (8 - i) * n).reduce((total, next) => total+ next , 0)// alternative of sum : a * 8 + b * 7 + c * 6 + d * 5 + e * 4 + f * 3 + g * 2
const h= getH(formula % 11);
//Completing tax number
const identificationNumber = [...numbers, h].join('');
//displaying number in console
console.log(identificationNumber);

Related

SyntaxError: identifier starts immediately after numeric literal while trying to create a BigInt in javascript

I am trying to solve Pi till n number of digits in JavaScript with this formula:
#!/usr/bin/env js60
function calculatePi(n) {
var q = t = k = 1
var m = x = 3
var n = n + 1
var r = 0
str = ''
while (str.length < n) {
if (4 * q + r - t < m * t) {
str += m
var rr = r
r = 10 * (r - m * t)
m = Math.floor((10 * (3 * q + rr)) / t - 10 * m)
q = 10 * q
}
else {
m = Math.floor(((q * (7 * k + 2)) + (r * x)) / (t * x))
r = ((2 * q) + r) * x
t = t * x
q = q * k
k = k + 1
x = x + 2
}
}
return str.slice(0, 1) + '.' + str.slice(1)
}
print(calculatePi(19))
Here's how it works in a language with arbitrary length integer support.
But in JavaScript the code generate correct values till the 18 decimal places, and after that the number gets really big to work with. Worse, if the function is given a large number like 10000, it will run in a infinite loop.
When I am trying to write a big number with an n appended to it (as suggested here):
var a = 1000000000000000000000000000n
I get:
typein:1:8 SyntaxError: identifier starts immediately after numeric literal:
typein:1:8 var a = 1000000000000000000000000000n
typein:1:8 ........^
How can I represent an arbitrary length integer in JavaScript?
Thanks to the comments, changing the JS engine from SpiderMonkey to Node solved the issue. The final code looked like:
#!/usr/bin/env node
function calculatePi(n) {
var one = 1n, two = 2n, three = 3n, seven = 7n, ten = 10n
var q = t = k = one
var m = x = three
var n = BigInt(n) + one
var r = 0n
str = ''
while (str.length < n) {
if (4n * q + r - t < m * t) {
str += m
var rr = r
r = ten * (r - m * t)
m = (ten * (three * q + rr)) / t - ten * m
q *= ten
}
else {
t *= x
m = (q * (seven * k + two) + (r * x)) / t
r = ((two * q) + r) * x
q *= k
k += one
x += two
}
}
return str.slice(0, 1) + '.' + str.slice(1)
}
console.log(calculatePi(5000))
Now it can solve any digits using some system's memory (around 40 MiB for 5,000 digits).
The code removed Math.floor() function because BigInt calculation are Integers. A floating point number with arbitrary precision is not going to be calculated here.

How to get a for loop create a string of 9 random 1digit number?

I need to create a random number generator with 9 total digit created from a random 1 digit number generated thru a for loop .
This one works but i need to use a for loop for it :
var random1 = Math.floor(Math.random() * 9) + 1 ;
var random2 = Math.floor(Math.random() * 9) + 1 ;
var random3 = Math.floor(Math.random() * 9) + 1 ;
var random4 = Math.floor(Math.random() * 9) + 1 ;
var random5 = Math.floor(Math.random() * 9) + 1 ;
var random6 = Math.floor(Math.random() * 9) + 1 ;
var random7 = Math.floor(Math.random() * 9) + 1 ;
var random8 = Math.floor(Math.random() * 9) + 1 ;
var random9 = Math.floor(Math.random() * 9) + 1 ;
// ... and then dump the random number into our random-number div.
$("#random-number").text(""+ random1 + random2 + random3 + random4 + random5 + random6 + random7 + random8 + random9);
var results = ""+ random1 + random2 + random3 + random4 + random5 + random6 + random7 + random8 + random9 ;
$("#results").prepend(results + " <br>");
the above code works in creating a random 9 digit number but i need to use a for loop to make my code concise .
You can use for loop. Create a string and in each loop concentrate the new random number with that string.
let random = '';
for(let i =0;i<9;i++){
random += Math.floor(Math.random() * 9) + 1 ;
}
$("#random-number").text(random);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="random-number"></div>
Another way can be using map() and join()
let random = [...Array(9)].map(x => Math.floor(Math.random() * 9) + 1).join('')
$("#random-number").text(random);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="random-number"></div>
You can try this way with all digits is in range [0, 9] and you should relize that first digit can be zero:
var digits = [];
for (let i=0; i<9; i++) {
let n = Math.floor(Math.random()*10);
digits.push( n );
}
var number = digits.join('')
Construct a new array where the items are random numbers and then join the array with an empty string.
const random = length => Array.from(Array(length), _ => Math.floor(Math.random() * 9) + 1).join('');
console.log(random(9));
console.log(random(9));
console.log(random(9));
console.log(random(9));
console.log(random(9));
In case you want to have all the 9 number to be unique you can use a object to keep track of added previously added numbers and if it is not included add a it to random number as well as object
let random = '';
let included = {}
for(let i =0;i<9;i++){
let temp = true
while(temp){
let num = Math.floor(Math.random() * 9) + 1 ;
if(included[num] === undefined){
temp = false
random += num
included[num] = num
}
}
}
$("#random-number").text(random);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="random-number"></div>

Compound Interest Calculator Not Producing Correct Values

I'm working on creating a compound interest formula with monthly contributions in javascript for populating a chartkick.js graph to show the total amount the principal grows to at the end of each year. Here is the formula I'm following.
Compound Interest For Principal
P(1 + r/n) ^ nt
Future Value of a Series
PMT * (((1 + r/n)^nt - 1) / (r/n)) * (1+r/n)
A = [Compound Interest for Principal] + [Future Value of a Series]
A = the future value of the investment/loan, including interest
P = the principal investment amount (the initial deposit or loan amount)
PMT = the monthly payment
r = the annual interest rate (decimal)
n = the number of times that interest is compounded per year AND additional payment frequency
t = the number of years the money is invested or borrowed for
*/
Here's my javascript:
P = $("#start-amount").val().replace(/[^\d\.]/g, '');
var t = $("#years").val();
var PMT = $("#contributions-amount").val().replace(/[^\d\.]/g, '');
var n = $("#contribution-rate").val();
//If you choose monthly it is equal to 12 and annually it is equal to 1
//Convert Interest Rate to Decimal
var r_percentage = $("#interest-rate").val().replace(/[^\d\.]/g, '');
var r = parseFloat(r_percentage) / 100.0;
//Create an arary with list of numbers less than number of years
var t_arr = [];
for (i = 0; i <= t; i++) {
if (i > 0 && i <= t) {
t_arr.push(i)
}
}
//For Chartkick Chart
data = [
{"name": "With interest", "data": {}
},
{"name": "No Interest", "data": {}
}];
/*
Needs to be like this!
data = [
{"name":"Workout", "data": {"2013-02-10 00:00:00 -0800": 3, "2013-02-17 00:00:00 -0800": 4}},
{"name":"Call parents", "data": {"2013-02-10 00:00:00 -0800": 5, "2013-02-17 00:00:00 -0800": 3}}
];*/
/*With Interest
J is equal to each individual year less than the total number of years*/
for (j = 1; j <= t_arr.length; j++) {
var compound_interest_for_principal = P * (Math.pow(1 + r / n, n * t));
var value_rounded1 = Math.round(compound_interest_for_principal * 100) /100;
var future_value_of_series = PMT * (Math.pow(1 + r / n, n * j) - 1) / (r / n) * (1 + r / n);
var value_rounded2 = Math.round(future_value_of_series * 100) / 100;
var A = value_rounded1 + value_rounded2;
var A = A.toFixed(2);
if (data[0]["data"][j] === undefined) {
data[0]["data"][j] = A;
}
}
/*Without Interest */
for (k = 1; k <= t_arr.length; k++) {
var r = 0;
var principal_no_interest= P;
var value_rounded1 = Math.round(principal_no_interest * 100) /100;
var monthly_no_interest = PMT * n * k;
var value_rounded2 = Math.round(monthly_no_interest * 100) / 100;
var A = value_rounded1 + value_rounded2;
var A = A.toFixed(2);
if (data[1]["data"][k] === undefined) {
data[1]["data"][k] = A;
}
}
new Chartkick.LineChart("savings-chart", data, {"discrete": true});
The values I'm testing are P = $1,000, r = 5% (annual interest), PMT = $100 per month, and n = 12 (number of times interested is compounded per year AND additional payment frequency).
Where the problem is coming in is the values I'm getting.
After 1 year with interest, I get $2,880 and I should get $2,277. After 10 years, I should get $17,065.21, but I'm getting $17,239.94. I don't understand why it's adding about $1,800 to the original vs about $1,200 like it should. Any suggestions?
You could check this
var result = PMT * (Math.pow(1 + r / n, nt) - 1) / (r / n) * (1 + r / n);
Thank you all for your help. I found a solution. Here's the incorrect code vs the correct code:
/*
Formula to Implement
P(1 + r/n) ^ nt
Future Value of a Series
PMT * (((1 + r/n)^nt - 1) / (r/n)) * (1+r/n)
A = [Compound Interest for Principal] + [Future Value of a Series]
A = the future value of the investment/loan, including interest
P = the principal investment amount (the initial deposit or loan amount)
PMT = the monthly payment
r = the annual interest rate (decimal)
n = the number of times that interest is compounded per year AND additional payment frequency
t = the number of years the money is invested or borrowed for
/*
/*INCORRECT SOLUTION
J is equal to each individual year less than the total number of years*/
for (j = 1; j <= t_arr.length; j++) {
//Correct
var compound_interest_for_principal = P * (Math.pow(1 + r / n, n * t));
//Correct
var a= Math.round(compound_interest_for_principal * 100) /100;
//Incorrect
var future_value_of_series = PMT * (Math.pow(1 + r / n, n * j) - 1) / (r / n) * (1 + r / n);
var b = Math.round(future_value_of_series * 100) / 100;
var A = a + b;
var A = A.toFixed(2);
if (data[0]["data"][j] === undefined) {
data[0]["data"][j] = A;
}
}
//CORRECT SOLUTION
for (j = 1; j <= t_arr.length; j++) {
//Incorrect
var compound_interest_for_principal = P * (Math.pow(1 + r / n, n * j));
var a = Math.round(compound_interest_for_principal * 100) / 100;
var future_value_of_series = ((PMT * n) / r) * (Math.pow(1 + r / n, n * j) - 1)
var b = Math.round(future_value_of_series * 100) / 100;
var A = a + b
var A = A.toFixed(2);
if (data[0]["data"][j] === undefined) {
data[0]["data"][j] = A;
}

Math.random and mixture of letters abcd etc

I'm generating a random number with the code below:
Math.floor((Math.random() * 9999) * 7);
Some of the results I'm getting:
45130,
2611,
34509,
36658
How would I get results like this(with 2 letters included):
TT45130,
PO2611,
KL34509,
GH36658
Side question:
What is the range of numbers that Math.random() carries? Can I set a specific range of values? Not necessary to answer but just curious.
You can use a function like below to get a random uppercase character:
function getRandomUppercaseChar() {
var r = Math.floor(Math.random() * 26);
return String.fromCharCode(65 + r);
}
So to generate a code as you specified with a two-letter prefix:
function generateCode() {
var prefix = new Array(2).fill().map(() => getRandomUppercaseChar()).join(""),
integer = Math.floor((Math.random() * 9999) * 7);
return prefix + integer;
}
NOTE: The above generateCode function uses modern ES6 and ES5 javascript, which is perfectly fine in a modern environment (such as Node.js or a current browser). However, if you wanted greater compatibility (for example, to ensure that it works in old browsers), you could rewrite it like so:
function generateCode() {
var integer = Math.floor((Math.random() * 9999) * 7);
for (var i = 0, prefix = ""; i < 2; ++i)
prefix += getRandomUppercaseChar();
return prefix + integer;
}
Try the simpler answer
var randomNumber = function () {
return Math.floor((Math.random() * 9999) * 7);
}
var randomChar = function () {
return String.fromCharCode(64 + Math.floor((Math.random() * 26)+1));
}
console.log(randomChar()+randomChar()+randomNumber());
//Sample outputs
HB10527 DR25496 IJ12394
Or you can use Number#toString for this purpose with radix = 36.
function getRChar() {
return (Math.random() * 26 + 10 | 0).toString(36).toUpperCase();
}
var s = getRChar() + getRChar() + Math.floor((Math.random() * 9999) * 7);
document.write(s);
If you need to generate a random string with JS, the most common way is to define an alphabet and pick random indices from that:
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numbers = "0123456789";
var randomString = "";
// Pick two random chars
for (var i = 0; i < 2; i++) {
var rand = Math.floor(Math.random()*alphabet.length);
randomString = randomString + alphabet.charAt(rand);
}
// Pick four random digits
for (var i = 0; i < 4; i++) {
var rand = Math.floor(Math.random()*numbers.length);
randomString = randomString + numbers.charAt(rand);
}
// randomString now contains the string you want
Sample strings:
OJ8225
YL5053
BD7911
ES0159
You could use String.fromCharCode() with a random integer between 65 and 90 to get an uppercase letter, i.e.
String.fromCharCode(Math.random() * 26 + 65) + String.fromCharCode(Math.random() * 26 + 65) + Math.floor((Math.random() * 9999) * 7);
gives med the results: "SH21248", "BY42401", "TD35918".
If you want to guarantee that the string always has the same length, you could also use
String.fromCharCode(Math.random() * 26 + 65) + String.fromCharCode(Math.random() * 26 + 65) + Math.floor(Math.random() * 59993 + 10000);
Math.random() always returns a number between 0 and 1, but never 0 or 1 exactly.
An array of the alphabet, a random number is generated to get a random letter, repeated to get a second random letter and then joined to the random number generated as in your code:
var alphabet=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
var ranletter1 = alphabet[Math.floor(Math.random() * alphabet.length)];
var ranletter2 = alphabet[Math.floor(Math.random() * alphabet.length)];
var ranNum = Math.floor((Math.random() * 9999) * 7);
var ranCode = ranletter1 + ranletter2+ ranNum;

How to print a recursive trace (factorial function)?

In the interest of better understanding recursion, I'm trying to figure out how to log a recursive trace to the console. I've got the 'trace down' part, but I'm not sure how to 'bubble up' the solution. Any suggestions for a perfectly placed console.log statement?
Here's what I've got so far:
function factorial (num) {
if (num === 1) {
console.log('factorial(' + num + ') = ' + num);
return 1;
} else {
console.log('factorial(' + num + ') = ' + num + ' * ' + 'factorial(' + (num - 1) + ')');
return num * factorial(num - 1);
}
}
which prints the following to the console:
factorial(5) = 5 * factorial(4)
factorial(4) = 4 * factorial(3)
factorial(3) = 3 * factorial(2)
factorial(2) = 2 * factorial(1)
factorial(1) = 1
120
But what about the 1 * 2 * 3 * 4 * 5 part? I know it's happening in there somewhere, how can I print it?
I guess I'd expect it to look something like this:
1
1 * 2
2 * 3
6 * 4
24 * 5
120
Thanks for any suggestions!
Ok after more searching I found this over at CodeRanch, unfortunately sans code (and written in Java):
Enter fact(6)
Enter fact(5)
Enter fact(4)
Enter fact(3)
Enter fact(2)
Enter fact(1)
Enter fact(0)
0!Ret: 1
Ret: 1 * fact(n-1) = 1 * fact(0) = 1 * 1 = 1
Ret: 2 * fact(n-1) = 2 * fact(1) = 2 * 1 = 2
Ret: 3 * fact(n-1) = 3 * fact(2) = 3 * 2 = 6
Ret: 4 * fact(n-1) = 4 * fact(3) = 4 * 6 = 24
Ret: 5 * fact(n-1) = 5 * fact(4) = 5 * 24 = 120
Ret: 6 * fact(n-1) = 6 * fact(5) = 6 * 120 = 720
fact(6) = 720
Pretty cool, right? After more experimenting, I still can't achieve this though...
function factorial (num) {
if (num === 1) {
console.log(num); //print new line after this
return 1;
} else {
var val = factorial(num - 1);
console.log(num +'*' + val); //print new line after this
return num * val;
}
}
I think it's best explained by using your example (edited a little) with comments. Assume you call this function with the parameter set to 5 the first time.
// num = 5, the first time it's called
function factorial (num) {
console.log('factorial(' + num + ')');
if (num === 1) {
// If num === 1, the function will just return 1 and exit.
return 1;
} else {
// Otherwise, which happens almost every time (since 1 is only
// reached once and then it stops). For 5, this would return
// 5 * factorial(4), which in order returns 4 * factorial(3),
// and so on.
return num * factorial(num - 1);
}
}
This output might help you understand:
factorial(5) == (5) * (factorial(4)) // (5) * (4 * 3 * 2 * 1)
factorial(4) == (4) * (factorial(3)) // (4) * (3 * 2 * 1)
factorial(3) == (3) * (factorial(2)) // (3) * (2 * 1)
factorial(2) == (2) * (factorial(1)) // (2) * (1)
factorial(1) == (1) // (1)
function factorial (num) {
for (var i=1; i<6-num; i++)
console.log(' ');
}
console.log('Enter fact('+num+')'); //add code to move new line
if(num==0) {
for (var i=1; i<6-num; i++)
console.log(' ');
}
console.log('0!Ret: 1 '); // add code to move new line
return 1;
} else {
int val = factorial(num-1);
for (var i=1; i<6-num; i++)
console.log(' ');
}
console.log('Ret:'+num+ ' * fact(n-1) = ' + num+ ' * fact('+(num-1)+') = '+num+' * ' + val + ' = ' + (num*val) ); // add code to move new line
return num*val;
}
}

Categories