Find the largest sequence of five numbers in a string in Javascript - javascript

HI everyone hopefully an easy one. I have split a string example below in to 5 digit blocks I now need to find the largest 5 number sequence, and not sure how to do this any help much appreciated. "731671765313306249192251196744265747423553491949349698352036854250632623957831801698480186947885184385861560789112949495459501737958331952853208805511125406987471585238630507156932909632952274430435576689664895
function solution(digits){
let output = digits.match(/.{1,5}/g);
console.log(output);
}

This approach (of splitting into chunks of 5), will not always give the optimal result, as you are not looking at every possible chunk of 5... only those that start at an index that is a multiple of 5.
So just iterate through every array index, and then take 5 characters from there, and compare...
let str = "731671765313306249192251196744265747423553491949349698352036854250632623957831801698480186947885184385861560789112949495459501737958331952853208805511125406987471585238630507156932909632952274430435576689664895";
let best = "";
for (let i = 5; i <= str.length; i++) {
let slice = str.slice(i - 5, i);
if (slice > best) best = slice;
}
console.log(best);

Related

Generate random 6 characters based on input

Generate random 6 characters based on input. Like I want to turn 1028797107357892628 into j4w8p. Or 102879708974181177 into lg36k but I want it to be consistant. Like whenever I feed 1028797107357892628 in, it should always spit out j4w8p. Is this possible? (Without a database if possible.) I know how to generate random 6 characters but I dont know how to connect it with an input tbh. I would appreciate any help, thanks.
let rid = (Math.random() + 1).toString(36).substring(7);
You can create a custom hashing function a simple function to your code would be
const seed = "1028797089741811773";
function customHash(str, outLen){
//The 4 in the next regex needs to be the length of the seed divided by the desired hash lenght
const regx = new RegExp(`.{1,${Math.floor(str.length / outLen)}}`, 'g')
const splitted = str.match(regx);
let out = "";
for(const c of splitted){
let ASCII = c % 126;
if( ASCII < 33) ASCII = 33
out += String.fromCharCode(ASCII)
}
return out.slice(0, outLen)
}
const output = customHash(seed, 6)
console.log(output)
It is called hashing, hashing is not random. In your example to get rid:
let rid = (Math.random() + 1).toString(36).substring(7);
Because it is random, it's impossible to be able to produce "consistant result" as you expect.
You need algorithm to produce a "random" consistant result.
Thanks everyone, solved my issue.
Code:
let seed = Number(1028797089741811773)
let rid = seed.toString(36).substring(0,6)
console.log(rid)
Or:
let seed = Number(1028797089741811773)
let rid = seed.toString(36).substring(6)
console.log(rid)

easy way to multiply a value to successive substrings in javascript

Good morning, sorry for my poor English.
I'm a neophyte and I'm trying to create a javascript program that, given a string in input, if it finds inside defined substrings it returns a value to each substring and returns the sum of the values ​​found as output. Everything ok here. But I'm finding it difficult to manage the case where in front of the substring that I'm looking for, there's for example "2x" which means that the value of the next substring (or of all subsequent substring) is to be multiplied for 2. How can I write in simple code this exception?
Example:
A1 = 1
M1 = 1
input description = A1-M1
output = 2
input descritpion = 2 x A1-M1
output = 4
Thanks in advance
For more comprehesion, you can find my code below:
let str_description = "2 x A1-M1";
var time_mont = [];
var time_cloa = [];
if(str_description.includes("A1")){
time_mont.push (0.62);
} else {
time_mont.push (0);
}
if(str_description.includes("M1")){
time_mont.push (0.6);
} else {
time_mont.push (0);
}
How can I manage "2 x " subtring?

Adding space to fill array length

