converting a string to numbers Javascript - javascript

I've starting messing up with javascript lately and stumbled upon some problem.
I'm allowing my user to insert a series of numbers separated by white-spaces into a text field. I am trying to read the string from the text field and store the numbers in an array. However, I have those 0's added unwillingly. I went thru my code over and over, yet I cannot find whats wrong.
the code:
function get_input(str)
{
var arr = [];
var elem=0;
for(var i=0,j=1; i<str.length ;i++,j++)
{
if (j == str.length) {elem += str[i];
arr.push(elem);
return arr;}
else if (str[j]== " ")
{
elem *=10;
elem +=str[i];
arr.push(elem);
elem=0;
i++;
j++
}
else
{
elem *=10;
elem += str[i];
}
}
return arr;
}
e.g for an input:123 45 6
the output is : 10203*405*06*
I put the * only to see the elements in the array,
Help will be much appreciated.

function get_input(str){
var a = str.split(' ');
for(var i = 0; i < a.length; i++){
a[i] = parseFloat(a[i]);
}
return a;
}
Break-down:
Using the split method, we're populating an array with the strings separated by the ' ' (space) delimiter.
We then cycle through the array in order to parse the results into Numbers. If this isn't needed (i.e you're happy with the digits being represented as Strings) then you don't need that extra step.
We then return the array.

Related

Finding a first letter most repeated in an string

