math.random always returning 1 in array - javascript

So i ran the code about 50 times and each time it returned olg / 1 so What is wrong
alert("welcome to word unscrambler undscramble this")
console.log("i am not a distraction")
document.write("i am not a distraction either")
var r = ["pttoao","recme","logd","teey","olg"]
var g=Math.floor(Math.random() *+ 6);
if (g=="0") {select =("pttoao")}
else if(g=="1"){select=("recme")}
else if (g==2){select="logd"}
else if(g==3){select="dre"}
else if(g==4){select="olg"}
if(select=="pttoao"){realword="potato"}
if(select=="recme"){realword="creme"}
if(select=="logd"){realword="gold"}
if(select=="teey"){realword="yeet"}
if(select="olg"){realword="log"}
var awnser= prompt("unscramble "+select)
if(awnser==realword){alert("correct")
}else{
alert("incorrect")}
maybe it is that it cant randomly select words

Here's some code that works for any amount of words.
Notice the structure: array of objects, objects have the real word and the scramble of it.
The random is relative to the amount of words.
I've combined the prompt, the check, and the alert into one line.
"Simplify by complication..." :)
var words=[
{real:"potato", scrambled:"pttoao"},
{real:"creme", scrambled:"recme"},
{real:"gold", scrambled:"logd"},
{real:"yeet", scrambled:"teey"},
{real:"log", scrambled:"olg"}
];
var random=Math.floor(Math.random()*words.length);
alert(
prompt("Unscramble: "+words[random].scrambled)
==
words[random].real?
"Correct":
"Wrong"
);

var g=Math.floor(Math.random() *+ 6 )
should be replaced with following as array elements index starts from
zero and array "r" contains 5 elements
var g=Math.floor(Math.random() * 5);
if(select="olg"){realword="log"}
here, you have assigned "olg" value to select variable. Inside "if" condition assignment is simply returning assigned value which is "olg" that makes it true and executes realword="log"
It should be replaced with
if(select=="olg"){realword="log"}

Related

How do I display messages using an array or object

I've created a random generator game and this is a RandomNumber() function that will display the message if the user keys in the correct or wrong number. Does anyone knows how to display the message using an array or object method? For example, "Your guess number 1 is 5 and it is too low", "Your guess number 2 is 23 and it is too high". So the maximum number a user have is 5 tries.
function RandomNumber()
{
if (!this.guesses)
{
this.guesses = 1;
}
else
{
this.guesses++;
if (this.guesses > 5)
{
document.getElementById("correct").innerHTML="No more tries";
document.getElementById("guessing").disabled=true;
return;
}
}
//get value from random number textbox
var lol=document.getElementById("guess").value;
//get new value from user
var ass=document.getElementById("textbox").value;
if(ass == lol)//if user guess correctly
{
document.getElementById("correct").innerHTML="Correct"
}
else if(ass!=lol)//if user guess wrongly
{
document.getElementById("correct").innerHTML="Not correct"
}
}
function getMessage(correctNumber, guess, guessNumber) {
const highOrLow = guess > correctNumber?"too high.":"too low.";
return `Your guess number ${guessNumber} is ${guess} and it is ${highOrLow}`;
}
const message = getMessage(3, 5, 1); // message now equals "Your guess number 1 is 5 and it is too high."
Explanation:
The first line const highOrLow = guess > correctNumber?"too high.":"too low."; creates the part of the string that says "too high" or "too low" using a ternary operator. If guess is too high then highOrLow will equal "too high.". It will equal "too low." otherwise. The second line uses javascripts string templating to create the final string. The ${variable} part of the string are replaced with the value of variable.
Keep in mind this function doesn't account for when "guess" and "correctNumber" are equal.
This doesn't use an array or object but there is no reason to use an array or object. If you really want to put it in an object then do:
var o = {message: getMessage(3, 5, 1)}
but I don't see why you would need to do that.

variable not working in function

Why are these two codes in javascript different from each other? This is the first code:
var string = "I am 21 years old. My number is 0799340540"
string += " and I am 19. My number is 0786432560";
var validate = /\d+/g;
var result;
while ((result = validate.exec(string)) != "null") {
document.write(result[0] + "<br>");
}
and this is the second code
var string = "I am 21 years old. My number is 0799340540"
string += " and I am 19. My number is 0786432560";
var validate = /\d+/g;
var result = validate.exec(string);
// while (result != "null") {
// document.write(result[0] + "<br>");
//}
// the commented lines will create an infinite loop
As was stated in some of the comments, the difference essentially comes down to the fact that in the first code snippet, the regular expression is continuously evaluated until it reaches the end of the string, in the second one, it is evaluated once. What this results in your example is that the first one will execute the code in the while loop 4 times, then exit. Whereas the second one will be stuck in an infinite loop. For instance:
while((result = validate.exec(string)) != null){
document.write(result[0] + "<br>");
}
WIll execute validate.exec() for every iteration if the loop, each time it searches the string from where it left off, untill it finally finishes the search and returns null, at this point the while condition is false and therefore it exits the loop.
Now in this code:
var result = validate.exec(string);
while(result != null){
document.write(result[0] + "<br>");
}
validate.exec() is only executed once in the first line, and it returns an array containing information about the search. it is not null. So when your while loop runs, in every iteration of the loop it checks if result != null, and since nowhere in the loop are you updating the value of result, it will never change and so result != null will always evaluate to true, thereby never exiting the loop.
UPDATE
As was pointed out, you also need to correctly check for null, instead of comparing to the string value of "null", you need to compare to the primitive value of null. Updated the snippets above to reflect this.

