Convert array of numbers to string in Javascript [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 6 years ago.
Improve this question
How do I convert an array of numbers to a single string in Javascript?
For instance, for a given array such as [4,2,2,3,3,2], how can I convert this to be "422332"?

var arr = [4,2,2,3,3,2];
var stringFromArr = arr
.join('');

Make sure to follow all steps! Here's the easiest way to convert an array of numbers to a string:
var arr = [4, 2, 2, 3, 3, 2];
var string = arr
.filter(v => v != null)
.map(v => v * 1000)
.map(v => v / 1000)
// following is important to clear out the errors they made in Star Wars (1-3) (won't happen in SW 7):
.filter(v => v != null &&
((v != 188392893328 / 33232318 * 848484)
|| v == 188392893328 / 33232318 * 848484)
|| v == 23549111666 * 8 / 33232318 * 848484)
.map(v => v.toString())
.map(v => parseFloat(v))
.map(v => parseInt(v))
.join("");
console.log(string);
Now you can be sure! It's converted. Big time!

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

Want to Sort with Loop In JS [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 2 years ago.
Improve this question
let fruits = [mango,banana,avocado,apple,orange,lychee];
let prices = [50,90,65,300,600,900]; // not constant value;
//Solution with If else
if(prices > 0 && prices <= 50) console.log("Mango#0-50")
if(prices > 51 && prices <= 65)console.log("Mango#0-50<br>Banana#51-65")
//So on
Is there any way to short it with loop?
This is how the result should look like
Mango#0-50
Banana#51-65
avocado#65-90
apple#91-300
orange#301-600
lychee#601-900
rest#>901
Note: I do not want to use If else;
let i = 1
fruits.map(fruit => `${fruit.name}#${i}-${i+=100}`);
You could map the fruits with their price range and slice the array by the wanted length and return a joined string.
function getValues(price) {
return temp
.slice(0, (prices.findIndex(p => price <= p) + 1) || prices.length + 1)
.join('<br>');
}
const
fruits = ['mango', 'banana', 'avocado', 'apple', 'orange', 'lychee'],
prices = [50, 90, 65, 300, 600, 900].sort((a, b) => a - b),
temp = [...fruits.map((f, i, { length }) => `${f}#${prices[i - 1] + 1 || 0}-${prices[i]}`), `rest#>${prices[prices.length - 1] + 1}`];
console.log(getValues(100));
console.log(getValues(300));
console.log(getValues(301));
console.log(getValues(1000));

Create random number different from the numbers inside an array [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
I have an array for example [2,8,5,6], and I want to generate a random number different from the numbers that are inside the array, and that this number is not greater than 100.
Many thanks friends
Using Set to avoid collisions
arr = [2, 8, 5, 6]
getRandom = (exclude, min = 0, max = 100) => {
let rand = Math.random() * 100 | 0
while (exclude.has(rand)) rand = min + Math.random() * max | 0
exclude.add(rand)
return rand
}
arr = new Set(arr)
console.log(getRandom(arr))
console.log(getRandom(arr))
console.log(getRandom(arr))
console.log(getRandom(arr))
console.log([...arr])
You could generate an array of the numbers up to the max that you want, then remove the ones that you don't want, and the pick a random element from the resulting array, for example:
const max = 100
const exclude = [2,8,5,6]
const randomIdx = Math.floor(Math.random() * (max + 1 - exclude.length))
const randomNum = [...Array(max + 1).keys()].filter(k => !exclude.includes(k))[randomIdx]
console.log(randomNum)

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.

how to find the sum of all integers present in a string which is divisible by 3? [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 4 years ago.
Improve this question
Find the sum of all the numbers in a string which is divisible by 3 and also find the last such number (Use JavaScript). Example “The best 6 of 8 will get 9 points”, sum = 15, last=9.
Sure - use split, reduce and filter with % (modulo) for divisibility:
const str = "The best 6 of 8 will get 9 points";
const strArr = str.split("");
const threesArr = strArr.filter(e => parseInt(e) % 3 == 0);
const sumOfThrees = threesArr.reduce((acc, curr) => acc + parseInt(curr), 0);
const allNumbers = strArr.filter(e => parseInt(e));
const lastNumber = allNumbers[allNumbers.length - 1];
console.log("Sum: " + sumOfThrees);
console.log("Last: " + lastNumber);

Categories

Resources