Good evening, I proceed to explain my situation. I started to get interested in javascript which started to dabble
in this language, I have been doing some online courses which I have encountered the following task, basically I am trying through the condition "for" tell me what is the first repeated letter of a string also adding the funsion ".UpperCase () "which at the beginning worked best, until I entered more characters to the string in this case" x "throwing me as output result" undefined "instead of" the most repeated word is: X "reach the case that the string should Consider all the letters regardless of whether they are lowercase or capital letters, for which I ask for help to understand if ¿there is another way? for this task and thus move forward (Sorry for my bad english)
Well i making this task in JavasScript with Atom Editor
var word = "SQSQSQSSaaaassssxxxY";
var contendor = [];
var calc = [];
var mycalc = 0;
function repeat() {
for (var i = 0; i < word.length; i++) {
if (contendor.includes(word[i])) {} else {
contendor.push(word[i])
calc.push(0)
}
}
for (var p = 0; p < word.length; p++) {
for (var l = 0; l < contendor.length; l++) {
if (word[p].toUpperCase() == word[l]) {
calc[l] = calc[l] + 1
}
}
}
for (var f = 0; f < calc.length; f++) {
if (calc[f] > mycalc) {
mycalc = calc[f]
}
}
}
repeat()
console.log("The first letter repeated its: " + contendor[mycalc])
I expected the output of the String to be: "X"
but the actual output is: "Undefined"
The first error in your script is that you store the wrong value in mycalc:
mycalc = calc[f]
Since you want mycalc to be an index, the above should have been
mycalc = f
Now, you will get a result, but your code is actually going through a lot of effort to find the uppercase character that is repeated most often, not first.
Your comparison should have used toUpperCase on both sides of the comparison, otherwise lower case letters will never match.
To get the character that was repeated most often, you could use a Map (to keep track of the counts like you did in calc):
function mostRepeated(str) {
const map = new Map;
let result;
let maxCount = 0;
for (let ch of str) {
ch = ch.toUpperCase();
let count = (map.get(ch) || 0) + 1;
map.set(ch, count);
if (count > maxCount) {
maxCount = count;
result = ch;
}
}
return result;
}
var word = "MBXAYMZAXmZYxxxxxxxxxxmBxAYMZaXmZY";
console.log(mostRepeated(word));
Note that you should better use function parameters and local variables. Declaring your variables as global is not considered best practice.
You could find the letter that occurs the most number of times in a string by:
first creating a map that relates each unique letter, to the number of times it occurs in the string
converting that map to an array of "key/value" entries, and then sorting those entries by the "count value"
returning the "letter key" that has the largest count
One way to express this in JavaScript would be via the following:
function findMaxLetter(word) {
/* Create a map that relates letters to the number of times that letter occours */
const letterCounts = Array.from(word).reduce((map, letter) => {
return { ...map, [letter] : (map[letter] === undefined ? 0 : map[letter] + 1) }
}, {})
/* Sort letters by the number of times they occour, as determined in letterCounts map */
const letters = Object.entries(letterCounts).sort(([letter0, count0], [letter1, count1]) => {
return count1 - count0
})
.map(([letter]) => letter)
/* Return letter that occoured the most number of times */
return letters[0]
}
console.log("The first letter repeated its: " + findMaxLetter("MBXAYMZAXmZYxxxxxxxxxxmBxAYMZaXmZY"))
I this is solution is most detailed for you
function func( word ){
word = word.toLowerCase();
var i, charCountCache = {};
//store all char counts into an object
for( i = 0; i < word.length; i++){
if( charCountCache[ word[ i ] ] )
charCountCache[ word[ i ] ] = charCountCache[ word[ i ] ] + 1;
else
charCountCache[ word[ i ] ] = 1;
}
//find the max value of char count in cached object
var fieldNames = Object.keys( charCountCache )
, fieldValues = Object.values( charCountCache )
, mostReapeatChar = '', mostReapeatCharCount = 0;
for( i = 0; i < fieldNames.length; i++ ){
if( mostReapeatCharCount < fieldValues[i] ){
mostReapeatCharCount = fieldValues[i];
mostReapeatChar = fieldNames[i];
}
}
console.log('most repeating char: ', mostReapeatChar, ' no of times: ', mostReapeatCharCount )
}
console.log("The first letter repeated its: " + contendor[mycalc])
You tried to print the 14th index of contendor which has only 9 values, that is why your log result was undefined.
You probably wanted to print word[mycalc].
Also if you intended to count x as X, you should have added toUpperCase() to every letter you process/go-through.
This is only a note to the issues in your code, there are better/faster/cleaner solutions to reach the result which i am sure other answers will provide.
my advice would be to create a hashmap such as
letter => [indexLetter1, indexLetter2].
From that hashmap, you could easily find your first repeated letters.
For that string MBXAYMZAXmZYxxxxxxxxxxmBxAYMZaXmZY, hashmap will look like
[
M => [0,5,..],
B => [1, ..],
X => [2, ..],
...
]
now you can find every letter with multiple values in its array, then in those arrays take the one with the lowest value.
If you want to get the index of most repeated letter, you can use Array.from to convert the word into an array. Add a map function to make all letters uppercase.
Get the count of each letter by using reduce and Object.entries
Use indexOf to the get the index of the lettet in the array. Please note that indexOf count the letters from 0.
var word = "MBXAYMZAXmZYxxxxxxxxxxmBxAYMZaXmZY";
var letters = Array.from(word, o => o.toUpperCase());
var [highestLetter, highestCount]= Object.entries(letters.reduce((c, v) => (c[v] = (c[v] || 0) + 1, c), {})).reduce((c, v) => c[1] > v[1] ? c : v);
var index = letters.indexOf(highestLetter);
console.log("Most repeated letter:", highestLetter);
console.log("Count:", highestCount);
console.log("First Index:", index);

Write a function which takes a sentence as an input and output a sorted sentence

