simple algorithm with indexOf not working in JS - javascript

my mission is to find and output, where the tabs/word entered, is placed in the sentence.
the console gives me back that place var is not defined. What should I do? Thank you very much!
var sentence = prompt("Enter you sentence");
var word = prompt("Enter the tabs/word you looking for");
var counter = 0;
var place = stntence.indexOf(word, counter);
if (stntence.indexOf(word) != -1) {
while (place != -1) {
if (place != -1) {
console.log("The place of the word/tab is: " + place);
counter = place++;
} else {
console.log("That's all")
}
}
} else {
console.log("the word/tabs are not exist in the sentence");
}

Beside the typo of stntence !== sentence, you could take the advantage of the counter and use a shortened approach by assigning the place directly in the while condition.
var sentence = prompt("Enter you sentence"),
word = prompt("Enter the tabs/word you looking for"),
counter = 0,
place = -1;
while ((place = sentence.indexOf(word, place + 1)) != -1) {
console.log("The place of the word/tab is: " + place);
counter++;
}
if (counter) {
console.log("That's all");
} else {
console.log("the word/tabs are not exist in the sentence");
}

Related

Javascript adding to array using readline

I'm trying to repeatedly get 2 inputs and store them into an array until the word 'end' is typed. However, I'm getting undefined at the console.log(studentList[i]);
EDIT: With the help of you guys, I was able to store the values into the array. Right now what I want to do is to give a 'grade' to each of the marks that was entered. However no matter what number i entered, i was getting 'HD' for all the grades.
const readline = require('readline-sync');
var name, marks;
var studentList = [];
Input();
function printList(list) {
for (let i = 0; i < studentList.length; i += 1) {
var grade;
if ((marks <= 100) && (marks => 80)){
grade = 'HD'
studentList[i][2] = grade;
}
else if ((marks <= 79) && (marks => 70))
{
grade = 'D'
studentList[i][2] = grade;
}
else if ((marks <= 69) && (marks =>60))
{
grade = 'C'
studentList[i][2] = grade;
}
else if ((marks <= 59) && (marks =>51))
{
grade = 'P'
studentList[i][2] = grade;
}
else if ((marks < 50) && (marks =>0))
{
grade = 'N'
studentList[i][2] = grade;
}
console.log(studentList[i]);
}
}
function Input()
{
while(true) {
console.log("Please enter the student name (or \"end\" to end): ");
name = readline.question("Student Name: ");
if (name === 'end') {
printList(studentList)
break
}
console.log("Student Name is" , name);
marks = readline.question("Enter marks for " + name + ": ");
if (marks === 'end') {
printList(studentList)
break
}
console.log("Marks for " + name + " is " + marks );
studentList.push([name, marks]);
}
}
Any advice would be much appreciated! Thanks!
You mainly need to change .Length to .length and you have to use a while loop combined with a break (once 'end' is typed) that comes out of the while loop to give you the list you want to print. By changing the location of the if statements you are able to adjust when the break can occur and when it reads from users input.
const readline = require('readline-sync');
var name, marks;
var studentList = [];
Input();
function printList(list) {
for (let i = 0; i < list.length; i += 1) {
console.log('list[i]', list[i]);
}
}
function Input()
{
while(true) {
console.log("Please enter the student name (or \"end\" to end): ");
name = readline.question("Student Name: ");
if (name === 'end') {
printList(studentList)
break
}
console.log("Student Name is" , name);
marks = readline.question("Enter marks for " + name + ": ");
if (marks === 'end') {
printList(studentList)
break
}
console.log("Marks for " + name + " is " + marks );
studentList.push([name, marks]);
}
}
I don't think you know how many students there are ahead of time, so you will need to loop until "end" is detected.
This might help:
const readline = require('readline-sync');
var name, marks;
var studentList = [];
Input();
function Input() {
while (true) {
console.log("Please enter the student name (or \"end\" to end): ");
name = readline.question("Student Name: ");
if (name === 'end') break;
console.log("Student Name is", name);
marks = readline.question("Enter marks for " + name + ": ");
console.log("Marks for " + name + " is " + marks);
studentList.push([name, marks]);
}
}
for (var i = 0; i <= studentList.Length; i++) {
console.log(studentList[i]);
}

My javascript code is crashing when I put a random number generator/guesser into a function. Why does it crash?

