Extending a Variable's Length With Random Numbers Doesn't Work - javascript

I am making an AI that tries to solve a user-inputted "numberle" in JavaScript. I don't want the user to do extra work just to see an AI do it's thing, so on the input field, if the user inputs a number that has less than 5 digits, the JavaScript should add random numbers at the end of the variable, until it has a total of five digits.
I used all the loops I had experience with, under an if statement, so if the length of the input was less than 5 (like 3), the loop will add 5 - the number of digits of the input (2) digits that are random, using the Math.random attribute.
Here is the code I currently have:
if (input.length < 5)
do {
input = (input * 10) + Math.floor(Math.random() * 9) + 1;
} while (input.length < 5);
}
console.log(input)
I have also used the for and while loops with basically the same condition (obviously modified for the if loop; made a variable for input.length so that it has the same value).
Here is what I get in the console:
5 // Inputted number (1 digit)
52 // Inputted digit + random number
As you can see, the loop only runs once, although it should've ran 3 more times. I am using strict mode also. My code editor is github.dev, and I am using the CodeSwing console.

If input is a number, it will not have "length", since it is not a string.
You can achieve the desired result like this:
let input = 5;
let digits = 2;
while (input < 10**(digits-1)) input = ~~((input+Math.random())*10);
console.log(input);
Note that ~~ is a compact way of doing Math.floor()
Alternatively, without a while loop:
let input = 5, digits = 2, M = Math; L = x=>~~(M.log(x)/M.log(10))+1;
input = ~~((input+M.random())*10**(digits - L(input)));
console.log(input);

Related

Why is for-loop sometimes skipping some iterations?

In the function below, the for loop sometimes skips one iteration.
In some rare cases, I've also found it skipping two iterations.
This sometimes breaks my code and would probably affect my future codes, if my understanding of the for loop remains incomplete.
I further looked into the matter and tried the same with a while loop and found out that this problem doesn't happens if a while loop is used.
Why is the for-loop sometimes skipping some iterations ?
function forLoopString(len)
{
var string = 'abcdefghijklmnopqrstuvwxyz0123456789';
var character = '',
randomString = '';
for (var i = 0; i < len; i++)
{
character = string.charAt(Math.floor(Math.random() * string.length-1) + 0);
randomString += character;
}
if(randomString.length < len)
{
console.log('Less than required length!');
randomString = randomString + '5';
}
return randomString;
}
JSFiddle
The loop shown won't "skip" any iterations, but will iterate from [0, len) as told to do.
However, a negative argument to charAt makes it seem like it "skips" because "foo".charAt(-1) == "". The same empty-string result holds for any out-of-bounds to String.charAt:
.. If the index you supply [to charAt] is out of range, JavaScript returns an empty string.
A correction that yields an always-valid index would merely be Math.floor(Math.random() * string.length), without the -1.
Although this is slightly biased (for anyone that really cares) this is 'correct' because Math.random returns a number in the range [0, 1). Thus Math.random() * len returns a value from [0, len); and as an Integer in the same interval after the floor.
Also, it would be good to choose more useful variable names.. and, as Ed points out the +0 is irrelevant because Math.floor returns a (integer) number.
The random number is sometimes negative, that's why a character is skipper from randomString in those cases.
https://jsfiddle.net/ojbp0evz/3/
Use Math.abs for example.
Your problem is HERE:
character = string.charAt(Math.floor(Math.random() * string.length-1) + 0);
if your rand is less than 0, you will get a negative number, and therefor, you won't get any character. You must encapsulate your string.length-1 like so:
character = string.charAt(Math.floor(Math.random() * (string.length-1)));
Updated fiddle: DEMO
Always remember: MULTIPLICATIONS GOES FIRST!!
EDIT: string.length is 36, you dont need to substract 1 to it, just multiply
character = string.charAt(Math.floor(Math.random() * string.length));

How can I check that a bit is set (without bitwise operation)?

Looking at the int 44 — I need Math.CEIL (log(2) 44) of binary places to represent 44.
(answer is 6 places)
6 places :
___ ___ ___ ___ ___ ___
32 16 8 4 2 1
But how can I check that (for example) the bit of 8 is checked or not ?
A simple solution will be do to :
((1<<3) & 44)>0 so this will check if the bit is set.
But please notice that behind the scenes the computer translates 44 to its binary representation and just check if bit is set via bitwise operation.
Another solution is just to build the binary myself via toString(2) or mod%2 in a loop
Question
Mathematically Via which formula, I can test if n'th bit is set ?
(I would prefer a non loop operation but pure single math phrase)
Divide by the value of the bit that you want to check
and test if the first bit is set (this can be tested with x mod 2 == 1)
Math expression:
floor(value/(2^bitPos)) mod 2 = 1
As JS function:
function isSet(value, bitPos) {
var result = Math.floor(value / Math.pow(2, bitPos)) % 2;
return result == 1;
}
Note: bitPos starts with 0 (bit representing the nr 1)
The 'bit' (actually any base) value of an indexed number index in a value val in base base can in general be calculated as
val = 1966;
index = 2;
base = 10;
alert (Math.floor(val/Math.pow(base,index)) % base);
result: 9
val = 44;
index = 3;
base = 2;
alert (Math.floor(val/Math.pow(base,index)) % base);
result: 1 (only 0 and 1 are possible here – the range will always be 0..base-1).
The combination of Math.floor (to coerce to an integer in Javascript) and Math.pow is kind of iffy here. Even in integer range, Math.pow may generate a floating point number slightly below the expected 'whole' number. Perhaps it is safer to always add a small constant:
alert (Math.floor(0.1+val/Math.pow(base,index)) % base);
You can simply check if the bit at the position is set to 1.
function isBitSet(no, index) {
var bin = no.toString(2);
// Convert to Binary
index = bin.length - index;
// Reverse the index, start from right to left
return bin[index] == 1;
}
isBitSet(44, 2); // Check if second bit is set from left
DEMO