I need to write a function which takes a sentence as an input and output a sorted sentence. and there are two criteria:
Each character of the word should be arranged in alphabetical order
Words should be arranged in ascending order depending on its character count
Note: - Word only can have lowercase letters
Example :
Inputs str = "she lives with him in a small apartment"
Output = "a in ehs him hitw eilsv allms aaemnprtt"
Here is my code.
function makeAlphabetSentenceSort(str) {
var sens = str.split(' ');
sens.sort(function(a, b) {
return a.length - b.length;
console.log(sens);
});
function alphaSort(b) {
var x = b.split("");
console.log(x.sort().join(""));
}
for (var i = 0; i <= sens.length - 1; i++) {
console.log(alphaSort(sens[i]));
}
}
console.log(makeAlphabetSentenceSort("she lives with him in a small enter code hereapartment"));
I'm confused about how to solve that. Any suggestion, please?
It appears that your code mostly works. I was able to get the correct output by replacing console.log(x.sort().join("")); with return x.sort().join("");
I also had to remove console.log(alphaSort(sens[i])); in favor of storing the loop output in a temp variable called output and then returning the entire loop output as a string.
function makeAlphabetSentenceSort(str) {
var sens = str.split(' ');
sens.sort(function(a, b){
return a.length - b.length;
});
function alphaSort(b){
var x = b.split("");
return x.sort().join("");
}
var output = "";
for(var i = 0; i <= sens.length - 1; i++){
output += alphaSort(sens[i]) + " ";
}
return output.trim();
}
console.log(makeAlphabetSentenceSort("she lives with him in a small apartment"));
I would also for readability rewrite the code as follows:
Remove alphaSort as a function as it does not need to be a function in the current context.
use let keyword instead of var keyword to instantiate output variable.
instantiate output variable at the top of the function (because this is how JS really works)
function makeAlphabetSentenceSort(str) {
let output = "";
// Sort the initial sentence by words alphabetically.
var sens = str.split(' ');
sens.sort(function(a, b){
return a.length - b.length;
});
for(var i = 0; i <= sens.length - 1; i++){
// Split each word into single characters. Sort the characters and
// join them back as a single string.
output += sens[i].split("").sort().join("");
// Because we want the response to look like a sentence.
output += " ";
}
return output.trim();
}
console.log(makeAlphabetSentenceSort("she lives with him in a small apartment"));

Find the nth character from an array of words in JavaScript

I'd like to create a function (nthChar) that takes 1 parameter - an array of n words.
The function should concatenate the nth letter from each word to construct a new word which should be returned as a string.
The nth letter should be the 1st from the first word in the array, the second from the second word in the array, the third from the third and so on. So:
nthChar(['I','am','Tom']) should return 'Imm'
Here's my attempt:
function nthChar(words){
for (var i=0; i<words.length; i++) {
return words[i].charAt(words.indexOf(words[i]))
}
}
Which only seems to grab the first letter of the first word. How would I proceed to the other words of the array before concatenation?
With minimal changes to your code, you can do this
function nthChar(arr) {
var str = '';
for (var i=0; i<words.length; i++) {
str = str + words[i][i];
}
return str;
}
str - used to build up the result string
words[i] selects the i'th word ... the second [i] in that statement selects the i'th letter in that word
for example: "Hello World"[6] is W
Bonus: works in IE8 and earlier ...
and, just for the hell of it, void's answer in ES6
var nthChar = arr => arr.map((i, v) => i[v]).join('');
This can be as simple as
function nthChar(words){
var s = "";
for(var i=0;i<words.length;i++){
s+= words[i].charAt(i);
}
return s;
}
Live example: http://jsfiddle.net/11yc79jn/
This is closest to your original solution, and just uses the loop control variable i which is incrementing already as you loop through the words array. Of course, also return after the entire loop has run as well.
function nthChar(arr){
return arr.map(function(i, v){
return i[v];
}).join("");
}
console.log(nthChar(['I','am','Tom']));
So it is returning an array of the characters you want and then it is joining it. Makes sense?
The issue with your code was that you were not concatenating anything to the output. You can access the characters of a string as if it is an array.
Live Fiddle
Your code can be:
function nthChar(words){
var str = "";
for (var i=0; i<words.length; i++) {
str += words[i].charAt(i);
}
return str;
}
Fiddle
Try something like this
function nthChar(words){
var result = "";
for (var i = 0, ln = words.length; i<ln; i++)
result += words[i].charAt(i);
return result;
}