I am working with a javascript program that needs to be formatted a certain way. Basically, I need to have each section of information from an array be a set length, for example 12 characters long, and no more than that.
The problem I am running into comes when a value in the array is NOT 12 characters long. If I have a value that is less than the 12 characters the remaining character allotment needs to be filled with blank spaces.
The length of each section of information varies in size and is not always 12. How can I add X number of blank spaces, should the length not meet the maximum requirement, for each section?
This is where I am at with adding space:
str = str + new Array(str.length).join(' ');
I am pretty sure what I have above is wrong but I believe I am on the right track with the .join function. Any ideas?
EDIT: I was asked to show a wanted outcome. It is a bit complicated because this javascript is being run out of a web report tool and not out of something like Visual Studio so its not traditional JS.
The outcome expected should look something like:
Sample Image
So as shown above the data is in one line, cutting off longer strings of information or filling in blank spaces if its too short for the "column" to keep that nice even look.
try this code and leverage the wonders of the map function:
let say your array is:
var myArr = ["123456789012", "12345678901", "123"];
now just apply this function
myArr.map(function(item){ //evalueate each item inside the array
var strLength = item.length; //apply this function to each item
if (strLength < 12){
return item + ' '.repeat(12-item.length) //add the extra spaces as needed
} else {
return item; // return the item because it's length is 12 or +
}
})
What you are looking for is the ' '.repeat(x) - where x is the times you want to repeat the string you have set, it could be '*'.repeat(2) and you would get '**', if you want to understand more about it look at the docs
depending on which version of javascript, this might work:
if (str.length < 12) str += ' '.repeat(12 - str.length);
Not exactly sure how you're setup -- but something like the following will accept an array and return another array with all its values being 12 characters in length.
var array = ['Test', 'Testing', 'Tested', 'This is not a Test'];
var adjustedArray = correctLength(array, 12);
function correctLength(array, length) {
array.map(function(v, i) {
if (array[i].length < length) {
array[i] += Array((length+1) - array[i].length).join('_');
}
// might not need this if values are already no greater than 12
array[i] = array[i].substring(0, length);
});
return array;
}
console.log(adjustedArray);

NaN Issue - Why does identical code returns diffrent results?

