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

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

Related

get the specific index of element in the array [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 1 year ago.
Improve this question
I have a list of different units:
const unitList = [1, 10, 36, 50, 20]; // all different numbers and all numbers are above 0
const unit = 13; // this is not included in unitList and not more that max number in unitList
And I want to get the index of unit in which unit should be placed before. for instance:
const unit = 13; returns index 4 because it should be placed before 20
const unit = 35; returns index 2 because it should be placed before 36
function getUnitPosition() {
if(!unitList.length) return 'before add new unit';
const max = Math.max(...unitList);
if(unit > max) return 'before add new unit';
const min = Math.min(...unitList);
if(unit < min) return columns[0].id;
for(let a = 0; a < unitList.length; a++) {
console.log(unit , unitList[a], unit < unitList[a])
if(unit < unitList[a]) return columns[a].id;
}
}
You could take the first found index with a smaller value than unit. For any other smaller value check the value to get the smallest one.
const
getIndex = (data, unit) => {
let index;
for (let i = 0; i < data.length; i++) {
if (
unit < data[i] &&
(index === undefined || data[i] < data[index])
) index = i;
}
return index;
},
unitList = [1, 10, 36, 50, 20];
// 13 ^^
// 35 ^^
console.log(getIndex(unitList, 13)); // 4 placed before 20
console.log(getIndex(unitList, 35)); // 2 placed before 36

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)

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));

sort array by specific pattern [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 3 years ago.
Improve this question
I want to get the array from:
const foo = [
FOO_BAR_A_READ_SELF,
FOO_BAR_A_WRITE_SELF,
FOO_BAR_A,
FOO_BAR_A_READ_ALL,
FOO_BAR_A_WRITE_ALL,
FOO_BAR_B_READ_SELF,
FOO_BAR_B_WRITE_SELF,
FOO_BAR_B,
FOO_BAR_B_READ_ALL,
FOO_BAR_B_WRITE_ALL
]
to
const foo = [
FOO_BAR_A,
FOO_BAR_A_READ_SELF,
FOO_BAR_A_WRITE_SELF,
FOO_BAR_A_READ_ALL,
FOO_BAR_A_WRITE_ALL,
FOO_BAR_B,
FOO_BAR_B_READ_SELF,
FOO_BAR_B_WRITE_SELF,
FOO_BAR_B_READ_ALL,
FOO_BAR_B_WRITE_ALL
]
i tried to go with the length by splitting with the "_", but I never worked with the sort function that specific.
I only used desc and asc ( return 1 > -1 ) || ( return -1 > 1 )
Can someone can explain me how I can get the wanted result?
Not sure it was my best...
var arr = [
'FOO_BAR_A_WRITE_SELF',
'FOO_BAR_A',
'FOO_BAR_A_READ_SELF',
'FOO_BAR_A_READ_ALL',
'FOO_BAR_A_WRITE_ALL',
'FOO_BAR_B_READ_SELF',
'FOO_BAR_B_WRITE_SELF',
'FOO_BAR_B',
'FOO_BAR_B_READ_ALL',
'FOO_BAR_B_WRITE_ALL'
];
const onRWorder=s=>{
let x = s.replace('_WRITE_','_')
if (x != s) x += '_WRITE'
else {
x = s.replace('_READ_','_')
if (x!= s) x += '_READ'
}
return x
}
arr.sort(function(a, b){
let a1 = onRWorder(a)
let b1 = onRWorder(b)
if(a1 < b1) { return -1 }
if(a1 > b1) { return 1 }
return 0
})
for (let z of arr) console.log(z)
.as-console-wrapper { max-height: 100% !important }
did you try this ?
var arr = [
'FOO_BAR_A_WRITE_SELF',
'FOO_BAR_A',
'FOO_BAR_A_READ_SELF',
'FOO_BAR_A_READ_ALL',
'FOO_BAR_A_WRITE_ALL',
'FOO_BAR_B_READ_SELF',
'FOO_BAR_B_WRITE_SELF',
'FOO_BAR_B',
'FOO_BAR_B_READ_ALL',
'FOO_BAR_B_WRITE_ALL'
];
var sorted = arr.sort();
console.log(sorted);

Convert array of numbers to string in Javascript [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
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!

Categories

Resources