comma separated string javascript

I'm sorry it's a stupid question but I'm try to list a sequence of numbers from 1 to a limit and they should be separated by comma. I have a problem. I don't know how to stop the comma. I should have 1,2,3 but I have ,1,2,3. Can you help me? Here is my code.
function getNumberSequence(number) {
var result = ""
if(number <= 0){
return result
}
else{
if(number == 1){
result = result + 1
} else {
for(i = 1; i <= number; i++){
result = result + ',' + i;
}
}
}
return result
}
Thanks for all
You can simply add a flag (in the example "first") and check if this is your first iteration - if so, don't add a comma but set it to false ... see here: http://jsfiddle.net/fdfxc5zq/
var first = true; //have a flag that tells you if this is your first iteration - don't add a comma the first time around
for (i = 0; i <= number; i++) {
if (first) {
first = false;
} else {
result += ", ";
}
result += i;
}
Using your code, simply declare result with an initial value of 1 and start the for loop with i=2. Solved. (And in case of number being 1, just return result)
A one-liner for you:
return Object.keys(Array.apply(null,new Array(number))).map(function(n) {return +n+1;}).join(",");
Basically, creates an array of length number, "applies" it (basically ends up giving undefined values to each index), then uses Object.keys to get the indices of the array, increments all the items, then joins the whole thing with commas.
Two easy methods:
1) Just add a comma after each number and return a substring of length-1 to get rid of the last comma
if (i === 0) return ""; //to avoid substring() issues on empty strings
var result = "";
for (i = 0; i <= number; i++) {
result = i + ",";
}
return result.substr(0, result.length-1);
2) Using array and join
var result = [];
for (i = 0; i <= number; i++) {
result.push(i)
}
return result.join(); //default join separator is the comma
YourCommaSeparatedString.split(',');

Random alpha-numeric string in JavaScript?

