Find time to write a number in one figure [closed] - javascript

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 7 days ago.
Improve this question
write a function to calculate the number of milliseconds needed to type a number with one finger in javaScript
am try to solve this question but i don't have any idea how am solve this problem.

If I understand the comments well here's the answer
function calcTime (digits, num ){
const digits_arr = Array.from(digits);
let last_index = 0, new_index, time =0;
for (const n of num) {
new_index =digits_arr.findIndex(x => x===n);
time += Math.abs(new_index - last_index);
last_index = new_index;
}
return time;
}
example: Input: digits = "0123456789", num = "201" Output: 4

Here is the solution of Time Complexity: O(n) and Space Complexity: O(1):
def typing_time(digits, num):
typing_time = 0
start = 0
for digit in num:
index = digits.index(digit)
typing_time += abs(start - index)
start = index
return typing_time
# Test code
print(typing_time('0123456789', '210')) # 4
print(typing_time('8459761203', '5439')) # 17

Thanks to AbdelazizAlsabagh's answer I've finally understand the trick with the indexes!. I'm posting the full problem to solve (untested).
Number Generator
A digit-only keyboard contains all 10 digits from 0 to 9. They all exist in one line.
Give a string of 10 digits illustrating how the keys are positioned. To type a digit, you start from index zero to the index of the target digit. It takes |a - b| milliseconds to move from index a to index b.
Write a function to calculate the number of milliseconds needed to type a number with one finger.
Input: digits = '0123456789', num = '210
Output: 4
Input: digits = '8459761203', num = '5439'
Output: 17
Constraints:
digits.length == 10
digits contains each digit [0-9] exactly one in some order
1 <= num.length <= 10e4
num[i] is digit
def number_gen_idx(digits: str, nums: str) -> str:
"""
>>> number_gen_idx('0123456789', '210')
4
>>> number_gen_idx('8459761203', '5439')
17
"""
digits_idx = defaultdict(int)
for idx, digit in enumerate(digits):
digits_idx[digit] = idx
curr_ptr = 0
result = 0
for digit in nums:
result += abs((digits_idx[digit] - curr_ptr))
curr_ptr = digits_idx[digit]
return result

Related