I have build a random number generator used to guess numbers. I have limited this number guesser not to ask the same number twice and this works outside of the function. as soon as I put the number generator/guesser into a function the window crashes every few attempts. I believe this has to do with the number generating on an infinite loop. Can anyone see what the issue is?
Edit: for those who like to see the HTML as well. I have two simple inputs before the JS:
<body>
<p>Think of a number!</p>
<select name="fingers" id="mynumber">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<button id="startguess">Start guessing my number!</button>
Here are the global variables:
var guessed = [""];
var guess = "";
Here is the function:
function doaguess(correctanswer) {
guess = Math.floor(Math.random() * 6);
var n = "";
n = guessed.includes(guess);
if (n == true) {
guess = Math.floor(Math.random() * 6);
} else {
if (guess == correctanswer) {
return (true);
} else {
return (false);
}
}
}
And the rest of the script is this:
document.getElementById("startguess").onclick = function() {
var mynumber = document.getElementById("mynumber").value;
var gotit = false;
var numberofguesses = 1;
while (gotit == false) {
if (doaguess(mynumber) == true) {
gotit = true;
alert("Got it! It was a " + mynumber + ". It took me " + numberofguesses + " guesses.");
} else {
numberofguesses++;
guessed.push(guess);
}
}
}
Everything worked fine until I moved the generator into the function doaguess(). I have tried moving the variables into global from local to change the scope and this made the code work but it now crashes. Any help is appreciated.
Edit: for those who like to see the HTML as well. I have two simple inputs before the JS:
If you guess the number after (n == true) you are not returning anything, and the guess could be a repetead one, that should be into a loop also searching for a new guess. When you guess the number in that case, then the result is not true and the correct answer is added in the guessed array causing the infinite loop.
Fix:
n = guessed.includes(guess);
while (n == true) {
guess = Math.floor(Math.random() * 6);
n = guessed.includes(guess);
}
if (guess == correctanswer) {
return (true);
} else {
return (false);
}
Its this line guessed.push(guess); should be guessed.push(mynumber);
Here is it working:
var guessed = [""];
var guess = "";
function doaguess(correctanswer) {
guess = Math.floor(Math.random() * 6);
var n = guessed.includes(guess);
if (n === true) {
guess = Math.floor(Math.random() * 6);
} else {
return guess == correctanswer;
}
}
document.getElementById("startguess").onclick = function() {
var mynumber = document.getElementById("mynumber").value;
var gotit = false;
var numberofguesses = 1;
while (!gotit) {
if (doaguess(mynumber)) {
gotit = true;
alert("Got it! It was a " + mynumber + ". It took me " + numberofguesses + " guesses.");
} else {
numberofguesses++;
guessed.push(mynumber);
}
}
}
<button id="startguess">Guess</button>
<input id="mynumber" type="number"></input>
I have found the issue. The variables are not resetting every time I try to offer a number so it appears not to work if I try multiple times without reloading the page because the numbers are stored instead of resetting at each new "play". To resolve this I need to reset the variables and arrays guess and guessed every time the onclick is pressed. Like this:
document.getElementById("startguess").onclick = function() {
guessed = [""];
guess = "";
var mynumber = document.getElementById("mynumber").value;
var gotit = false;
var numberofguesses = 1;
while (gotit == false) {
if (doaguess(mynumber) == true) {
gotit = true;
alert("Got it! It was a " + mynumber + ". It took me " + numberofguesses + " guesses.");
} else {
numberofguesses++;
guessed.push(guess);
}
}
}

How to make sure user input is a valid string in js

