I am a beginner and I need help with this programming assignment.
Need to do a prompt. Get 10 names as input from user (string inputs). Put the names into an array and then write it out to the webpage.
My question is how do I save the input in the array, when the prompt has to be displayed over and over again for each name the user enters a name? Also, depending on how many names the user wants to enter, the user has a choice of quitting the prompt by typing in the letter 'q'. I am quite proficient at coding while and for loops, but not so much at coding arrays. Tried to search online but couldn't find an answer.
I would love if somebody could explain how to do it. Thanks!
I suggest the following solution:
// Create new array with 10 default values:
var result = new Array(10).fill('');
// Fill array with names via prompt():
eval(((a, b = ['x => x' + '.' + '\n' + 'so\x6De']) => b + '\x28' + a + '\x29')((a, b) => 'q' == (x[b] = prompt())))(result);
// Print result:
console.log(result);
How about something like this?
in your html somewhere
<div id="names">
</div>
function getNames(num) {
var arr = [],
person,
max = num || 5; // number of names you want
return (function R() {
if (arr.length < max) {
person = prompt("Please enter your name");
arr.push(person)
R()
} else {
document.getElementById("names").innerHTML =
"Hello " + arr.join(", ") + "! How are you today?";
}
}())
}
getNames(4)
Related
I would like to display a different madlib each time a user clicks the submit button. Only needs to be clicked 3 times. I am using the functions below, but it doesn't seem all that random. I also have a snippet of the dogLib function that creates three madlibs and then calls the function above it to generate a random madlib string.
//Class: madlibGenerator.js
//----- Private Helper Functions -----
//Get Random: word strings for randam madlib
//Get Random: madlib string to display
function getRandomString(array) {
for(var i = array.length - 1; i>0; i--){
var j = Math.floor(Math.random() * (i+1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return this.word = array.pop();
}
//Set: set user input word string arrays into the getRandomString(array)
//Get: a final array of words to add to the madLib display strings
function getFinalWordArray(){
var prpN = getRandomString(this.properNouns);
var adjt = getRandomString(this.adjectives);
var noun = getRandomString(this.nouns);
var vrb = getRandomString(this.verbs);
return finalWordArray = [prpN, adjt, noun, vrb];
}
//Get Random Dog Lib
function getDogLib() {
//Get Random Dog Words
var dogWordsArray = getFinalWordArray();
//DogLibs
var dogLibOne =
"What is that " + dogWordsArray[1] +
" sound!" +
" Hey! " + dogWordsArray[0] +
"! You come " + dogWordsArray[3] +
" you crazy " + dogWordsArray[2] +
"!";
var dogLibTwo =
dogWordsArray[0] + "!! " +
dogWordsArray[0] + "!! " +
"Come " + dogWordsArray[3] +
" and lay on my clean " + dogWordsArray[2] +
" while your treat is still " + dogWordsArray[1] + "!";
var dogLibThree =
"My human comes home and takes me for a " + dogWordsArray[3] +
" where I sit on a " + dogWordsArray[2] +
" and get my " + dogWordsArray[1] +
" belly rubbed!";
//Make array of DogLibs
var dogLibArray = [dogLibOne, dogLibTwo, dogLibThree];
//Pick random dogLib string to display
finalDogLib = getRandomString(dogLibArray);
}
//Display: Random MadLib to console for now
function displayMadlib(pDisplayIDValue) {
if(pDisplayIDValue == "dogLib"){
//display
getDogLib();
console.log(finalDogLib);
}else if(pDisplayIDValue == "loveLib"){
//display
getLoveLib();
console.log(finalLoveLib);
}else if(pDisplayIDValue == "funnyLib"){
//display
getFunnyLib();
console.log(finalFunnyLib);
}
}
The code above isn't broken, it just doesn't produce a true random.
//Preferred Result: the program displays a different madlib each time the user clicks the submit button. The user only needs to click the button 3 times to get different madlibs, the fourth click clears the form and starts the program fresh.
Thank you!
I am open to any idea to make this a truly random madlibGenerator. Maybe counting number of clicks from a submit button?
So true randomness is going to be tough to achieve. Math.Random() from the javascript library isn't truly random as you've guessed, it's pseudo-random, meaning there is a pattern to it over a large number of inputs. Computers inherently can't really do true randomness, because they are always going to have to take some number, perform some sort of algorithm on it (these are usually "Mersenne Twisters" - fun wikipedia read), and spit out the result.
That said, I don't know exactly how to improve on what you've put into place here. With PRNG, a really large number of possible inputs can help a lot. If you want absolutely true randomness, the easiest way would probably be to hook into random.org's API (https://api.random.org/dashboard - developer license is free, limited to 1000 requests per day). Hooking into an API might be more work than you were planning on, but random.org uses (if I remember right) atmospheric noise and barometric pressure from the Earth to create their random numbers, so it's about as close to true randomness as you can possibly get.
I hope this helps!
I have been implementing a simple quiz for English. In that, we need to validate answers, which are entered by users in input field. In the current implementation, I am comparing the correct answer with user's answer exactly. Like,
HTML
<input type="text" id="answer" />
<button onclick="validate()">Validate</button>
Javascript
var question = "Do you like movies?",
answer = "No, I don't like movies.";
function validate() {
var userInput = document.getElementById('answer').value;
if(answer == userInput) {
console.log("correct");
} else {
console.log("wrong");
}
}
But I don't want validate exactly. Like, ignore case sensitive, commas, apostrophe, etc. For example if user enters,
i dont like movies
The answer can be correct. I don't know how start and where to start. Anyone please help.
One option would be to strip out all non-word characters and spaces, and compare the lower-case version of each replaced string:
var question = "Do you like movies?",
answer = "No, I don't like movies.";
const normalize = str => str
.replace(/[^\w ]/g, '')
.toLowerCase();
function validate(userInput) {
const noramlizedInput = normalize(userInput)
const noramlizedAnswer = normalize(answer);
if (noramlizedInput == noramlizedAnswer) {
console.log("correct");
} else {
console.log("wrong");
}
}
validate('No i dont like movies');
validate("NO!!!!! I DON''t like movies.");
Another option would be to loop through all possible substrings of the userInput and figure out which has the most overlap with the desired answer, but that's a whole lot more complicated.
An easier option would be to check to see how many overlapping words there are:
var question = "Do you like movies?",
answer = "No, I don't like movies.";
const normalize = str => str
.replace(/[^\w ]/g, '')
.toLowerCase()
.split(/\s+/)
function validate(userInput) {
const noramlizedInputArr = normalize(userInput);
const noramlizedAnswerArr = normalize(answer);
const overlapCount = noramlizedInputArr.reduce((a, word) => (
a + Number(noramlizedAnswerArr.includes(word))
), 0);
console.log(overlapCount);
if (overlapCount >= 4) {
console.log("correct");
} else {
console.log("wrong");
}
}
validate('No i dont like movies');
validate("NO!!!!! I DON''t like movies.");
validate("i dont like movies.");
validate("Yes I like movies.");
If you are interested in simply catching spelling errors and small variations, a standard metric is called edit distance or Levenshtein distance. This is a count of the minimum number of deletions, insertions, or substitutions you need to change one text into another. Strings like "No I don't like the movies" and "No I don't like the moveys" will have small edit distances.
Here's a quick and dirty recursive edit distance function that will give you an idea:
function validate(text, pattern) {
// some simple preprocessing
let p = pattern.toLowerCase().replace(/[^a-z]+/ig, '')
let t= text.toLowerCase().replace(/[^a-z]+/ig, '')
// memoize recursive algorithm
let matrix = Array.from({length: t.length + 1}, () => [])
function editDistance(text, pattern, i = 0, j = 0){
if(i == text.length && j == pattern.length) return 0
if(i == text.length) return pattern.length - j
if(j == pattern.length) return text.length - i
let choices = [
(matrix[i+1][j+1] || (matrix[i+1][j+1] = editDistance(text, pattern, i+1, j+1))) + (text[i].toLowerCase() === pattern[j].toLowerCase() ? 0 : 1),
(matrix[i+1][j] || (matrix[i+1][j] = editDistance(text, pattern, i+1, j))) + 1,
(matrix[i][j+1] || (matrix[i][j+1] = editDistance(text, pattern, i, j+1))) + 1
]
return Math.min(...choices)
}
return editDistance(t, p)
}
// similar strings have smaller edit distances
console.log(validate("No I dont lik moves","No i dont like movies"))
// a little less similar
console.log(validate("Yes I like movies","No i dont like movies"))
// totally different
console.log(validate("Where is the bathroom","No i dont like movies"))
// careful -- small edit distance !== close meaning
console.log(validate("I do like tacos","I don't like tacos"))
Picking a minimum acceptable distance works pretty well for matching strings with small typos. Of course, if you are trying to gauge user intent, none of these simple hues tics will work. Strings like "I love tacos" and "I loath tacos" have a small edit distance and you can't tell that they mean the opposite without knowledge of the language. If you need to do this level of checking you can try using a service like Watson Conversation that will return user intents to input.
First off my apologies if I did something incorrectly with asking a question, I'm very new to stackoverflow and javascript as well. I am having an issue with passing a property through my getPassword function and I've searched around and couldn't truly pinpoint an answer. The code I created is designed for an object called "student" with two properties; FirstName and LastName.
Using a couple of dialogue boxes the information related to each student is entered. At the end, a prompt should display and asks the user "Do you want to add more student?" If the answer is "Yes", It asks the next student's information. If the answer is anything else, It stops asking. Then the information is displayed on the webpage. I want to have a property called "UID" The format of UID is FirstName_PSWD. For calculating the "PSWD" the function called "generatePassword" is used. This function randomly creates a 6-digit password including characters and numbers. For example: if username is John, then UID may be "John_X12bn231". I can not seem to get this password function to work, what might I be doing wrong? I am also aware that there might be other errors in my code, which I do apologize for i am very much a beginner.
var student={FirstName:"", LastName:""};
var studentlist=[];
var i=0;
function generatePassword() {
var length = 4,
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
retVal += charset.charAt(Math.floor(Math.random() * n));
}
return retVal;
}
function Register() {
var next="Yes";
while (next="Yes"){
student.FirstName=prompt("Please enter the name");
student.LastName=prompt("Please enter the last name");
studentlist.push(student);
document.getElementById("demo").innerHTML += "<li> <b>First Name:</b> "+ studentlist[i].FirstName + "," +
"<b>Last Name: </b>"+ studentlist[i].LastName + "," + "</li>";
next = prompt ("Do you want to add more data?", "Yes")
i++;
}
}
Two mistakes:
var student={FirstName:""; LastName:""};
Should be -> var student={FirstName:"", LastName:""};
var i==0; -> var i = 0;
Try after changes and tell me if it works ;d
Btw. Javascript is a frontend. Your users will be able to check how you generate the password, because all your code can be read.
the past two days I've been really struggling on finishing this assignment.
The assignment goal is to create a javascript that takes in Student information until the user either hits cancel or enters in blank text.
the information gets validated every time the user enters information if it is valid, it is then saved to a Student Object Array.
Here is my code:
var Student =[];
// Validates Student Courses, loops through making sure they are equal to courseList values.
function validateCourses(courses){
var valid='';
var courseList = ['APC100','IPC144','ULI101','IOS110','EAC150','IBC233','OOP244','DBS201','INT222'];
alert(courses);
for(var i =0;i<courseList.length;i++){
var a = courses;
a.splice();
if(a[i]!==courseList[i]){
valid=false;
}
else{
valid=true;
}
}
return valid;
}
function formatingName(name){
var res ='',cap='';
res = res + name.charAt(0).toUpperCase();
cap = res + name.substr(1);
return cap;
}
// I'm having issues with this validation for the student id. the student id can only be xxx.xxx.xxx
function validateStudentID(sid){
var validate=0;
var patt1 = /^\(?([0-9]{3})\)?([.]?)([0-9]{3})?([.]?)([0-9]{2})$/;
var result = patt1.test(sid);
return result;
}
var courseSelect=[];
var tag=0;
// this displays what users are in what course depending on what the user enters
function code(coursecode){
for(var w = 0;w<count;w++){
for(var t = 0;t<Student[w].courses.length;t++){
var a = Student[w].courses;
a.splice();
if(a[t] == coursecode){
tag=1;
}
}
if(tag){
courseSelect.push(Student[w].fname + " " + Student[w].lname + " " + Student[w].id + " " + Student[w].email);
}
}
alert('List students registered in ' + coursecode + ' :\n\n' + courseSelect.join('\n'));
}
// main functions and validation calls
var userInput = "";
var i=0,count=0,j=4,flag=false;
var result='',courses=[];
var Student,validCourses;
do{
userInput = prompt("Please enter first name, last name,student ID,\n" +
"email and courses (speareted by ',').");
if(userInput != null && userInput !=''){
result = userInput.split(',');
for(var i=4;i<result.length && i < 10;i++){
courses.push(result[i].toUpperCase());
}
// VALIDATION OF STUDENT ID AND STUDENT COURSES */
while(!flag){
var valid = validateStudentID(result[2]);
alert(valid);
if(valid){
id = result[2];
flag=true;
}
else {
alert(Student.id + " is not valid Student ID!" + "\n" + "Please try again.");
flag=false;
}
validCourse = validateCourses(courses);
if(validCourse){
flag=true;
}
else {
alert( validCourse + " is not the course provided by the CPD program! \n Please try again");
flag=false;
}
}
if(flag){
Student.push({
fname:formatingName(result[0]),
lname:formatingName(result[1]),
id:result[2],
email:result[3].toLowerCase(),
courses:courses,
});
count++;
i++;
}
else {
Student = [];
}
}
}while(userInput != null && userInput !='');
alert('There are total '+ count + ' students registered');
var coursecode = prompt("Please enter course code: ");
code(coursecode);
Some of the most obvious problems in your code are:
You have a while(!flag) loop after the input section. That loop contains no other request to input anything. Therefore it will run endlessly if your validate* methods return false.
Your regular expression /^\(?([0-9]{3})\)?([.]?)([0-9]{3})?([.]?)([0-9]{2})$/ isn't doing what you want it to do. You can simplify it to just /^[0-9]{3}\.[0-9]{3}\.[0-9]{3}$/ as all you want to know is whether your input parameter sid contains three number blocks, each of length 3. You don't need any braces for that and escaping them via \(? would anyways be wrong. You also didn't escape your points via \., which is wrong as they would match basically any character. You should read up more about regular expressions.
Your loop in validateCourses looks wrong. Why do you assign courses to a new variable (it isn't copied to a) and then call splice()? Your following if condition is also wrong, as it assumes that a and courseList have equal length and that the positions of the courses would match. That's certainly not what you want. You should check for each course in course whether it is contained in courseList, e.g.: var notInCourseList = courses.filter(function(course) { return (courseList.indexOf(course) == -1); }); and then return (notInCourseList.length == 0);. A forEach loop would be an easy alternative. You should read some tutorials about that.
Similarly, I don't see any good reason for var a = Student[w].courses; a.splice(); in code(). Just check directly on Student[w].courses.
Slightly more working jsfiddle here.
The goal is to filter some "test" or "flood" messages in a shout box chat.
ex: when an user writes something like
aaaaaaaaaaaaaaaaaaaaa or jdhshjdskhdshuishifhduif or dsqjlkdsqjiodsqjiosqjdsjq
I want to filter such stupid words: I guess I need to write some functions like:
if string length>20 or string conatins more that 4 vowels in a row or contains 4 consonants in a row
or contains some special chars...
Maybe this function has aleardy been written to avoid reinventing the wheel.
regards
Well using some Regular Expressions could do the trick.
EDIT
I have updated the code after Chris's suggestion.
So the credit goes to him.
String.prototype.testVowels = function () {
return !(/([aeiou]){4,}\w*/g.test(this));
}
String.prototype.testConsonants = function () {
return !(/([bcdfghjklmnpqrstwxyz]){4,}\w*/g.test(this));
}
String.prototype.testLength = function() {
return this.length < 20;
}
function testString(str) {
var stringArr = str.split(" ");
// this will test for each word in the str parameter
stringArr.forEach(function(s) {
if(s.testConsonants() && s.testLength() && s.testVowels()) {
console.log("The word " + s + " is ok !");
}
});
}