Complete and Generate number for a array in JS [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
In javascript I'm looking to complete one numbers, you can help me generate a array of please.
The first 4 digits start by "23 29 xx xx xx", the xx remains to be completed with a range from 0 to 99. Ex. 23 29 01 02 03
let firstDigit = "2329";
let numberOfRandomDigit = "6";
let firstRange = "01";
let maxRange = "99";
let arrayOfNumbers = ["2329010203, 2329xxxxxx", ...];
I don't know to do this with a loop for complete array
as I see it's a 10 digit number, and you know 4 digits initial, so rest 6 digits you can generate randomly like this :
from random import randint
def random_num(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
rest_digit = random_num(6)
Now you can simply append these 6 digit to the 4 digits that you have.
In JavaScript:
let firstDigit = "2329";
let firstRange = "00";
let maxRange = "99";
var random_string = function(digits) {
var num = Math.floor(Math.random() * (maxRange-firstRange+1)+firstRange).toString();
while (num.length < digits)
{
num = "0" + num;
}
return num;
}
var arrayOfNumbers = [];
for (i=0;i<10;i++)
{
six_digit_string = random_string(2)+random_string(2)+random_string(2);
arrayOfNumbers.push(firstDigit+six_digit_string);
}
In Python:
import random
def random_two_digit_numbers():
return str(random.randint(0,99)).zfill(2)
generated_string = '23 29 {} {} {}'.format(random_two_digit_numbers,random_two_digit_numbers,random_two_digit_numbers)

Seeking an explanation of Caesar Cipher code [closed]

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!

how to find lexicographic string based on specified ranking

Consider all the strings of length 6 composed of capital Latin letters (A - Z), sorted in lexicographic order. The string AAAAAA is the first. The string AAAAAZ is the 26th . The 27th is AAAABA. The hint to this problem is the Nth string where N is the number of primes less than 2^ 30 − M . M is a permutation of 123456789, and we won’t tell you which one it is, but we will give you the following constraints to reduce the space of possibilities:
M is divisible by 567.
M starts with 2, ends with 4, and the middle digit is 8.
I managed to find M and the Nth, but I am not able to find a solution on how to find the right string based on the ranking. Please note that I found 9 possibilities on the ranking (Nth) which are:
43973488
43929860
41992802
41914646
41831591
41232030
41066565
40861259
40167328
Thank you for your help.
you need to convert the numbers to base 26 , and match each digit to the related chars
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
function convertToBase26Strings(number) {
number = number - 1 ;
var res = ""
while(number >= chars.length ) {
var i = number % chars.length ;
number = Math.floor(number / chars.length)
res += chars[i];
}
res += chars[number];
return res.split("").reverse().join("").padStart(6 , "A");
}
console.log(convertToBase26Strings(1));
console.log(convertToBase26Strings(26));
console.log(convertToBase26Strings(27));

Get random number based on probability [closed]

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 was wondering to get a random number with two decimal places based on probability for example:
40% to get number from 1-10
20% to get number from 11-20
30% to get number from 21-30
10% to get number from 31-35
function Prob(){
var rnd = Math.random(),
rnd2 = Math.random();
if(rnd<0.4) return (1 + Math.floor(1000 * rnd2)/100);
else if(rnd<0.6) return (11 + Math.floor(1000 * rnd2)/100);
else if(rnd<0.9) return (21 + Math.floor(1000 * rnd2)/100);
else return (31 + Math.floor(500 * rnd2)/100);
}
You need two random numbers, so I calculate them at the start. I then use the if-else loops to cycle through your 40%, 20%, 30% and 10% (adding them up as I go). Note: Math.random returns a number between 0 and 1. Then for each catagory I use the SECOND random number to get in the range you have said - floor it to make sure it is an integer and add the starting number of each range. Note: the range of your last one is just 5.
I should explain, you must use two random numbers, otherwise the range of the second number would be dependent on which category you are in.
I have to do the 1000 * rnd2 in the floor and then divide by 100 outside to get the 2 decimal place you ask for.
Rewind's solution is great and specifically tailored to OP's quesiton. A more re-usable solution might be:
function getNumber(probabilities){
var rnd = Math.random();
var total = 0;
var hit;
for(var i = 0; i < probabilities.length; i++){
if(rnd > total && rnd < total + probabilities[i][0]){
hit = probabilities[i]
}
total += probabilities[i][0];
}
return Number((hit[1] + (Math.random() * (hit[2] - hit[1]))).toFixed(2));
}
var number = getNumber(
[
//chance, min, max
[0.4, 1, 10],
[0.2,11,20],
[0.3,21,30],
[0.1,31,35]
]
);
console.log(number);
The function will take an array with the probabilities, for each probability you specify the chance, the minimum value for that chance, the maximum value for that chance. It will return a number with two decimals.
https://jsfiddle.net/x237w5gv/
I guess this
var get1120 = _ => ~~(Math.random()*10)+11,
get2130 = _ => ~~(Math.random()*10)+21,
get3135 = _ => ~~(Math.random()*5)+31,
a = [get3135,get1120,get1120,get2130,get2130,get2130],
fun;
result = (fun = a[~~(Math.random()*10)]) ? fun() : ~~(Math.random()*10)+1;
console.log(result);
might do it;

Can someone explain this base conversion code

var ShortURL = new function() {
var _alphabet = '23456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ-_',
_base = _alphabet.length;
this.encode = function(num) {
var str = '';
while (num > 0) {
str = _alphabet.charAt(num % _base) + str;
num = Math.floor(num / _base);
}
return str;
};
this.decode = function(str) {
var num = 0;
for (var i = 0; i < str.length; i++) {
num = num * _base + _alphabet.indexOf(str.charAt(i));
}
return num;
};
};
I understand encode works by converting from decimal to custom base (custom alphabet/numbers in this case)
I am not quite sure how decode works.
Why do we multiply base by a current number and then add the position number of the alphabet? I know that to convert 010 base 2 to decimal, we would do
(2 * 0^2) + (2 * 1^1) + (2 * 0 ^ 0) = 2
Not sure how it is represented in that decode algorithm
EDIT:
My own decode version
this.decode2 = function (str) {
var result = 0;
var position = str.length - 1;
var value;
for (var i = 0; i < str.length; i++) {
value = _alphabet.indexOf(str[i]);
result += value * Math.pow(_base, position--);
}
return result;
}
This is how I wrote my own decode version (Just like I want convert this on paper. I would like someone to explain more in detail how the first version of decode works. Still don't get why we multiply num * base and start num with 0.
OK, so what does 376 mean as a base-10 output of your encode() function? It means:
1 * 100 +
5 * 10 +
4 * 1
Why? Because in encode(), you divide by the base on every iteration. That means that, implicitly, the characters pushed onto the string on the earlier iterations gain in significance by a factor of the base each time through the loop.
The decode() function, therefore, multiplies by the base each time it sees a new character. That way, the first digit is multiplied by the base once for every digit position past the first that it represents, and so on for the rest of the digits.
Note that in the explanation above, the 1, 5, and 4 come from the positions of the characters 3, 7, and 6 in the "alphabet" list. That's how your encoding/decoding mechanism works. If you feed your decode() function a numeric string encoded by something trying to produce normal base-10 numbers, then of course you'll get a weird result; that's probably obvious.
edit To further elaborate on the decode() function: forget (for now) about the special base and encoding alphabet. The process is basically the same regardless of the base involved. So, let's look at a function that interprets a base-10 string of numeric digits as a number:
function decode10(str) {
var num = 0, zero = '0'.charCodeAt(0);
for (var i = 0; i < str.length; ++i) {
num = (num * 10) + (str[i] - zero);
}
return num;
}
The accumulator variable num is initialized to 0 first, because before examining any characters of the input numeric string the only value that makes sense to start with is 0.
The function then iterates through each character of the input string from left to right. On each iteration, the accumulator is multiplied by the base, and the digit value at the current string position is added.
If the input string is "214", then, the iteration will proceed as follows:
num is set to 0
First iteration: str[i] is 2, so (num * 10) + 2 is 2
Second iteration: str[i] is 1, so (num * 10) + 1 is 21
Third iteration: str[i] is 4, so (num * 10) + 4 is 214
The successive multiplications by 10 achieve what the call to Math.pow() does in your code. Note that 2 is multiplied by 10 twice, which effectively multiplies it by 100.
The decode() routine in your original code does the same thing, only instead of a simple character code computation to get the numeric value of a digit, it performs a lookup in the alphabet string.
Both the original and your own version of the decode function achieve the same thing, but the original version does it more efficiently.
In the following assignment:
num = num * _base + _alphabet.indexOf(str.charAt(i));
... there are two parts:
_alphabet.indexOf(str.charAt(i))
The indexOf returns the value of a digit in base _base. You have this part in your own algorithm, so that should be clear.
num * _base
This multiplies the so-far accumulated result. The rest of my answer is about that part:
In the first iteration this has no effect, as num is still 0 at that point. But at the end of the first iteration, num contains the value as if the str only had its left most character. It is the base-51 digit value of the left most digit.
From the next iteration onwards, the result is multiplied by the base, which makes room for the next value to be added to it. It functions like a digit shift.
Take this example input to decode:
bd35
The individual characters represent value 8, 10, 1 and 3. As there are 51 characters in the alphabet, we're in base 51. So bd35 this represents value:
8*51³ + 10*51² + 1*51 + 3
Here is a table with the value of num after each iteration:
8
8*51 + 10
8*51² + 10*51 + 1
8*51³ + 10*51² + 1*51 + 3
Just to make the visualisation cleaner, let's put the power of 51 in a column header, and remove that from the rows:
3 2 1 0
----------------------------
8
8 10
8 10 1
8 10 1 3
Note how the 8 shifts to the left at each iteration and gets multiplied with the base (51). The same happens with 10, as soon as it is shifted in from the right, and the same with the 1, and 3, although that is the last one and doesn't shift any more.
The multiplication num * _base represents thus a shift of base-digits to the left, making room for a new digit to shift in from the right (through simple addition).
At the last iteration all digits have shifted in their correct position, i.e. they have been multiplied by the base just enough times.
Putting your own algorithm in the same scheme, you'd have this table:
3 2 1 0
----------------------------
8
8 10
8 10 1
8 10 1 3
Here, there is no shifting: the digits are immediately put in the right position, i.e. they are multiplied with the correct power of 51 immediately.
You ask
I would like to understand how the decode function works from logical perspective. Why are we using num * base and starting with num = 0.
and write that
I am not quite sure how decode works. Why do we multiply base by a
current number and then add the position number of the alphabet? I
know that to convert 010 base 2 to decimal, we would do
(2 * 0^2) + (2 * 1^1) + (2 * 0 ^ 0) = 2
The decode function uses an approach to base conversion known as Horner's rule, used because it is computationally efficient:
start with a variable set to 0, num = 0
multiply the variable num by the base
take the value of the most significant digit (the leftmost digit) and add it to num,
repeat step 2 and 3 for as long as there are digits left to convert,
the variable num now contains the converted value (in base 10)
Using an example of a hexadecimal number A5D:
start with a variable set to 0, num = 0
multiply by the base (16), num is now still 0
take the value of the most significant digit (the A has a digit value of 10) and add it to num, num is now 10
repeat step 2, multiply the variable num by the base (16), num is now 160
repeat step 3, add the hexadecimal digit 5 to num, num is now 165
repeat step 2, multiply the variable num by the base (16), num is now 2640
repeat step 3, add the hexadecimal digit D to num (add 13)
there are no digits left to convert, the variable num now contains the converted value (in base 10), which is 2653
Compare the expression of the standard approach:
(10 × 162) + (5 × 161) + (13 × 160) = 2653
to the use of Horner's rule:
(((10 × 16) + 5) × 16) + 13 = 2653
which is exactly the same computation, but rearranged in a form making it easier to compute. This is how the decode function works.
Why are we using num * base and starting with num = 0.
The conversion algorithm needs a start value, therefore num is set to 0. For each repetition (each loop iteration), num is multiplied by base. This only has any effect on the second iteration, but is written like this to make it easier to write the conversion as a for loop.

Categories

Resources