Create number range from input field - javascript

I have input field for ZIP, when user fill out field I want create two variables with first ground value.
example:
User type: 01250,
I need two variables with values 01000 and 02000
var zip = $('.js-zip-input').val();
var inputZip = zip % 1000;
var zipMax = zip - inputZip + 1000;
var zipMin = zip - inputZip;
This working for values when first char isn't 0

It's 'not working' because these are numbers, and it doesn't make sense to have a number 01000. This is really just 1000. If you really need to have the zero, you will have to turn your values into strings and add 0 to the beginning of them.

Is this what you wanted?
var zip = 1250;
var range = 1000;
var zipMin = Math.floor(zip/range) * range;
var zipMax = zipMin + range;
The code above gets the floor value of the zip input.
You can set up the range value as the difference of both outputs: in your case 1000 to 2000 would have a range of 1000. Give it a try.
As gavin pointed out, you cant have a leading 0 before the output unless you convert them to string. In this case, you can check for the length of the output (as strings) and add leading zeroes.
var outputLength = 5;
var zipMinOutput = "0".repeat(outputLength - zipMin.toString().length) + zipMin;
var zipMaxOutput = "0".repeat(outputLength - zipMax.toString().length) + zipMax;
The above code adds trailing zeroes for every missing character in the string.

(function(){
var zip = '00000140050';
var zeros = leading_zero(zip.toString().split('').map(Number)); //Number of zeros can be appended to min max values
alert(zeros);
var inputZip = zip % 1000;
var zipMax = zip - inputZip + 1000;
var zipMin = zip - inputZip;
alert(zipMax + ', ' + zipMin);
function leading_zero(x)
{
var n = 0;
for (var i = 0; i < x.length; i ++) {
if (x[i] == 0) n++;
else
break;
}
return n;
}
}());

Related

Is there a way to make an iterator variable greater than something and less then something?

So, the assignment is generating a random password between 7-10 characters. Is this valid syntax in my for loop which generates the amount of numbers.
var password = "";
var characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz0123456789##$";
for (i = 1; i <= 10; i++) {
var char = Math.floor(Math.random() * characters.length + 1);
password += characters.charAt(char);
}
console.log(password);
So, this current for loop makes the password ten characters.
I want it to be between 7 and 10 characters.
Is it valid Javascript syntax to do i<=10 && i>=7?
What you can do is select a random number from 0 to 3. Based on that number, you will decide how long your password is. Could be 7+0 or 7+1 or 7+2 or 7+3.
Now the number of times your loop runs is dynamic and hence you will get passwords of different lengths.
var password = "";
var characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz0123456789##$";
let x = Math.floor(Math.random()*4);
for (i = 1; i <= (7+x); i++) {
var char = Math.floor(Math.random() * characters.length + 1);
password += characters.charAt(char);
}
console.log(password);

How do read the last character per string?

My code generates a string, as shown in the image. At the end of each line a number in euros is shown, let call these euros1 and euros2. The idea is that the amount ✓ icons is multiplied with euros1 and euros2 shown per line. So in the case of my example: (10,45 + 5,50) x 2 = 31,90 for the first line, and for the second line (18,24 + 9,60) x 3 = 83,52. These numbers are supposed to be combined to a total of 115,42.
However my current code produces a total of 218,95. So it takes the sum of all the euros1 and euros2 and multiplies it by the total amount of ✓ icons.
How can I calculate the sum of the euros1 + euros2 x the amount ✓ icons, per line?
I think a for loop could help me, however I am new to Javascript and I am not sure how to proceed.
var temp = g_form.getValue('mwadm_onkosten_list_refList_changes');
var count = (temp.match(/✓/g) || []).length;
var lastChar = temp[temp.length -1];
if (count != temp);
{
total = total * count;
}
I was thinking of a split solution just like #dganenco mentioned. I created a TEMP variable to reproduce your result string. And execute a function on it foreach row.
And i intentionally kept it really simple. Hope this helps.
var temp = ["✓|| €10,45 | €1,50 ", "✓|| €10,45 | €2,50 ", "✓|| €10,45 | €3,50 "];
var totalTimes = (String(temp).match(/✓/g) || []).length;
//perform function for each row
temp.forEach(CalculateRow);
//Splits the row, Gets euro1 as decimal, euro2 as decimal, calculates the amount a character is found, calculates total, prints it to console.
function CalculateRow(item, index) {
var arr = item.split('|');
var euro1 = GetValueFromArray(arr,1);
var euro2 = GetValueFromArray(arr, 2);
var times = (String(arr).match(/✓/g) || []).length;
var _total = (euro1 + euro2) * times;
console.log(_total);
}
//Takes the index value, and casts it to decimal value
function GetValueFromArray(arr, index){
var getindex = arr.length -index;
var result = arr[getindex];
result = result.replace('€', '');
return parseFloat(result, 10);
}
I've got a solution for you in case if is it possible to only split strings by | symbol, then get last 2 values and do all needed stuff using them.
const strArr = ['asd|addf|$56.60|$10.40', 'asd|addf|$5.60|$1.40'];
let sum = 0;
strArr.forEach(str => {
const splitted = str.split('|');
debugger;
const x = getNumber(splitted[splitted.length - 2]);
const y = getNumber(splitted[splitted.length - 1]);
sum += (x+y)*2;
});
function getNumber(str){
return +str.substring(1);
}
console.log(sum)
Assuming temp is the multiline string in the form of
asd|√|√| €12.34 | €15.25
zxc|√|| €18.34 | €19.25
This code should give you a sum of last two numbers multiplied by the amount of √
var temp = "asd|√|√| €12.34 | €15.25\nzxc|√|| €18.34 | €19.25"
let lines = temp.split('\n')
let linesSummaries = []
for(let line of lines){
var count = line.match(/√/g).length
var vars = line.split('|')
var x = parseFloat(vars[vars.length-1].match(/\d+\.?\d*/))
var y = parseFloat(vars[vars.length-2].match(/\d+\.?\d*/))
var lineSum = (x + y ) * count
linesSummaries.push(lineSum)
}
console.log(linesSummaries)