How do I grab user input after an # symbol and before a space?

I want to grab the user input from an input tag including everything after the # symbol and up to a space if the space exists. For example:
If the user input is "hello#yourname"
I want to grab "yourname"
If the user input is "hello#yourname hisname"
I want to grab "yourname" because it is after the # symbol and ends at the space.
I have some code written that attempts to grab the user input based on these rules, but there is a bug present that I can't figure out how to fix. Right now if I type "hello#yourname hisname"
My code will return "yourname hisn"
I don't know why the space and four characters "hisn" are being returned. Please help me figure out where the bug is.
Here is my function which performs the user input extraction.
handleSearch(event) {
let rawName, nameToSearch;
rawName = event.target.value.toLowerCase();
if (rawName.indexOf('#') >= 0 && rawName.indexOf(' ') >= 0) {
nameToSearch = rawName.substr(rawName.indexOf('#') + 1, rawName.indexOf(' ') - 1);
} else if (rawName.indexOf('#') >= 0 && rawName.indexOf(' ') < 0) {
nameToSearch = rawName.substr(rawName.indexOf('#') + 1);
} else {
nameToSearch = '';
}
return nameToSearch;
}
Working example:
handleSearch(event) {
let rawName = event.target.value.toLowerCase();
if (rawName.indexOf("#") === -1) {
return '';
}
return (rawName.split("#")[1].split(" "))[0];
}
You have to handle a lack of "#", but you don't need to handle the case where there is a space or not after the "#". The split function will still behave correctly in either of those scenarios.
Edit: The specific reason why OP's code doesn't work is because the substr method's second argument is not the end index, but the number of characters to return after the start index. You can use the similar SUBSTRING method instead of SUBSTR to make this easier. Change the line after the first if statement as follows:
nameToSearch = rawName.substring(rawName.indexOf('#') + 1, rawName.indexOf(' '));
const testCases = [
"hello#yourname",
"hello#yourname hisname"
];
for (let test of testCases) {
let re = /#(.*?)(?:\s|$)/g;
let result = re.exec(test);
console.log(result[1]);
}
Use regex instead if you know how the string will be created.
You could do something like this--
var string = "me#somename yourname";
var parts = string.split("#");
var parts2 = parts[1];
var yourPart = parts2.split(" ");
console.log(yourPart[0]);
NOTE:
I am suggesting it just because you know your string structure.
Suggestion
For your Piece of code I think you have some white space after hisn that is why it is returning this output. Try to replace all the white spaces with some character see if you are getting any white space after hisn.
I'm not sure of the language your code is in (there are several it 'could be', probably Javascript), but in most languages (including Javascript) a substring function 'starts at' the position of the first parameter, and then 'ends at' that position plus the second parameter. So when your second parameter is 'the position of the first space - 1', you can substitute 'the position of the first space - 1' with the number 13. Thus, you're saying 'get a substring by starting one after the position of the first # character i.e. position 6 in a zero-based system. Then return me the next 13 characters.'
In other words, you seem to be trying to say 'give me the characters between position 6 and position 12 (inclusive)', but you're really saying 'give me the characters between position 6 and position 18 (inclusive)'.
This is
y o u r n a m e h i s n
1 2 3 4 5 6 7 8 9 10 11 12 13
(For some reason I can't get my spaces and newlines to get preserved in this answer; but if you count the letters in 'yourname hisn' it should make sense :) )
This is why you could use Neophyte's code so long as you can presume what the string would be. To expand on Neophyte's answer, here's the code I would use (in the true branch of the conditional - you could also probably rename the variables based on this logic, etc.):
nameToSearch = rawName.substr(rawName.indexOf('#') + 1;
var nameFromNameToSearch = nameToSearch.substr(nameToSearch.indexof(' ') - 1;
nameFromNameToSearch would contain the string you're looking for. I haven't completely tested this code, but I hope it 'conceptually' gives you the answer you're looking for. Also, 'conceptually', it should work whether there are more than one '#' sign, etc.
P.S. In that first 'rawName.substr' I'm not giving a second parameter, which in Javascript et al. effectively says 'start at the first position and give me every character up to the end of the string'.

How can I "break up" numbers into smaller pieces in javascript?

I think the title needs some explaining. I wan't to make my program break up a number into smaller bits.
For example, it would break 756 into 700, 50 and 6. 9123 would be 9000, 100, 20 and 3. Is there any way I can do this for any reasonably sized number?
Working Example
Here is a function that can do it:
function breakNumbers(num){
var nums = num.toString().split('');
var len = nums.length;
var answer = nums.map(function(n, i) {
return n + (Array(len - i - 1).fill(0)).join('');
});
return answer.map(Number).filter(function(n) {return n !== 0;});
}
function breakup(number) {
var digits = String(number).split('')
return digits.map(function(digit, i) {
return Number(digit.concat("0".repeat(digits.length - i - 1)))
}).filter(function(n) { return n !== 0 })
}
So first, we want to cast the number to a string, so we pass it into the String primitive like so: String(number)
Thus, calling the split method on the array and passing in an empty string (which tells it to split for every character) results in an array of the digits, i.e. ["7", "5", "6"]
We can leave them as strings for now because it makes the next part a little easier. Using the map function, you can pass a function which should be called on each element in the array. Besides the first argument to this function, there's an optional second argument which is the index of the item in the array. This will turn useful in our case, since where a number is in the array indicates what place it is.
Check it out, the value returned by the function passed to map takes the current number string and concats another string onto it, which is a number of repeated "0"s. That number is determined by looking at the parent array's length and subtracting it from the index of the current item being looped on, minus one. This is because arrays are 0-indexed in JavaScript--if we just subtracted digits.length from the i (index) for the first iteration, the values would be 3 and 0 respectively, so you'd end up with 7000 for the first value if you passed in 756. Note also that in our return statement inside the map function, we wrap it back in a Number primitive to cast it back from a string.
Also, you didn't mention this, but I assume you'd rather not have numbers which equal 0 in your example. By calling filter on the final array before its returned, we can effectively make sure that only items which are not equal to 0 are returned. Thus, if you call breakup(756) you'll recieve [700, 50, 6], but breakup(706) will give you [700, 6] instead.
Instead of using split() to break out digits, I used a regex to tokenize the number string. This way, we can easily handle any trailing decimals by treating a digit followed by a decimal point and any further digits as a single token. This also makes it possible to handle digits as part of a larger string.
function splitNumber( number ) {
var parts = [];
var re = /(\d(?:\.\d*)?)/g;
while(next_part = re.exec(number)) {
// adjust place value
parts.forEach( function(element, index) {
parts[index] = 10 * element;
} );
parts.push( next_part[0] );
}
return parts.map(Number).filter(function(n) {return n !== 0});
}

jQuery Form, check first four numbers of variable

What I'm trying to achieve is a code checker. Only the first 4 numbers are important, the other numbers can be any number. The form will be used for users to put in productcodes.
The problem is that if the variable changes to say, 5 numbers the variable is false.
See below example:
http://jsfiddle.net/MZfxs/3/
If the user puts in the numbers 3541 the box changes color, but if the user put in the remaining numbers the value is set to false.
Additionally I'm trying to make the box only change color when 13 numbers are inserted AND the first 4 numbers are matching, in that order.
Solved!
Working Example:
http://jsfiddle.net/MZfxs/8/
If I understood correctly, you need a field value validation and the requirement is the value should start from 4 numbers like 7514 or 9268. Here you can use a regular expression to validate input value like:
// Will work for " 123433 " or "12345634 ", etc.
var value = $(this).val(),
re = /^\s*(\d{4})(\d+)\s*$/, // better to initialize only once somewhere in parent scope
matches = re.exec(value),
expectedCode = 3541,
expectedLength = 13;
if(!!matches) {
var code = matches[1]; // first group is exactly first 4 digits
// in matches[2] you'll find the rest numbers.
if(value.length == expectedLength && code == expectedCode) {
// Change the color...
}
}
Also if your requirement is strict to length of 13 than you can modify the regular epression to
var re = /^(\d{4})(\d{9})$/;
and retrieve first 4 numbers in first group and rest 9 in second group:
var matches = re.exec(value);
if(!!matches) {
var first4Digits = matches[1],
rest9Digits = matches[2];
// ...
// Also in this way you'll not need to check value.length to be 13.
}
You can break the string each time on key event fires. You can do this by calling js substring() method and take the first four characters and check it.
Try to use this:
<script>
$("input").keyup(function () {
var value = $(this).val();
$("p").text(value);
var value2 = $(this).val().substr(0,4);
if(value2 == 3541){
$(".square").css("background-color","#D6D6FF");
}else{
$(".square").css("background-color","yellow");
}
})
</script>

Categories