I'm working on a script to match scrambled words to their unscrambled counterpart, and I'm running into a weird NaN problem. I have inserted comments below to guide you further in understand my problem in hopes that you can give me an explanation as to why this problem is occurring. Thank you for your time and help.
NOTE: Two chunks of code that are exactly the same (but with different variable names) act differently. The latter works, but the former does not.
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
</head>
<body>
<form id="words">
<input type="hidden" value="html:),121212,21122112,asdfjkl;,hal9000,1234qwer,1q2w3e,test123,gambit,sports,hello!,willie,hashtags,oneway,whoknows,whyowhy,youwho,theone,sweet!,wo0Oot">
</form>
<br>
<li>leho!l</li>
<li>lilwie</li>
<li>thahsags</li>
<li>yaneow</li>
<li>kwosonhw</li>
<li>ohhywwy</li>
<li>oyuwoh</li>
<li>otheen</li>
<li>e!stwe</li>
<li>wtoO0o</li>
<script>
var words, scram, wordVals, scramVals, sum, i, I;
// Turn word list into an array.
words = [];
var words = document.getElementById("words").elements[0].value.split(",");
// Turn scrambled word list into an array.
scram = [];
for (var i = 0; i < 10; i++) {
scram.push(document.getElementsByTagName("li")[i].innerHTML);
};
// Next I iterate through each letter of each word (for the unscrambled words)
// and convert those letters into ASCII values - adding those together
// to get the total ASCII value of each word.
wordVals = [];
for (i = 0; i < words.length; i++) {
for (I = 0; I < words[i].length; I++) {
sum += words[i].charCodeAt(I);
// console.log(sum)
// Using console.log(sum), you see that the first 6 iterations return NaN.
// Each iteration (ASCII Value) for the first word in this loop
// words[0].charCodeAt(0, 1, 2, 3, 4, 5, 6), all returned NaN.
// But each word after the first iteration calculates the ASCII values
// like it's supposed to.
};
wordVals.push(parseInt(sum));
sum = 0;
console.log("Word[" + i + "]: " + words[i] + " - Value: " + wordVals[i]);
};
// typeof WordVals[0] = number
console.log("typeof wordVals[0]?: " + typeof(wordVals[0]));
// isInteger = false
console.log("isInteger wordVals[0]?: " + Number.isInteger(wordVals[0]));
// Here I am iterating through each letter of each word (for the scrambled words)
// and converting those letters into ASCII values - adding those values together
// to get the total ASCII value of each word.
// **This loop uses the same exact code as the one above (but with different variables)
// and it works correctly. Why is this?
scramVals = [];
for (i = 0; i < scram.length; i++) {
for (I = 0; I < scram[i].length; I++) {
sum += scram[i].charCodeAt(I);
};
scramVals.push(sum);
sum = 0;
console.log("Scram Word[" + i + "]: " + scram[i] + " - Value: " + scramVals[i]);
};
</script>
</body>
</html>
OUTPUT:
Word[0]: html:) - Value: NaN
Word[1]: 121212 - Value: 297
...rest of list omitted...
typeof wordVals[0]?: number
isInteger wordVals[0]?: false
Scram Word[0]: leho!l - Value: 565
Scram Word[1]: lilwie - Value: 646
...rest of list omitted...
I have tried using a different starting word in my word list but get the same NaN result.
I don't understand why the first block of code doesn't work when it is practically identical to the second block of code that does work!
Why am I getting a NaN on the ASCII values of each letter of the first word?
I'm a beginner, and realize that this is not the proper way to go about finding word matches. Regular Expressions is probably what I will try to end up using, but I need to figure this out so I can progress in the way that I learn.
Thank you. I use this site all the time because I love the no nonsense approach most of you take in addressing user requests. There are a lot of really smart people here donating their time and intelligence, and I really appreciate it.
I am also open to any tips you can give me to improve this code.
That is because undefined + Number is NaN. Initially, the sum variable is undefined. that is why the first value in the wordVals array is NaN.
Just set sum to 0 and it should work as expected, ex:
var words, scram, wordVals, scramVals, sum = 0, i, I;
For the first iteration you adding a number with undefined( ie sum). So it'l become NaN. make sum = 0; at the beginning

Total sum of elements (strings) on an array

I am making a program that depending of my 6 characters that I use in sm4sh, outputs me the characters that helps the other with the large quantity of good matches helping the other character with bad matches, for example, I use Rosalina, she is bad against Mario, but with Ganondorf the match is slightly in my favor, what I want to do right now is the sum of all the elements in the array to check the 54 characters in all the arrays of my 6 characters (to not have imbalanced arrays for the moment).
Thanks.
w//ROSALINA
var rosalina_good_matches = ["Ganondorf","King Dedede","Little Mac","Jigglypuff","Duck Hunt","Bowser","Zelda","Dr Mario","Charizard","Donkey Kong","Mr Game and Watch","Robin","Wario","Ness","Palutena","Wii Fit Trainer","Peach","Mewtwo","Samus","Mega Man","ROB","Lucina","Pac-Man","Falco","Toon Link","Yoshi","Marth","Ike","Link","Villager","Kirby","Greninja","Roy","Diddy Kong","Shulk","Luigi","Fox","Lucario","Meta Knight","Olimar","Sonic","Corrin","Sheik"];
var rosalina_even_matches = ["Pit","Dark Pit","Lucas","Captain Falcon","Pikachu","Bayonetta","Cloud"];
var rosalina_bad_matches = ["Mario","Zero Suit Samus","Ryu"];
//Check the sum of 54 characters
for(var i = 0;i < rosalina_good_matches.length;i++){
console.log(rosalina_good_matches[i]);
}
To get sum of all array elements (in one string) you should use.join() (check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join)

Categories

Resources