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

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)

Related

how to check if value exists from value? [closed]

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)]}`))

Find time to write a number in one figure [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 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

calculating running speed [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed last year.
My problem is a wrong result.
I have a function this function has a distance and a time.
The result I want to achieve is calculating running speed.
function runningPace(distance, time) {
let result = time.replace(":", ".")
let fl = parseFloat(result)
let calc = fl / distance
let num = calc.toFixed(2) + ''
if(num.length === 1) {
num = num + '.00'
}
let rep = num.replace('.', ':')
console.log(distance, time, result, fl, calc, rep, num)
return rep;
}
console.log(runningPace(5, '25:00')) // '5:00'
console.log(runningPace(4.99, '22:32')) // '4:30'
I wrote such a function. Sorry for the naming, I'll fix it when I get it fixed.
When I test this code, the output is:
expected '4:47' to equal '4:30'
'4:30' => four minute thirty second
How can I find a solution? Thanks everyone in advance.
convert anything in seconds:
function runningPace(dist, time)
{
let
[ mn, sc ] = time.split(':').map(Number)
, fl = Math.floor(((mn *60) + sc) / dist)
;
sc = fl % 60
mn = (fl - sc) / 60
return `${mn}:${(sc<9)?'0'+sc:sc}`
}
console.log(runningPace( 5, '25:00')) // 5:00
console.log(runningPace( 4.99, '22:32')) // 4:30

Angular / JS generate random Uniq Serial ID [closed]

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.

Convert integers to string and then adding using recursion [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Hi I am trying to solve a problem where the input for a function digital_root(n) will add the digits. I am not sure what I am doing wrong.
function digital_root(n) {
// ...
//1. separate n into array of digits
var nString = n.toString();
//[ '1', '2', '3', '4' ]
var numbersToAdd = [];
var total = 0;
for (var i = 0; i < nString.length; i++) {
numbersToAdd.push(+nString.charAt(i));
}
// result is [ 1, 2, 3, 4 ]
//2. add digits
for (var x = 0; x < numbersToAdd.length; x++) {
total += numbersToAdd[i];
//expected outputs
// total = 0 + numbersToAdd[0]--> 0+1--> total = 1
// total = 1 + numbersToAdd[1]-->1+2--> total = 3
// total = 3 + numbersToAdd[2]-->3+3--> total = 6
// total = 6 + numbersToAdd[3]-->6+3--> total = 9
}
return total;
}
console.log(digital_root(1234));
You need to use "x" instead of "i"
So changing
total += numbersToAdd[i];
to
total += numbersToAdd[x];
will fix an issue.
Also output should be 10 instead of 9, there is calculation mistake in your question

Categories

Resources