Addition and Subtraction with Negative Numbers

I tried adding and subtracting negative numbers with this code
var num1 = parseInt(document.form1.num1.value);
var num2 = parseInt(document.form1.num2.value);
if(operand == "plus"){
var sum = parseInt(num1+num2);
// add alerts to check
alert (num1);
alert (num2);
alert (sum);
}else{
var sum = parseInt(num1-num2);
}
but when I print the result (sum), the program ignore the negative number and just count it as if it's a positive number. I tried delete the parseInt but nothing changes.
for those who's confused : my inputs are num1 and num2. using the code I had, if I input (4) and (-2) and choose plus sign, sum = 6. they dont count the negative as negative, but as positive.
update : apparently even if I input (-2), they save it as (2).
Assuming sum1 and sum2 are string literals, what you should do is parseInt(num1) + parseInt(num2)
It seems your problem is that you're applying a double negative, which makes a positive:
4 - -2 == 4 + 2

How to read letter by letter in textfield using javascript

I want to verify a Singapore NRIC using javascript,
the formula is
1) Take for example I want to test the NRIC number S1234567. The first digit you multiply by 2, second multiply by 7, third by 6, fourth by 5, fifth by 4, sixth by 3, seventh by 2. Then you add the totals together. So,1×2+2×7+3×6+4×5+5×4+6×3+7×2=106.
2) If the first letter of the NRIC starts with T or G, add 4 to the total.
3) Then you divide the number by 11 and get the remainder. 106/11=9r7
4) You can get the alphabet depending on the IC type (the first letter in the IC) using the code below:
If the IC starts with S or T: 0=J, 1=Z, 2=I, 3=H, 4=G, 5=F, 6=E, 7=D, 8=C, 9=B, 10=A
If the IC starts with F or G: 0=X, 1=W, 2=U, 3=T, 4=R, 5=Q, 6=P, 7=N, 8=M, 9=L, 10=K
How can I read every single number to do the formula?
Thanks in advance!
Strings are arrays so you can assign variables to the letters assuming you know the string has a fixed length, which it appears so, and then create a function to evaluate the characters and do the correct thing:
var nric = 'S1234567'
var chars = {
letter: nric[0],
one: nric[1],
...
}
string.charAt(charpos)
Should do the trick.
Alternatively,
string.substr(charpos,1)
You could also do
string[charpos]
but the first two above are recommended. This will return undefined if the string is empty, whereas the other alternatives will all return the null string.
Another idea is
string.split("")[charpos]
Finally, there is
string.slice(charpos,1)
Since you want a single character at a time I'd recommend charAt.
Elaborating on #elclanrs answer:
var nric = 'S1234567'
var numVal = 0; for(var i = 1, bound = nric.length; i < bound; i++){
numVal += parseInt(nric[i]);
}
if(nric[0] === 'S' && numVal === 28){
alert('ok');
}else{
alert('wrong');
}
should more or less do the trick.
I trust, You can do the multiplying yourself :-)

Javascript Greater than or less than

I did a rewrite of the code I submitted yesterday based on suggestions from others. I now have this but still can't seem to get it to work with greater than less than. I can add/substract the 2 numbers and get a valid answers. I can't get a > < to work however. Hoping someone can offer some additional help keeping it within this format of "If statements".
if ((input.search("what is greater")!= -1) && (input.search(/\d{1,10}/)!=-1) && (input.search(/\d{1,10}/)!=-1))
{var numbersInString = input.match(/\d+/g);
var num1 = parseInt( numbersInString[0], 10 );
var num2 = parseInt( numbersInString[1], 10 );
if (num1 < num2) document.result.result.value = ""+num1+" is less than "+num2+"";
if (num1 > num2) document.result.result.value = ""+num1+" is greater than "+num2+"";
if (num1 = num2) document.result.result.value = "Both numbers are equal";
return true;}
It sounds like you want to manipulate a number in two ways:
1) You want to refer to the individual characters.
2) You want to compare the number to another number and see if one is greater than another.
If you have a string called input, then you can use the function parseInt(input, 10) to convert it from a string to the number represented by that string.
If you want to get just the first two characters, you can use the substring function.
The important thing to keep in mind is that to the computer, the string '12345' and the number 12345 are completely different. The computer has a completely different set of operations that it will perform on each.
also, #albin is correct to point out that putting semicolons after your if statements is wrong.
The output of the match method is an array of strings, so I think you are NOT comparing numbers but strings. Try doing this before comparing your numbers.
var num1 = parseInt( numbersInString[0], 10 );
var num2 = parseInt( numbersInString[1], 10 );
And then compare num1 and num2.
http://jsfiddle.net/qt3RW/
Simple input box:
​​​​
<input id="input1" value="Is 6 greater than 5"></input>
Parser find 'Is # greater than #' where # is digit and alert this digits:
var IsStringValid = $("#input1").val().match(/Is \d greater than \d/g);
alert(IsStringValid);
if(IsStringValid){
var values = $("#input1").val().match(/\d/g);
for(var i = 0; i < values.length; i++){
alert(values[i])
}
}
​

Categories

Resources