Generate string of random number that includes some number and exclude some number

I have a problem about generating string in javascript.
I have an array of number that string should contains atleast 1, and 1 number(up to 7 digits) that must not contains in a string. String length must be 7.
var incNumber = ["15","51","14","41","55","39","23"];
var exclude = ... //input from user
I tried to generate it by random select from array, random position and random other number around selected number. Then check if string contains excluded number, generate it again.
//random select number
var getRandom = incNumber[Math.floor(Math.random() * incNumber.length)];
//random position of number
var position = Math.floor(Math.random() * 6);
//length of other string after selected number
var afterlen = 7 - (position+2);
//genNum(...) is my function that use to generate string of number in specific length.
var nstr = genNum(position)+getRandom+genNum(afterlen);
while (nstr.includes(exclude)) {
nstr = genNum(position)+getRandom+genNum(afterlen);
}
but doing this take too long time or sometimes freeze my browser. How should I fix it.?
edited: It's my homework about phonenumber.
final string should be like "37915002"
Edited my code again
Does that now match your needs? It has got pretty messy and I'm not sure if it's correct (I'm never sure.. xD) hope you can get some inspiration though.
// Variables
var initialList = ["100", "5", "19", "88", "10", "90"];
var excludeList = ["9", "10"];
var resultLength = 7;
var finalString = "";
// Create a third final array that is filtered
var finalList = initialList.filter(element => {
let shouldBeIncluded = true;
excludeList.forEach(excluder => {
Array.from(excluder).forEach(excluderFragment => {
if (element.includes(excluderFragment)) shouldBeIncluded = false;
});
});
if (shouldBeIncluded) return true;
});
// Check if all were excluded
if (finalList.length == 0) {
// Do error handling here
} else {
// Create the list
for (let i = 0; i < resultLength; i++) {
finalString += finalList[Math.floor(Math.random() * finalList.length)];
}
// Shorten the list because multiple digits values
finalString = finalString.slice(0, 7);
console.log(finalString);
}
You could start by filtering the unwanted number from the incNumber and doing everything the same way but on the new array
var incNumber = ["15","51","14","41","55","39","23"];
var exclude = "12";
var filteredNumbber =incNumber.filter(number=> number!==exclude);
var random = filteredNumbber[Math.floor(Math.random() * filteredNumbber.length)];
if we assume exclude is not a value but instead an array of values you would change the formula to
var incNumber = ["15","51","14","41","55","39","23"];
var exclude = ["15"];
var filteredNumbber =incNumber.filter(number=> !exclude.includes(number));
var random = filteredNumbber[Math.floor(Math.random() * filteredNumbber.length)];
as some people suggested random variable may end up as undefined if we exclude all the numbers inside of incNumber, if that was the case we should add an additional check in case that happens
if (random!==undefined) var nstr = genNum(position)+random+genNum(afterlen);

Sorting function?

I need to organize an array of strings of random length into the least number of new strings with a max size. Is there a function or something in javascript, or something that can be translated to javascript, that will do this?
For example, the new strings might have max lengths of 1000 characters. The array might have strings of lengths 100, 48, 29, etc. I would want to combine those strings into as few new strings as possible.
edit: Sorry if this doesn't make sense, I tried my best.
No standard method in Javascript, but plenty of theoretical work has been done on this (i.e. the bin packing problem).
http://en.wikipedia.org/wiki/Bin_packing_problem
Some sample pseudo code in the link - should be trivial to translate to javascript.
The algorithm shown isn't going to be optimal in every case. To find the optimal solution to your example you'll just need to iterate over every possibility which might not be that bad depending on how many strings you have.
For my own entertainment, I wrote a simple bin packing algorithm. I picked a simple algorithm which is to sort the input strings by length. Create a new bin. Put the first (longest remaining) string into the bin and then keep filling it up with the longest strings that will fit until no more strings will fit. Create a new bin, repeat. To test it, I allocate an array of strings of random lengths and use that as input. You can see the output visually here: http://jsfiddle.net/jfriend00/FqPKe/.
Running it a bunch of times, it gets a fill percentage of between 91-98%, usually around 96%. Obviously the fill percentage is higher if there are more short strings to fill with.
Here's the code:
function generateRandomLengthStringArrays(num, maxLen) {
var sourceChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY1234567890";
var sourceIndex = 0;
var result = [];
var len, temp, fill;
function getNextSourceChar() {
var ch = sourceChars.charAt(sourceIndex++);
if (sourceIndex >= sourceChars.length) {
sourceIndex = 0;
}
return(ch);
}
for (var i = 0; i < num; i++) {
len = Math.floor(Math.random() * maxLen);
temp = new String();
fill = getNextSourceChar();
// create string
for (var j = 0; j < len; j++) {
temp += fill;
}
result.push(temp);
}
return(result);
}
function packIntoFewestBins(input, maxLen) {
// we assume that none of the strings in input are longer than maxLen (they wouldn't fit in any bin)
var result = [];
// algorithm here is to put the longest string into a bin and
// then find the next longest one that will fit into that bin with it
// repeat until nothing more fits in the bin, put next longest into a new bin
// rinse, lather, repeat
var bin, i, tryAgain, binLen;
// sort the input strings by length (longest first)
input.sort(function(a, b) {return(b.length - a.length)});
while (input.length > 0) {
bin = new String(); // create new bin
bin += input.shift(); // put first one in (longest we have left) and remove it
tryAgain = true;
while (bin.length < maxLen && tryAgain) {
tryAgain = false; // if we don't find any more that fit, we'll stop after this iteration
binLen = bin.length; // save locally for speed/convenience
// find longest string left that will fit in the bin
for (i = 0; i < input.length; i++) {
if (input[i].length + binLen <= maxLen) {
bin += input[i];
input.splice(i, 1); // remove this item from the array
tryAgain = true; // try one more time
break; // break out of for loop
}
}
}
result.push(bin);
}
return(result);
}
var binLength = 60;
var numStrings = 100;
var list = generateRandomLengthStringArrays(numStrings, binLength);
var result = packIntoFewestBins(list, binLength);
var capacity = result.length * binLength;
var fillage = 0;
for (var i = 0; i < result.length; i++) {
fillage += result[i].length;
$("#result").append(result[i] + "<br>")
}
$("#summary").html(
"Fill percentage: " + ((fillage/capacity) * 100).toFixed(1) + "%<br>" +
"Number of Input Strings: " + numStrings + "<br>" +
"Number of Output Bins: " + result.length + "<br>" +
"Bin Legnth: " + binLength + "<br>"
);

Javascript - generating a random number of specified length from set of specified values

I wanted to generate a random number 32 characters in length from a specified set of characters.
For example:
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
var string_length = 32;
Which would then return a random number of length 32 using the specified characters.
Something like this?
Check out the jsfiddle. I modified it so you can see the progression as the result grows: http://jsfiddle.net/YuyNL/
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ"; // Pool of potential characters
var string_length = 32; // Desired length of result
var num_chars = chars.length; // Total number of characters in pool
var result = ''; // Container to store result
while(string_length--) { // Run a loop for a duration equal to the length of the result
// For each iteration, get a random number from 0 to the size of the
// number of characters you're using, use that number to grab the index
// of the character stored in 'chars', and add it to the end of the result
result += chars[ Math.floor( Math.random() * num_chars ) ];
}
$('body').append(result + '<br>'); // This just appends the result to the 'body'
// if you're using jQuery
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
var string_length = 32;
var myrnd = [], pos;
// loop as long as string_length is > 0
while (string_length--) {
// get a random number between 0 and chars.length - see e.g. http://www.shawnolson.net/a/789/make-javascript-mathrandom-useful.html
pos = Math.floor(Math.random() * chars.length);
// add the character from the base string to the array
myrnd.push(chars.substr(pos, 1));
}
// join the array using '' as the separator, which gives us back a string
myrnd.join(''); // e.g "6DMIG9SP1KDEFB4JK5KWMNSI3UMQSSNT"
// Set up a return variable
var randStr = "";
// Split the chars into individual array elements
chars = chars.split("");
// Until string_length is 0...
while (string_length--)
// ... select a random character from the array
randStr += chars[Math.floor(Math.random() * chars.length)];
// return the string
return randStr;
Here is a simple solution that should be quite easy to understand.
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
var string_length = 32;
var result = "";
for(var i=0; i<string_length; i++){
var randomPos = Math.floor( Math.random() * chars.length );
result += chars.substr(randomPos, 1);
}
Maybe make it a little more flexible.
You may want the return to be an array,
if you are going to do any big integer math on it
function charsRandom(len, chars){
chars= chars || "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
len= len || 32;
var cr= [], L= chars.length;
while(len--) cr[cr.length]= chars.charAt(Math.floor(Math.random()*L));
return cr.join(''); // or return the array cr
}
alert(charsRandom())

Categories

Resources