I want to randomize letters and numbers, something like
let r = Math.random().toString(36).substring(7);
console.log("random", r);
but insert it in a text input HTML field. I have already managed to plug in texts from a list, but I want it completely random and to follow with an #something.com.
For example, I want the input field, on every refresh to have something like the following:
8ut5fgh8#gmail.com
0okmnhy4#gmail.com
s5g7j9l0#gmail.com
The characters before the #gmail.com should be 8 chars long.
Thanks for your help. This is a snippet of what I have already done"
var texts = [
"#gmail.com",
"#yahoo.com",
"#xdxd.com"
];
document.getElementById('email0').value = texts[Math.floor(Math.random()*texts.length)];
E-mail: </br><input type="text" id="email0" name="email"><br>
If you figured out how to make a domain part - do the rest by analogy.
var texts = [
"#gmail.com",
"#yahoo.com",
"#xdxd.com"
];
var chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
function randomEmail(length) {
let result = ''
for (let i = 0; i <= length; i++) {
result += chars[Math.floor(Math.random() * chars.length)]
}
return result + texts[Math.floor(Math.random() * texts.length)]
}
document.getElementById('email0').value = randomEmail(8)
E-mail: <br><input type="text" id="email0" name="email"><br>
you can try this
var texts = [
"#gmail.com",
"#yahoo.com",
"#xdxd.com"
];
function random() {
var text = "";
var ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 8; i++)
text += ch.charAt(Math.floor(Math.random() * ch.length));
return text;
}
let str = random()+texts[Math.floor(Math.random()*texts.length)];
document.getElementById('email0').value = str
<input id="email0">
this is another way to do it using arrays and join and assuming you only want small letters in your random emails.
let texts = [
"#gmail.com",
"#yahoo.com",
"#xdxd.com"
];
let alphnum = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
let randomChoice = [texts[Math.floor(Math.random() * texts.length)]]
for (let index = 0; index < 8; index++) {
const element = alphnum[Math.floor(Math.random() * alphnum.length)];
randomChoice.unshift(element)
}
let randomChoiceString = randomChoice.join("")
document.getElementById('email0').value = randomChoiceString
Related
we have a digit letter map that looks like this
const digitsLetters = new Map([
["2", ['a', 'b', 'c']],
["3", ['d', 'e', 'f']],
["4", ['g', 'h', 'i']],
["5", ['j', 'k', 'l']],
["6", ['m', 'n', 'o']],
["7", ['p', 'q', 'r', 's']],
["8", ['t', 'u', 'v']],
["9", ['w', 'x', 'y', 'z']],
]);
The question asks us to return the all possible letter combinations that the number could represent. For example, if we have "23" then first digit 2 maps to ['a', 'b', 'c'] and second digit maps to ['d', 'e', 'f'] and we end up getting ["ad","ae","af","bd","be","bf","cd","ce","cf"].
I have found a way to produce such a combination between two arrays.
// this will output ["ad","ae","af","bd","be","bf","cd","ce","cf"]
['a', 'b', 'c'].map(char1 => ['d', 'e', 'f'].map(char2 => char1 + char2)).flat(2)
So I thought I could just recursively apply this algorithm for such digit until I hit the last one. I think it is doable. However I had a hard time implementing the solution. Can someone please help me?
Let's consider the cartesian product f(E, F) with an example
assume E is like ['12', '13']
then you get candidates a and b, which I name as F = ['a', 'b']
f(E, F) = E x F would give ['12a', '13a', '12b', '13b']
(note that ExF is the same type of E, an array of string)
now you can recurse on the digits given
g([digit, ...otherDigits], E) => {
candidates = m.get(digit)
EF = cartesianProduct(E, candidates)
return g(otherDigits, EF)
}
Note that the initialization on E should not be the empty array, but an array of length 1 whose sole element is the "neutral" element (empty string for strings)
const data = new Map([
["2", ['a', 'b', 'c']],
["3", ['d', 'e', 'f']],
["4", ['g', 'h', 'i']],
["5", ['j', 'k', 'l']],
["6", ['m', 'n', 'o']],
["7", ['p', 'q', 'r', 's']],
["8", ['t', 'u', 'v']],
["9", ['w', 'x', 'y', 'z']],
]);
const f = (E, F) => E.flatMap(e => F.map(f => e + f))
const g = ([digit, ...otherDigits], E=['']) => digit ? g(otherDigits, f(E, data.get(digit))) : E
console.log(g('23'.split('')))
console.log(g('234'.split('')))
You can basically just use map method to get array from you Map data based on string param and them implement Cartesian product algo.
const data = new Map([
["2", ['a', 'b', 'c']],
["3", ['d', 'e', 'f']],
["4", ['g', 'h', 'i']],
["5", ['j', 'k', 'l']],
["6", ['m', 'n', 'o']],
["7", ['p', 'q', 'r', 's']],
["8", ['t', 'u', 'v']],
["9", ['w', 'x', 'y', 'z']],
]);
function f(str, map) {
const result = [];
const arr = str.split('').map(c => map.get(c))
function r(data, n = 0, prev = []) {
if (n === data.length) {
return result.push(prev.slice())
}
for (let i = 0; i < data[n].length; i++) {
prev[n] = data[n][i]
r(data, n + 1, prev.slice())
}
}
r(arr)
return result;
}
console.log(f('23', data))
console.log(f('358', data))
Something like this
const digitsLetters = new Map([
["2", ['a', 'b', 'c']],
["3", ['d', 'e', 'f']],
["4", ['g', 'h', 'i']],
["5", ['j', 'k', 'l']],
["6", ['m', 'n', 'o']],
["7", ['p', 'q', 'r', 's']],
["8", ['t', 'u', 'v']],
["9", ['w', 'x', 'y', 'z']],
]);
const foo = (arr, result = []) => {
if (arr.length === 0) return result;
const value = arr.shift();
if (result.length === 0) return foo(arr, value);
const newResult = [];
result.forEach((el) => {
value.forEach((el2) => {
newResult.push(el + el2);
});
});
return foo(arr, newResult);
};
const boo = (str) => foo(str.split('').map((symbol) => (digitsLetters.get(symbol))));
console.log(boo(''));
console.log(boo('2'));
console.log(boo('23'));
console.log(boo('232'));
How can i delete all duplicates in array without using Set (because it will disturb the order)
And why my loop with splice method doesnt work?
let result = [
'j', 'a', 'a', 'v',
'a', 'a', 's', 'c',
'r', 'i', 'p', 't'
]
;
for (let i = 0; i < result.length; i++) {
if (result[i] === result[i + 1]){
result.splice(result.indexOf(result[i]), 1);
}
}
console.log(result) //[ "j", "v", "a", "a", "s", "c", "r", "i", "p", "t" ]
expected output - > [ "j", "a", "v", "a", "s", "c", "r", "i", "p", "t" ]
You could filter the array and have a look to the predecessor.
const
data = ['j', 'a', 'a', 'v', 'a', 'a', 's', 'c', 'r', 'i', 'p', 't'],
result = data.filter((v, i, a) => v !== a[i - 1]);
console.log(...result);
Your method fails in your condition:
if (result[i] === result[i + 1])
Because you only check to see if the next item is the same as the current item and not against the entire array.
To solve this you can create a new array and push in this array only the values that are not already there, thus eliminating duplicates.
const result2 = [];
for (let i = 0; i < result.length; i += 1) {
if (result2.indexOf(result[i])>-1) {
continue;
}
result2.push(result[i]);
}
I think to remove duplicate from an array write a function that do the job and return the array with unique item in it. Please find the below code that serve the propose.
function removeDuplicate(data) {
const tempArray = [];
data.forEach( (item) => {
if (tempArray.indexOf(item) === -1) {
tempArray.push(item);
}
});
return tempArray;
}
let result = [
'j', 'a', 'a', 'v',
'a', 'a', 's', 'c',
'r', 'i', 'p', 't'
];
result = removeDuplicate(result );
I have 3 arrays (or more/less, it's not mandatory to be 3, I just gave an example) and I want to remove all the common elements between them. For example, between the first 2, the common elements are x and z, between the second and the third array the common element would be t. Between the first and the thirs the common element is k. Basically I want to remove any elements that appear more than 1 times in multiple arrays.
!! the first array can have common elements with the third one !!
Here is what I tried so far, but it's not working correctly.
let y = [{
id: 'a',
elems: ['x', 'y', 'z', 'k']
},
{
id: 'b',
elems: ['x', 't', 'u', 'i', 'z']
},
{
id: 'c',
elems: ['m', 'n', 'k', 'o', 't']
},
]
// x, z, t
for (let i = 0; i < y.length - 1; i++) {
let current = y[i].elems
let current2 = y[i + 1].elems
if (current[i] == current2[i]) {
const index = current.indexOf(current[i]);
if (index > -1) {
current.splice(index, 1);
current2.splice(index, 1);
}
}
}
console.log(y)
The desired result would be
[
{
"id": "a",
"elems": [
"y"
]
},
{
"id": "b",
"elems": [
"u",
"i"
]
},
{
"id": "c",
"elems": [
"m",
"n",
"o"
]
}
]
Which would be a correct and optimal solution for this? I also tried to concatenate the 3 arrays and remove the duplicates, but then I don't know how to recreate the 3 arrays back.. Thanks!
I would first loop over all the elems and count up how many times that have been seen. After that I would loop again and filter out anything that was seen more than once.
const myData = [{
id: 'a',
elems: ['x', 'y', 'z']
},
{
id: 'b',
elems: ['x', 't', 'u', 'i', 'z']
},
{
id: 'c',
elems: ['m', 'n', 'o', 't']
},
]
// count up every elem so we know which ones are duplicated
const allElems = myData.reduce((acc, item) => {
item.elems.forEach( key => {
acc[key] = acc[key] || 0;
acc[key]++;
});
return acc;
}, {})
// loop over all the elems and select only the elems that we have seen once
myData.forEach(item => {
item.elems = item.elems.filter(key => allElems[key] === 1);
})
console.log(myData)
let x = ['a', 'b']
let y = [{
id: 'a',
elems: ['x', 'y', 'z', 'k']
},
{
id: 'b',
elems: ['x', 't', 'u', 'i', 'z']
},
{
id: 'c',
elems: ['m', 'n', 'k', 'o', 't']
},
]
// x, z, t
for (let i = 0; i < y.length - 1; i++) {
for (let j = 1; j < y.length; j++) {
let current = y[i].elems
let current2 = y[j].elems
current2.forEach((item,index)=>{
if(current.includes(item)){
current.splice(current.indexOf(item),1)
current2.splice(index,1)
}
})
}
}
console.log(y)
.as-console-wrapper { max-height: 100% !important; top: 0; }
const y = [
{ id: 'a', elems: ['x', 'y', 'z'] },
{ id: 'b', elems: ['x', 't', 'u', 'i', 'z'] },
{ id: 'c', elems: ['m', 'n', 'o', 't'] },
];
// get number of occurences for each elem
const elems
= y.flatMap(e => e.elems).reduce((acc,elem) => {
acc[elem] = acc[elem] ? acc[elem]+1 : 1;
return acc;
}, {});
// get unique elems
const unique = Object.keys(elems).filter(elem => elems[elem]===1);
// remove non-unique elems from each item
const res = y.map(item =>
({ ...item, elems: item.elems.filter(e => unique.includes(e)) })
);
console.log(res);
Using a Map to track counts after one loop through then use the count of that Map in a filter for final results
let x = ['a', 'b']
let y = [{
id: 'a',
elems: ['x', 'y', 'z']
},
{
id: 'b',
elems: ['x', 't', 'u', 'i', 'z']
},
{
id: 'c',
elems: ['m', 'n', 'o', 't']
},
]
const counts = new Map()
// first iteration to count values
y.forEach(({ elems }) => elems.forEach(v => counts.set(v, (counts.get(v) || 0) + 1)));
// second iteration to filter out dups
y.forEach(e => e.elems = e.elems.filter(v => counts.get(v) === 1))
console.log(y)
Let me know if this works for you.
let y = [
{
id: "a",
elems: ["x", "y", "z", "k"],
},
{
id: "b",
elems: ["x", "t", "u", "i", "z"],
},
{
id: "c",
elems: ["m", "n", "x", "z", "t"],
},
];
// For every element in first array
for (let el of y[0].elems) {
//If we find that every other array includes it
if (y.every((obj) => obj.elems.includes(el))) {
//Remove it from all arrays
for (let obj of y) {
obj.elems = obj.elems.filter((x) => x !== el);
}
}
}
let y = [{
id: 'a',
elems: ['x', 'y', 'z']
},
{
id: 'b',
elems: ['x', 't', 'u', 'i', 'z']
},
{
id: 'c',
elems: ['m', 'n', 'o', 't']
},
];
//
const notExist = (x, arr) => !arr.find(el => el == x);
const restToArrays = (i, arr) => arr.reduce((a, b, index) => index == i ? a : [...a, ...b.elems], []);
const result = y.map((ligne, index, arr) => ({
id: ligne.id,
elems: ligne.elems.filter(v => notExist(v, restToArrays(index, arr)))
}))
console.log(result);
If I have the code below to generate random characters, how can I code it to generate those same characters excluding some values? I.e. corresponding to var charactExclude.
Ex:
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
var charactExclude = document.getelementbyID(character).content.text
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result
}
console.log(makeid(10))
Here's how I would go about this:
First select your element containing the excluded characters (You have some errors in your JS) You can split this into an array using .split('') and use the [...new Set(Your array here)] pattern to remove duplicates at this point.
Then create a new variable for the filtered string, and loop through replacing the characters you do not want to include.
Finally, use this new variable in the creation of your string.
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactExclude = [
// Using a Set efficiently removes duplicates, and will speed up the loop below, and the ... expands them back into an array
...new Set(
// Using split('') will turn the string into an array of characters
document.getElementById("character").innerText.split('')
)
];
// Create a new variable, and then loop through the charactExclude array, removing undesired chars
var charactersFiltered = characters
for (var i = 0; i < charactExclude.length; i++) {
charactersFiltered = charactersFiltered.replace(charactExclude[i], '')
}
for (var i = 0; i < length; i++) {
result += charactersFiltered.charAt(Math.floor(Math.random() * charactersFiltered.length));
}
return result
}
console.log(makeid(100))
<div id="character">ABCDEFG</div>
I admit this might be a little tortuous as solution...
/*
* Char codes ranges:
* 0-9 -> 48-57
* A-Z -> 65-90
* a-z -> 97-122
*/
function makeId(idLength, charsToExclude = []) {
// list of all invalid char codes between '0' (char code 48) and 'z' (char code 122)
const invalidCharCodes = [58, 59, 60, 61, 62, 63, 64, 91, 92, 93, 94, 95, 96];
// add to the invalid char list any char passed as parameter
if (charsToExclude.length > 0) {
charsToExclude.forEach(char => invalidCharCodes.push(char.charCodeAt(0)))
}
let id = '';
while (id.length < idLength) {
let charCode;
do {
charCode = Math.floor(Math.random() * (122 - 48 + 1)) + 48;
} while (invalidCharCodes.indexOf(charCode) >= 0)
id += String.fromCharCode(charCode);
}
return id;
}
// test
console.log('should return an ID containing digits and letters (either lower or upper case):', makeId(10));
console.log('should return an ID containing only digits:', makeId(10, ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']));
console.log('should return an ID containing only letters (either lower or upper case):', makeId(10, ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']));
console.log('should return an ID containing only lower case letters:', makeId(10, ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']));
console.log('should return an ID containing only upper case letters:', makeId(10, ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']));
console.log('should return an ID containing only 0s:', makeId(10, ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']));
You could use Array.filter for that
const alphabetAndNumbers = () => [...Array(26)]
.map((x, i) => String.fromCharCode(i + 65))
.concat([...Array(26)].map((x, i) => String.fromCharCode(i + 97)))
.concat([...Array(10)].map((x, i) => `${i}`));
console.log(`Your id: ${createRandomId(10)}`);
function createRandomId(len) {
let characters = alphabetAndNumbers();
console.log(`[characters] initial ${characters.join("")}`);
//retrieve characters to exclude from the template element and split it to an array
const excludes = document.querySelector("#excludes").content.textContent.split("");
// filter initial characters array to exclude the characters in [excludes]
// now [characters] is an array too
characters = characters.filter(c => !~excludes.indexOf(c));
console.log(`excluded ${excludes.join("")}`)
console.log(`[characters] now ${characters.join("")}`);
// create an array with length [len], map characters (pseudo random) into it
// and return the joined array
return [...Array(len)]
.map(v => characters[Math.floor(Math.random() * characters.length)])
// ^ characters is array, so you can pick an element from it
.join("");
}
// easier may be to initially use a subset
const createRandomIdSimple = (len, chars) => [...Array(len)]
.map(v => chars[Math.floor(Math.random() * chars.length)])
.join("");
const chars4Id = document.querySelector("#chars4RandomId").content.textContent.split("");;
console.log(`Your id from createRandomSimple: ${createRandomIdSimple(10, chars4Id)}`);
<template id="excludes">DWX23Aal0gn</template>
<template id="chars4RandomId">BCEFGHIJKLMNOPQRSTUVYZbcdefhijkmopqrstuvwxyz1456789</template>
Bonus: rewritten to a factory function for creating random Id's
const randomId = RandomIdFactory();
const log = Logger();
log(`Lets create 25 pseudo random id's of length 32`,
`without "l" (lowercase L) and "0" (zero):\n`,
[...Array(25)].map(x => randomId(32, "l0")).join("\n"));
function RandomIdFactory() {
const characters = [...Array(26)]
.map((x, i) => String.fromCharCode(i + 65))
.concat([...Array(26)].map((x, i) => String.fromCharCode(i + 97)))
.concat([...Array(10)].map((x, i) => `${i}`));
return (len, excludes) => {
const chars = excludes &&
characters.filter(c => !~excludes.indexOf(c)) ||
characters;
return [...Array(len)]
.map(v => chars[Math.floor(Math.random() * chars.length)])
.join("");
};
}
function Logger() {
const logEl = document.querySelector("#log") || (() => {
document.body.append(Object.assign(document.createElement('pre'), {id:"log"}));
return document.querySelector("#log");
})();
return (...strs) => strs.forEach(s => logEl.textContent += `${s}\n`);
}
I am trying to find a word from consecutive strings inside an array and I am stuck at the moment.
For example: array = ['w', 'r', 'a', 'p', 'p', 'l', 'e', 'f', 'k', 'l']; I want to make a function that will return true if the word 'apple' is inside this array. Strings need to be consecutive.
array1 = ['w', 'r', 'a', 'p', 'l', 'p', 'e', 'f', 'k', 'l']; function for this kind of strings with no consecutive 'apple' strings should return false.
Can you help please?
array = ["w", "r", "a", "p", "p", "l", "e", "f", "k", "l"];
console.log(array.toString().replace(/,/g,"").indexOf("apple")>-1);
One approach would be traverse your array, and get substrings of length that equals the length of the matching substring, and compare the substring with the matching substring
for (int i=0; i<array.length-matching.length; i++) {
if (array.substr(i, i+matching.length) == matching) return true;
} return false;
Try this:
var array = ['w', 'r', 'a', 'p', 'p', 'l', 'e', 'f', 'k', 'l'];
function findWord(arr, word) {
return arr.join('').indexOf(word) !== -1;
}
// test
console.log('apple: ', findWord(array, 'apple'))
console.log('dog: ', findWord(array, 'dog'))
check this function:
function hasWord(inputSourceList, inputWord) {
return inputSourceList.join('').indexOf(inputWord) > -1;
};
With Array.join(), String.replace() and String.indexOf() functions:
var contains_word = function(arr, w) {
return arr.join('').replace(new RegExp('[^' + w + ']', 'g'), '')
.indexOf(w) !== -1;
}
console.log(contains_word(['w', 'r', 'a', 'p', 'l', 'p', 'e', 'f', 'k', 'l'], 'apple'));
console.log(contains_word(['w', 'r', 'a', 'p', 'p', 'l', 'e', 'f', 'k', 'l'], 'apple'));
You can use a combination of Array.every(), and Array.indexOf() to check if all letters are found in the correct order:
const findWordInArray = (word, array) => {
let last = -1; // stores the last index found
// iterate the letters of the word
return [...word].every((c) => {
// search for the letter from the last known position + 1 onwards
const index = array.indexOf(c, last + 1);
last = index; // change last to the new found position
return index !== -1;
});
}
const array1 = ['w', 'r', 'a', 'p', 'p', 'l', 'e', 'f', 'k', 'l'];
const array2 = ['w', 'r', 'a', 'p', 'l', 'p', 'e', 'f', 'k', 'l'];
const word = 'apple';
console.log(findWordInArray(word, array1));
console.log(findWordInArray(word, array2));