Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 3 years ago.
Improve this question
I'm creating a function that generate a random Uniq Serial id by replacing a string with this format ; xxxx-xxxx-xxxx-xxxx , the goal is to get a serial like that : ABCD-1234-EFGH-5678 ,the first and third parts are a letters and the second and last parts are numbers, this is my code :
public generateUniqSerial() {
return 'xxxx-xxxx-xxx-xxxx'.replace(/[x]/g, function (c) {
let r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8)
return v.toString(16)
})
}
it give a result like that : "7f8f-0d9a-fd5-450f"
, how to edit this function to get a result with this format : ABCD-1234-EFGH-6789 ?
You can do something like this to generate a random Uniq Serial id with a format like ABCD-1234-EFGH-5678:
function rnd(t) {
let str = '';
const min = t === 'a' ? 10 : 0;
const max = t === 'n' ? 10 : 62;
for (let i = 0; i++ < 4;) {
let r = Math.random() * (max - min) + min << 0;
str += String.fromCharCode(r += r > 9 ? r < 36 ? 55 : 61 : 48);
}
return str;
}
function generateUniqSerial() {
return `${rnd('a')}-${rnd('n')}-${rnd('a')}-${rnd('n')}`
}
console.log(generateUniqSerial())
console.log(generateUniqSerial())
When I'm asked to do things like this I like to start with a "string of letters" and a "string of digits." My logic then simply consists of choosing a random index into the appropriate source string to get each character that I need. I like to do it this way because to me it's "extremely obvious" what I am doing and equally easy to desk-check that it will work.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
if I have the following values
0 - a
1 - b
2 - c
4 - d
8 - e
16 - f
if i get the value 17, how would i know that values b and f are in that values, some for the others as these can be mixed together by adding, so bd value would be 6
Convert your value to binary format. For example 17 => 10001. Then select only 1's. You can make for loop starts from 'a' to 'z'. Increase characters +1 then convert to character.
This is sample code:
function foo(num) {
if (num == 0)
return 'a';
const binaryNum = (num >>> 0).toString(2);
function nextChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1);
}
var converted = '';
var asci = 'b';
for(var i=binaryNum.length-1; i>=0; --i) {
if (binaryNum.charAt(i) == '1')
converted+=asci;
asci = nextChar(asci);
}
return converted;
}
console.log(foo(17));
console.log(foo(0));
console.log(foo(6));
console.log(foo(28));
Output is:
bf
a
bd
def
Note that 'bd' is 5.
Much like the bank note problem, reduce down the value in denominations, then pick out the index for the map to the letter.
const v1 = [0, 1, 2, 4, 8, 16];
const v2 = ['a', 'b', 'c', 'd', 'e', 'f'];
let value = 7
const vMap = new Map();
for (let i = v1.length - 1; i >= 0 && value; i--) {
const qty = Math.floor(value / v1[i]);
qty && vMap.set(v1[i], qty);
value = value % v1[i];
}
const entries = Array.from(vMap.entries());
console.log(entries.map(([curr, qty]) => `${curr} * ${qty} = ${curr * qty} is ${v2[v1.indexOf(curr)]}`))
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
After trying (and failing) to code a Caesar Cipher assignment for the Odin Project exercise, I finally caved in and looked up the answer. However, I do not quite understand it.
I am seeking an explanation of each line does and why it works. The code I copied has some brief descriptions of what each line does, but I still don't understand how it all works.
const caesar = function (str, amount) {
// Wrap the amount
if (amount < 0) {
return caesar(str, amount + 26);
}
// Make an output variable
var output = "";
// Go through each character
for (var i = 0; i < str.length; i++) {
// Get the character we'll be appending
var c = str[i];
// If it's a letter...
if (c.match(/[a-z]/i)) {
// Get its code
var code = str.charCodeAt(i);
// Uppercase letters
if (code >= 65 && code <= 90) {
c = String.fromCharCode(((code - 65 + amount) % 26) + 65);
}
// Lowercase letters
else if (code >= 97 && code <= 122) {
c = String.fromCharCode(((code - 97 + amount) % 26) + 97);
}
}
// Append
output += c;
}
// All done!
return output;
};
The first if-statement:
if (amount < 0) {
return caesar(str, amount + 26)
}
Makes sure that the shifting amount is 0 and above by calling itself until it is. Then the following line loops through all the characters in the entire string.
for (var i = 0; i < str.length; i++) {
For every character it checks if its a letter using something called a regex (Google for more information)
if (c.match(/[a-z]/i)) {
The line
var code = str.charCodeAt(i);
Gets the number representing the character at position "i" in the string. The number is the way the computer represents letters and other characters. Upper- and lowercase characters have two completely different numbers associated with them. That is what the two following if-statements is for. I will explain the one for lowercase letters, you should be able to see how the uppercase one works as well.
c = String.fromCharCode(((code - 65 + amount) % 26) + 65);
It starts by subtracting 65 from the number. This is because the first lowercase letter "a" has a value of 65. After that it shifts the result by "amount". The %-sign might seem weird. But all it does is divide the two sides and returning the "rest", the residual number. For example if we write:
5 % 2
It is equal to 1. This is done to "loop" the number and keep it between 0 and 26. After that it adds back the 65 and turns the number back to a character. The last line:
output += c;
Adds the character to the resulting string. Hope this helped you out!
This question already has answers here:
JavaScript: How to reverse a number?
(19 answers)
Closed 2 years ago.
So i am trying to reverse an integer and so far the code works but i am trying to find a solution to reverse the integer without converting into a string first? Any help would be appreciated. This is my code snippet so far to reverse the integer.
function reverseInt(num) {
const reversed = num.toString().split('').reverse().join('')
return parseInt(reversed) * Math.sign(num)
}
console.log(reverseInt(-500));
I am trying to do it using javascript.
Try this:
function reverseInt(number) {
var isNegative = number < 0 ? true : false;
if(isNegative)
number = number * -1;
var reverse = 0, lastDigit = 0;
while (number >= 1) {
reverse = Math.floor(reverse * 10 + (number % 10));
number = number / 10;
}
return isNegative == true ? reverse*-1 : reverse;
}
console.log(reverseInt(-500));
console.log(reverseInt(501));
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm writing a simple app to help my daughter practice basic Algebra (first grade). I would like to assign a score to each response depending on the difficulty of the operation, where 2+2 is worth less than 12-7, for example.
Do you know of any existing algorithm I can look up and adapt to my needs?
EDIT
if you want to see the app https://algebro.herokuapp.com
if you want to see the code https://gitlab.com/etozzato/algebro
**EDIT ← **
trying to make the question more specific ;)
given two integers and a basic algebraic operation
algorithm input: int a,b and string operation
algorithm output: float difficulty
→ What are the factors that can help inferring a difficult coefficient?
I would surely look at the input numbers, where their distance can be
significant in determining the complexity of the operation. 10 + 1 is clearly easier than 7 + 5 because (when not memorized and instantly responded) it takes longer counting time;
As an amendment to the previous statement, common/simple arguments should decrease the complexity of the operation: 0 or 10 are a good example;
I don't know of any algorithm to find the "difficulty" of an equation but if I had more time, I might try to play around with something like this... Even though it is for reading, the concept might be adaptable to arithmetic.
Anyway here is a super silly post-midnight crack at something that might work with some tweaking for extremely basic arithmetic. You can tweak the factors/weights but this might get you started. Good luck!
function get_difficulty (eq) {
var difficulty = 0;
var settings = {
terms_factor : 3, //Multiply by the number of terms in an equation
digits_factor : 2, //Multiply by the number of digits in each term
negative_weight : 2, //Add this if subtracting two numbers in the equation yields a negative number
operations : {
"+" : 1,
"-" : 2,
"*" : 4,
"/" : 6,
"=" : 0
}
};
eq += "=";
var ptr = 0;
var terms = 0;
var prev_term = null;
var len = eq.length;
var stack = [ ];
var is_numeric = function (n) {
return /\d+/.test (n); //Not a brilliant way but works for basic arithmetic
};
while (ptr < len) {
var tok = eq [ptr];
if (tok !== " " && tok !== "(" && tok !== ")") {
if (is_numeric (tok)) {
stack.push (tok);
} else if (tok in settings.operations) {
var curr_term = parseInt (stack.join (""));
if (prev_term !== null && curr_term > prev_term && ["-", "="].indexOf (tok) !== -1) {
difficulty += settings.negative_weight;
}
difficulty += stack.length * settings.digits_factor;
prev_term = curr_term;
stack = [ ];
terms++;
difficulty += settings.operations [tok];
} else {
console.log ("Unknown token: " + tok);
}
}
ptr++;
}
difficulty += terms * settings.terms_factor;
return difficulty;
}
console.log (get_difficulty (" 2 + 2 ")); //11
console.log (get_difficulty (" 12 - 7 ")); //14
console.log (get_difficulty (" 7 - 12 ")); //16
console.log (get_difficulty (" 5 - 5 ")); //12
console.log (get_difficulty (" 5 - 1205 ")); //20
console.log (get_difficulty (" 5 - 1205 * 35 ")); //29
console.log (get_difficulty (" 5 * 40 ")); //18
console.log (get_difficulty (" 102 - 5 / 13 + 32 ")); //39
console.log (get_difficulty (" 100 - 100 ")); //20
console.log (get_difficulty (" 32 - 12 ")); //16
console.log (get_difficulty (" 12 - 32 ")); //18
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have an object with a property containing a large string. This property has a value with random numbers generated earlier in the script in the format x , x , x , x ... (isn't and can't be an array because of other needs for the variable within the program) and so on. I am trying to get the sum of these numbers and my first thought was to use parseInt() to do this by splitting them all up then adding them together, but when I do this it only returns the first number. Is this what I should do but I'm just doing it wrong? Or is there another function that would make this easier?
The program is a blackjack game I'm making to see how well i understand everything I am learning.
Here is the function i am trying to make to see if the user busts when taking a hit (not much so far because i can't figure out the parseInt thing)
'
function checkBust() {
var total = parseInt(user.hand, 10);
}
'
the user object
'
var user = {
hand: dealUser()
};
'
and the functions to set the object property
function randomCard() {
// random number between 0 and 10
var j = Math.random() * 10;
// round that number into a var called card
var card = Math.round(j);
// if card is 0, assign a J Q or K by making a random number again
if (card === 0) {
//another random number
var k = Math.random() * 10;
// checks random number and assign J Q or K
if (k <= 4) {
card = 'J';
} else if (k <= 7) {
card = 'Q';
}
else {
card = 'K';
}
}
// value of the function is a single card
return card;
}
function dealUser() {
// empty array to store cards
var x = [];
// var to start for loop
var i = 0;
// start for loop
for (i; i < 2; i++) {
// add a random card to the i^th index of x
x[i] = randomCard();
}
// value for function is array of two cards x[0] , x[1]
var cards = x[0] + " , " + x[1];
return cards;
}
parseInt will stop parsing when it reaches a non numeric character.
parseInt('1234,5678', 10); // => 1234
// since a comma (,) is not a numeric character, everything after is ignored.
You have to split the string into an array of strings using the comma as the delimiter:
'1234,5678'.split(','); // => ['1234', '5678'];
Then parse each element of the array to convert them to numbers and then you can sum them.
Here's how I'd do it:
var nums = "1,2,3,4,5";
var sum = nums.split(',').reduce(function(memo, num) {
return memo + parseInt(num, 10);
}, 0);
console.log(sum); // => 15
That should work. See jsbin example.
Note the split parameter needs to match the delimiters you use in your string. for this example ',' is appropriate. For your example you might need /\s*,\s*/.
Unrelated
Since you provided an example of code I can see that you're spending a lot of effort attempting to duck punch and transform the values to the types you need instead of exposing the types in an object. Might I suggest:
function Stack(cards) {
this.cards = cards || [];
}
Stack.prototype.toString = function() {
return this.cards.join(' , ');
};
Stack.prototype.sum = function() {
return this.cards.reduce(function(memo, card) {
return memo + parseInt(card, 10);
}, 0);
};
function randomCard() {
return Math.floor(Math.random() * 13) + 1;
}
Stack.dealHand = function() {
var card1 = randomCard(), card2;
do { card2 = randomCard(); } while (card1 === card2);
return new Stack([card1, card2]);
};
// Example
var hand = Stack.dealHand();
console.log(hand + ' = ' + hand.sum()); // => '3 , 11 = 14'