I am very new to JS,
how do I make sure that the user input is a valid string?
If the string is inside of the array, the game should continue.
if the string is outside of the array, the game should ask user to input their guess again.
var color = ["AliceBlue","Black","FireBrick","GreenYellow","LightBlue","Ivory","MediumBlue","Indigo","SpringGreen","Moccasin"];
var target;
var guess_input_text;
var guess_input;
var finished = false;
var guesses = 0;
var rightAnswer;
var i = 0;
function do_game() {
var random_number = Math.random()* color.length;
var random_number_interger = Math.floor(random_number);
target = random_number_interger + 1;
rightAnswer = color[target];
while(!finished) {
guess_input_text = prompt("I am thinking of one of these colors:\n\n" + color.sort()+ "\n\n The right answer is\n" + rightAnswer);
guess_input = guess_input_text;
guesses +=1;
finished = check_guess();
}
}
function check_guess() {
if(guess_input < rightAnswer){
console.log("Hint: your color is alphabetically lower than mine")
return false;
}
else if( guess_input > rightAnswer) {
console.log("Hint: your color is alphabetically higher than mine ")
return false;
}
else (guess_input == rightAnswer)
{
console.log("Congrats!!!")
return true;
}
)
}
You can use indexOf to check the position of guess_input in the color array. It will return -1 if it is not present.
So:
function check_guess() {
if (color.indexOf(guess_input) < 0) {
console.log("Not a valid colour, try again.");
return false;
}
return true;
}
You can use Array.prototype.find function with ES6 arrow functions to make it even snappier.
if(color.findIndex(e => e === guess_input) === -1){
alert("Please guess again!);
}
The above code alerts the user to guess again if the guess_input isn't found in the array.

JavaScript - Make a variable change every second

Ok, so this is my code:
name: function(gameServer, split) {
// Validation checks
var id = parseInt(split[1]);
if (isNaN(id)) {
console.log("[Console] Please specify a valid player ID!");
return;
}
var name = split.slice(2, split.length).join(' ');
if (typeof name == 'undefined') {
console.log("[Console] Please type a valid name");
return;
}
var premium = "";
if (name.substr(0, 1) == "<") {
// Premium Skin
var n = name.indexOf(">");
if (n != -1) {
premium = '%' + name.substr(1, n - 1);
for (var i in gameServer.skinshortcut) {
if (!gameServer.skinshortcut[i] || !gameServer.skin[i]) {
continue;
}
if (name.substr(1, n - 1) == gameServer.skinshortcut[i]) {
premium = gameServer.skin[i];
break;
}
}
name = name.substr(n + 1);
}
} else if (name.substr(0, 1) == "[") {
// Premium Skin
var n = name.indexOf("]");
if (n != -1) {
premium = ':http://' + name.substr(1, n - 1);
name = name.substr(n + 1);
}
}
and i want to change premium to something like <kraken> and <spy> every second, so that then it changes gameServer.skinshortcut to %kraken and then 1 second later it changes that to %spy... and cycles, How do I do this?
Use setInterval(function, delay in ms)
Try:
Var pre_stat=0;
function tgl_pre()
if (pre_stat=0)
{
pre_stat=1;
//change variable to `kraken`;
}
else
{
pre_stat=0;
//change variable to 'spy';
}
setInterval("tgl_pre()", 1000);
end

How can I slice a block of text so that it doesn't end on a split word?

I've written code that takes a large block of text, splits it into 995 character blocks and pushes each block into an array. However, this often results splits words when they fall at the 995-character line- how could I edit my code so that each block of text is as close as possible to 995 characters long (must be under) but ends at the last available space?
function cutUp() {
var PAname = prompt("Determine PA type and PA Name (e.g. 5=mexican food=");
var chunks = [];
var OGstring = document.getElementById('PATypes').value;
var my_long_string = OGstring.split('1').join('').split('2').join('').split('3').join('').split('4').join('').split('5').join('').split('6').join('').split('7').join('').split('8').join('').split('9').join('').split('0').join('').split('[edit]').join('').split('[citation needed]').join('').split('[').join('').split(']').join('').split('(').join('').split(')').join('');
var i = 0;
var n = 0;
while (n < my_long_string.length) {
chunks.push(my_long_string.slice(n, n += 995));
}
if (chunks[0] != null) {
$('PAType=Name=Value8').innerHTML = PAname + chunks[0];
}
if (chunks[1] != null) {
$('PAType=Name=Value9').innerHTML = PAname + chunks[1];
}
if (chunks[2] != null) {
$('PAType=Name=Value10').innerHTML = PAname + chunks[2];
}
if (chunks[3] != null) {
$('PAType=Name=Value11').innerHTML = PAname + chunks[3];
}
if (chunks[4] != null) {
$('PAType=Name=Value12').innerHTML = PAname + chunks[4];
}
if (chunks[5] != null) {
$('PAType=Name=Value13').innerHTML = PAname + chunks[5];
}
if (chunks[6] != null) {
$('PAType=Name=Value14').innerHTML = PAname + chunks[6];
}
if (chunks[7] != null) {
$('PAType=Name=Value15').innerHTML = PAname + chunks[7];
}
if (chunks[8] != null) {
$('PAType=Name=Value16').innerHTML = PAname + chunks[8];
}
if (chunks[9] != null) {
$('PAType=Name=Value17').innerHTML = PAname + chunks[9];
}
////this is to create new exportable table
$('exportTable').innerHTML += $('tableContents').innerHTML;
$("exportTable").removeClass('hidden');
///this resets to default
defaultReset();
}​
Without any specific Javascript knowledge, I'd say to look ahead 995 characters, and if that character isn't itself a space, to start looking back towards the start until you find a space, and truncate there.
In C-like pseudocode, with chars being your big array of characters:
for(truncOffset = 995; truncOffset > 0; truncOffset--):
{
if chars[currentLoc + truncOffset] = ' ': /* a space character */ break;
}
Rinse, repeat to taste. Remember to move currentLoc to currentLoc + truncOffset after finding that space.

Categories

Resources