What's the shortest way (within reason) to generate a random alpha-numeric (uppercase, lowercase, and numbers) string in JavaScript to use as a probably-unique identifier?
I just came across this as a really nice and elegant solution:
Math.random().toString(36).slice(2)
Notes on this implementation:
This will produce a string anywhere between zero and 12 characters long, usually 11 characters, due to the fact that floating point stringification removes trailing zeros.
It won't generate capital letters, only lower-case and numbers.
Because the randomness comes from Math.random(), the output may be predictable and therefore not necessarily unique.
Even assuming an ideal implementation, the output has at most 52 bits of entropy, which means you can expect a duplicate after around 70M strings generated.
If you only want to allow specific characters, you could also do it like this:
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
Here's a jsfiddle to demonstrate: http://jsfiddle.net/wSQBx/
Another way to do it could be to use a special string that tells the function what types of characters to use. You could do that like this:
function randomString(length, chars) {
var mask = '';
if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (chars.indexOf('#') > -1) mask += '0123456789';
if (chars.indexOf('!') > -1) mask += '~`!##$%^&*()_+-={}[]:";\'<>?,./|\\';
var result = '';
for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
return result;
}
console.log(randomString(16, 'aA'));
console.log(randomString(32, '#aA'));
console.log(randomString(64, '#A!'));
Fiddle: http://jsfiddle.net/wSQBx/2/
Alternatively, to use the base36 method as described below you could do something like this:
function randomString(length) {
return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}
UPDATED:
One-liner solution, for random 20 characters (alphanumeric lowercase):
Array.from(Array(20), () => Math.floor(Math.random() * 36).toString(36)).join('');
Or shorter with lodash:
_.times(20, () => _.random(35).toString(36)).join('');
Another variation of answer suggested by JAR.JAR.beans
(Math.random()*1e32).toString(36)
By changing multiplicator 1e32 you can change length of random string.
Or to build upon what Jar Jar suggested, this is what I used on a recent project (to overcome length restrictions):
var randomString = function (len, bits)
{
bits = bits || 36;
var outStr = "", newStr;
while (outStr.length < len)
{
newStr = Math.random().toString(bits).slice(2);
outStr += newStr.slice(0, Math.min(newStr.length, (len - outStr.length)));
}
return outStr.toUpperCase();
};
Use:
randomString(12, 16); // 12 hexadecimal characters
randomString(200); // 200 alphanumeric characters
This is cleaner
Math.random().toString(36).substr(2, length)
Example
Math.random().toString(36).substr(2, 5)
function randomString(len) {
var p = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
return [...Array(len)].reduce(a=>a+p[~~(Math.random()*p.length)],'');
}
Summary:
Create an array of the size we want (because there's no range(len) equivalent in javascript.
For each element in the array: pick a random character from p and add it to a string
Return the generated string.
Some explanation:
[...Array(len)]
Array(len) or new Array(len) creates an array with undefined pointer(s). One-liners are going to be harder to pull off. The Spread syntax conveniently defines the pointers (now they point to undefined objects!).
.reduce(
Reduce the array to, in this case, a single string. The reduce functionality is common in most languages and worth learning.
a=>a+...
We're using an arrow function.
a is the accumulator. In this case it's the end-result string we're going to return when we're done (you know it's a string because the second argument to the reduce function, the initialValue is an empty string: ''). So basically: convert each element in the array with p[~~(Math.random()*p.length)], append the result to the a string and give me a when you're done.
p[...]
p is the string of characters we're selecting from. You can access chars in a string like an index (E.g., "abcdefg"[3] gives us "d")
~~(Math.random()*p.length)
Math.random() returns a floating point between [0, 1) Math.floor(Math.random()*max) is the de facto standard for getting a random integer in javascript. ~ is the bitwise NOT operator in javascript.
~~ is a shorter, arguably sometimes faster, and definitely funner way to say Math.floor( Here's some info
I think the following is the simplest solution which allows for a given length:
Array(myLength).fill(0).map(x => Math.random().toString(36).charAt(2)).join('')
It depends on the arrow function syntax.
for 32 characters:
for(var c = ''; c.length < 32;) c += Math.random().toString(36).substr(2, 1)
Random character:
String.fromCharCode(i); //where is an int
Random int:
Math.floor(Math.random()*100);
Put it all together:
function randomNum(hi){
return Math.floor(Math.random()*hi);
}
function randomChar(){
return String.fromCharCode(randomNum(100));
}
function randomString(length){
var str = "";
for(var i = 0; i < length; ++i){
str += randomChar();
}
return str;
}
var RandomString = randomString(32); //32 length string
Fiddle: http://jsfiddle.net/maniator/QZ9J2/
Using lodash:
function createRandomString(length) {
var chars = "abcdefghijklmnopqrstufwxyzABCDEFGHIJKLMNOPQRSTUFWXYZ1234567890"
var pwd = _.sampleSize(chars, length || 12) // lodash v4: use _.sampleSize
return pwd.join("")
}
document.write(createRandomString(8))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Random Key Generator
keyLength argument is the character length you want for the key
function keyGen(keyLength) {
var i, key = "", characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var charactersLength = characters.length;
for (i = 0; i < keyLength; i++) {
key += characters.substr(Math.floor((Math.random() * charactersLength) + 1), 1);
}
return key;
}
keyGen(12)
"QEt9mYBiTpYD"
var randomString = function(length) {
var str = '';
var chars ='0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split(
'');
var charsLen = chars.length;
if (!length) {
length = ~~(Math.random() * charsLen);
}
for (var i = 0; i < length; i++) {
str += chars[~~(Math.random() * charsLen)];
}
return str;
};
When I saw this question I thought of when I had to generate UUIDs. I can't take credit for the code, as I am sure I found it here on stackoverflow. If you dont want the dashes in your string then take out the dashes. Here is the function:
function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x7|0x8)).toString(16);
});
return uuid.toUpperCase();
}
Fiddle: http://jsfiddle.net/nlviands/fNPvf/11227/
This function should give a random string in any length.
function randString(length) {
var l = length > 25 ? 25 : length;
var str = Math.random().toString(36).substr(2, l);
if(str.length >= length){
return str;
}
return str.concat(this.randString(length - str.length));
}
I've tested it with the following test that succeeded.
function test(){
for(var x = 0; x < 300000; x++){
if(randString(x).length != x){
throw new Error('invalid result for len ' + x);
}
}
}
The reason i have chosen 25 is since that in practice the length of the string returned from Math.random().toString(36).substr(2, 25) has length 25. This number can be changed as you wish.
This function is recursive and hence calling the function with very large values can result with Maximum call stack size exceeded. From my testing i was able to get string in the length of 300,000 characters.
This function can be converted to a tail recursion by sending the string to the function as a second parameter. I'm not sure if JS uses Tail call optimization
A simple function that takes the length
getRandomToken(len: number): string {
return Math.random().toString(36).substr(2, len);
}
Ff you pass 6 it will generate 6 digit alphanumeric number
Nice and simple, and not limited to a certain number of characters:
let len = 20, str = "";
while(str.length < len) str += Math.random().toString(36).substr(2);
str = str.substr(0, len);
One could just use lodash uniqueId:
_.uniqueId([prefix=''])
Generates a unique ID. If prefix is given, the ID is appended to it.
Here's a simple code to generate random string alphabet.
Have a look how this code works.
go(lenthOfStringToPrint); - Use this function to generate the final string.
var letters = {
1: ["q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m"],
2: ["Q","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M"]
},i,letter,final="";
random = (max,min) => {
return Math.floor(Math.random()*(max-min+1)+min);
}
function go(length) {
final="",letter="";
for (i=1; i<=length; i++){
letter = letters[random(0,3)][random(0,25)];
final+=letter;
}
return final;
}
I used #Nimphious excellent second approach and found that occasionally the string returned was numeric - not alphanumeric.
The solution I used was to test using !isNaN and use recursion to call the function again.
Why bother? I was using this function to create object keys, if all the keys are alphanumeric everything sorts properly but if you use
numbers as keys mixed with alphanumeric (strings) looping through the object will produce a different order to original order.
function newRandomString(length, chars) {
var mask = '';
if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (chars.indexOf('#') > -1) mask += '0123456789';
if (chars.indexOf('$') > -1) mask += '0123456789';
var result = '';
for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() *
mask.length)];
/*
we need a string not a number !isNaN(result)) will return true if '1234' or '3E77'
because if we're looping through object keys (created by newRandomString()) and
a number is used and all the other keys are strings then the number will
be first even if it was the 2nd or third key in object
*/
//use recursion to try again
if(!isNaN(result)){
console.log('found a number....:'+result);
return newRandomString(length, chars)
}else{
return result;
}
};
var i=0;
while (i < 1000) {
var a = newRandomString(4, '#$aA');
console.log(i+' - '+a);
//now we're using recursion this won't occur
if(!isNaN(a)){
console.log('=============='+i+' - '+a);
}
i++;
}
console.log('3E77:'+!isNaN('3E77'));//true
console.log('1234:'+!isNaN('1234'));//true
console.log('ab34:'+!isNaN('ab34'));//false
After looking at solutions in answers to this question and other sources, this is the solution that is simplest while allowing for modification of the included characters and selection in the length of the returned result.
// generate random string of n characters
function randomString(length) {
const characters = '0123456789abcdefghijklmnopqrstuvwxyz'; // characters used in string
let result = ''; // initialize the result variable passed out of the function
for (let i = length; i > 0; i--) {
result += characters[Math.floor(Math.random() * characters.length)];
}
return result;
}
console.log(randomString(6));
Use md5 library: https://github.com/blueimp/JavaScript-MD5
The shortest way:
md5(Math.random())
If you want to limit the size to 5:
md5(Math.random()).substr(0, 5)

Categories