Browser does not respond - javascript

I wrote this little piece of code to count the numbers of negative, zero, and positive elements in an array of number. When I run the code, the browser won't respond and I have to kill it! Any help will be appreciated. Thank you.
<script type = "text/javascript">
var promptArrayNum = prompt("Enter an array of numbers (Separated by comma): ");
var arrayNum1 = promptArrayNum.toString();
var arrayNum2 = [arrayNum1];
var arrayNum3 = counter(arrayNum2);
function counter(number){
var count;
var countNeg = 0;
var countPos = 0;
var countZero = 0;
for (var i = 0; i <= arrayNum2.length; i++)
{
switch (true){
case (arrayNum2[i] < 0): countNeg++;
document.write("Negative elements = " + countNeg);
break;
case (arrayNum2[i] = 0): countZero++;
document.write("Zero elements = " + countZero);
break;
case (arrayNum2[i] > 0): countPos++;
document.write("Positive elements = " + countPos);
break;
default: {document.write("Array is invalid");}
}
}
return count;
}

First off, it isn't array what you're operating on. Just split on the ,
var promptArrayNum = prompt("Enter an array of numbers (Separated by comma): ");
var arr = promptArrayNum.split(",");
Also, your code can be more efficient as in
var numOf0s = arr.filter(function(e){ return e == 0 }).length,
numberOfPositives = arr.filter(function(e){ return e > 0 }).length,
numberOfNegatives = arr.filter(function(e){ return e < 0 }).length;

Although your algorithm is not correct. The reason of infinite loop is line
case (arrayNum2[i] = 0): countZero++;
you have used assignment operator and you are looping through arrayNum2. its size is increasing in every loop.
instead it should be
case (arrayNum2[i] == 0): countZero++;

Here's a simplified working version of your code
use split to generate your input array
use if statements rather than switch
arrayNum2[i] = 0 is assignment, not equality comparison (use === (strict equality)
moved alerts outside the loop
http://jsfiddle.net/hk6uger4/2/
var input = prompt("Enter an array of numbers (Separated by comma): ");
var arr = input.split(',');
var count;
var countNeg = 0;
var countPos = 0;
var countZero = 0;
var i = 0;
for (i = 0; i <= arr.length; i++) {
if (arr[i] < 0) {
countNeg++;
}
if (arr[i] === 0) {
countZero++;
}
if (arr[i] > 0) {
countPos++;
}
}
alert("Negative elements = " + countNeg);
alert("Zero elements = " + countZero);
alert("Positive elements = " + countPos);

It works now! I took me more than 2 hours to figure it out. I'm a newbie to JS.
<script type = "text/javascript">
var promptArrayNum = prompt("Enter an array of numbers (Separated by comma): ");
var arrayNum = promptArrayNum.toString();
var arrayData = [arrayNum];
arrayData = arrayNum.split(",");
var arrayImplement = counter(arrayData);
function counter(number){
var count;
var countNeg = 0;
var countPos = 0;
var countZero = 0;
for (var i = 0; i < arrayData.length; i++){
switch (true){
case (arrayData[i] < 0): countNeg++;
break;
case (arrayData[i] == 0): countZero++;
break;
case (arrayData[i] > 0): countPos++;
break;
default: {document.write("Array is invalid");}
}
}
document.write("The array of numbers entered is: " + arrayData, "<br/>");
document.write("Negative elements = " + countNeg, "<br/>");
document.write("Zero elements = " + countZero, "<br/>");
document.write("Positive elements = " + countPos, "<br/>");
return count;
}

oh, weird code. Try this one:
var promptArrayNum = prompt("Enter an array of numbers (Separated by comma): ");
var data = promptArrayNum.split(",");
data = data.map(function(item){if(!item)return 0;else return parseInt(item.trim())});
for(var i = 0; i < data.length; i++){
var item = data[i];
if(item == 0){alert("item == 0")}
else if(item > 0) { alert("item > 0")}
else alert("item < 0")
}

Related

JavaScript Compression String

Defined a function that takes one argument (a string) and returns another string.
Input example: aabcc
Output example: a2bc2
function compressedString(message) {
if (message.length == 0) {
return;
}
var result = "";
var count = 0;
for (var n = 0; n < message.length; n++) {
count++;
if (message[n] != message[n+1]) {
result += message[n] + count;
count = 0;
}
}
return result;
}
console.log(compressedString('aabcc'));
Output I am getting: a1b1c1
Looked over the code but don't seem to find what's wrong.
Please change one line.
result += count > 1 ? message[n] + count : message[n];
If count is lower than 2, don't add count.
You can add a Conditional operator to only append the count if it is greater than 1.
result += message[n] + (count > 1 ? count : '');
Full code:
function compressedString(message) {
if (message.length == 0) {
return;
}
var result = '';
var count = 0;
for (var n = 0; n < message.length; n++) {
count++;
if (message[n] != message[n + 1]) {
result += message[n] + (count > 1 ? count : '');
count = 0;
}
}
return result;
}
console.log(compressedString('aabcc'));
Your function was actually returning: a2b1c2. If you want to return a2bc2 you just need an if to check if count is 1:
function compressedString(message) {
if (message.length == 0) {
return;
}
var result = "";
var count = 0;
for (var n = 0; n < message.length; n++) {
count++;
if (message[n] != message[n + 1]) {
if (count == 1)
result += message[n]
else {
result += message[n] + count;
}
count = 0;
}
}
return result;
}
Suppose you have arr1 = [a1,b2,c1];
and you want to convert it into [abbc]
Javascript accepts only numbers in for loop. So if you take the elements of this array individually, in the cast of characters it won't run except in the case of all the numbers it will run. But don't use +(element) operator. Since characters will throw a NaN.
So you can approach it so easily like this:
function check(string){
var new_string = "";
for(let i=0; i < string.length; i++){
let count = string[i];
for(var j=0; j< count; j++){
new_string = new_string + string[i];
}
}
console.log(new_string);
}
check("a2b3c2");
good luck

I am looking to create an Array from the Output of Counts conducted by my string

I am trying to make my below JS code, Develop and Array of
Count of each vowels
1) Count of A
2) Count of E
3) Count of I
4) Count of 0
5) Count of U
Upon reading a string the code, generates the number of times each vowel occurs.
But now I need to create an array that display, the Vowel occurring the most frequently
I know it is something to do with creating a variable for
var biggestSoFar etc... But how to piece it together I am having problems.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
function count_all() {
var str = document.getElementById('txtname').value;
var count9=0, totalvowels="";
var count2=0, totalconsonants="";
var count3=0, total_digits="";
var count4=0, totalA="";
var count5=0, totalE="";
var count6=0, totalI="";
var count7=0, totalO="";
var count8=0, totalU="";
for (var i = 0; i < str.length; i++) {
if (str.charAt(i).match(/[a-zA-Z]/) !== null) {
if (str.charAt(i).match(/[aeiouAEIOU]/))
{
totalvowels = totalvowels + str.charAt(i);
count9++;
}
if (str.charAt(i).match(/[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]/))
{
totalconsonants = totalconsonants + str.charAt(i);
count2++;
}
if (str.charAt(i).match(/[aA]/))
{
totalA = totalA + str.charAt(i);
count4++;
}
if (str.charAt(i).match(/[eE]/))
{
totalE = totalE + str.charAt(i);
count5++;
}
if (str.charAt(i).match(/[iI]/))
{
totalI = totalI + str.charAt(i);
count6++;
}
if (str.charAt(i).match(/[oO]/))
{
totalO = totalO + str.charAt(i);
count7++;
}
if (str.charAt(i).match(/[uU]/))
{
totalU = totalU + str.charAt(i);
count8++;
}
}
function retnum(str1) {
var num = str1.replace(/[^0-9]/g, '');
return num;
}
function count_digits(str2) {
var num2 = str2.replace(/[^0-9]/g,"").length;
return num2;
}
}
document.getElementById('TotalU').value = count8;
document.getElementById('TotalO').value = count7;
document.getElementById('TotalI').value = count6;
document.getElementById('TotalE').value = count5;
document.getElementById('TotalA').value = count4;
document.getElementById('consonant_counter').value = count2;
document.getElementById('total_consonants').value = totalconsonants;
document.getElementById('vowels').value = totalvowels;
document.getElementById('vocount').value = count9;
document.getElementById('digits1').value = count_digits(str);
document.getElementById('digits2').value = retnum(str);
}
function clear_all()
{
document.getElementById('TotalU').value = "";
document.getElementById('TotalO').value = "";
document.getElementById('TotalI').value = "";
document.getElementById('TotalE').value = "";
document.getElementById('TotalA').value = "";
document.getElementById('consonant_counts').value ="";
document.getElementById('total_consonants').value ="";
document.getElementById('vowels').value = "";
document.getElementById('vcount').value = "";
document.getElementById('digits1').value ="";
document.getElementById('digits2').value ="";
document.getElementById('txtname').value ="";
document.getElementById('txtname').focus();
}
Why not something like this? You supply the string and it will return an object with a count for each vowel?
function countVowels(str) {
var result = {};
result.a = 0;
result.e = 0;
result.i = 0;
result.o = 0;
result.u = 0;
for (var i = 0, len = str.length; i < len; i++) {
switch(str[i].toLowerCase()) {
case "a":
result.a = result.a + 1;
break;
case "e":
result.e = result.e + 1;
break;
case "i":
result.i = result.i + 1;
break;
case "o":
result.o = result.o + 1;
break;
case "u":
result.u = result.u + 1;
break;
default:
break;
}
}
return result;
}
When you get the result object back you can then do your checks to see which is the most occurring.
One other way of doing this could be like
var str = "When found, separator is removed from the string and the substrings are returned in an array. If separator is not found or is omitted, the array contains one element consisting of the entire string. If separator is an empty string, str is converted to an array of characters. If separator is a regular expression that contains capturing parentheses, then each time separator is matched, the results (including any undefined results) of the capturing parentheses are spliced into the output array. However, not all browsers support this capability.",
vowels = {"a":0,"e":0,"i":0,"o":0,"u":0},
ok = Object.keys(vowels);
maxvow = "";
for (var i = 0, len = str.length; i < len; i++ ){
var chr = str[i].toLowerCase();
chr in vowels && ++vowels[chr]; // or ok.includes(chr) && ++vowels[chr];
}
maxvow = ok.reduce((p,k) => vowels[k] > p[0] ? [vowels[k],k] : p,[0,""])[1];
console.log(vowels);
console.log(maxvow);
You could split the string and use an object for counting the vowels and other letters.
var count = { a: 0, e: 0, i: 0, o: 0, u: 0, other: 0 },
test = 'Es war einmal ein schwarzes Kaninchen';
test.toLowerCase().split(/(?=[a-z])/).forEach(function (c, i) {
if (c[0] in count) {
count[c[0]]++;
} else {
count.other++;
}
});
console.log(count);

hangman --can't get my loop to display correct answers

First day of school, we're supposed to make a hangman game. I've been staring at the logic in my while loop for hours now. I can't get my loop to say yes, the word(newWord) does contain the guess. I always get the prompt that it is incorrect, and then all heck breaks loose. I've tried 25 different ways. I know it's all busted beyond repair now, but if anyone can get me going the right direction, I'd be eternally grateful.
let words = ["skate", "guitar", "laugh", "party", "shirt"]
let wordValue = Math.floor(Math.random() * 4) + 1;
let newWord = words[wordValue];
let misses = 0;
let rightGuess = 0;
let wrongGuess = 0;
var answerLines = [];
for (let i = 0; i < newWord.length; i++) {
answerLines[i] = "_";
}
let remainingLetters = newWord.length;
while (remainingLetters > 0 && misses < 6) {
alert(answerLines.join(" "));
let guess = prompt("Guess a letter, any letter!");
for(let j = 0; j < newWord.length; j++) {
if (newWord[j] === guess) {
rightGuess++
}
else { wrongGuess++ }
if (rightGuess != 0) {
answerLines[j] = guess;
remainingLetters--;
}
else {
misses++
(alert("That was is incorrect. You have " + misses + " of 6 misses."));
Your logic for processing the guess is a little off. Try this:
var words = ["skate", "guitar", "laugh", "party", "shirt"]
var wordValue = Math.floor(Math.random() * 4) + 1;
var newWord = words[wordValue];
console.log("Word is: " + newWord);
var misses = 0;
var answerLines = [];
for (var i = 0; i < newWord.length; i++) {
answerLines[i] = "_";
}
var remainingLetters = newWord.length;
while (remainingLetters > 0 && misses < 6) {
alert(answerLines.join(" "));
var guess = prompt("Guess a letter, any letter!");
var matchesNone = true; //boolean to track if guess matched any letters
for (var j = 0; j < newWord.length; j++) {
if (newWord[j] === guess) {
answerLines[j] = guess;
remainingLetters--;
matchesNone = false; //the guess matched atleast one letter
}
}
if (matchesNone) { //the guess matched none of the letters
misses ++;
alert("That was is incorrect. You have " + misses + " of 6 misses.");
}
}
if(remainingLetters>0) {
alert("You failed to guess the word: " + newWord);
}else{
alert("You guessed the word! It was: " + newWord);
}

Longest substring in alphabetical order Javascript

Seeing all the people talking about longest substring in alphabetical order in Python, I have decided to try it in JS.
The function should look for the longest substring inside a given string, where letters are ordered alphabetically.
Here is what I have:
var s = 'azcbobobegghakl'
function substringChecker(s) {
var longestSub = "";
for (var i = 0; i < s.length; i++) {
var count = 0;
var currSub = "";
while((i+count)<=s.length){
var curr = i+count;
var next = curr+1;
var prev = curr-1;
if(curr !== s.length-1) {
if(s[curr] <= s[next]){
currSub += s[curr]
} else {
break;
}
} else {
if(s[curr]>s[prev]) {
currSub += s[curr];
}
}
count++;
}
if(currSub.length >= longestSub.length) {
longestSub = currSub;
}
};
return longestSub;
}
var result = substringChecker(s);;
console.log(result);
The funny thing it works great for all test cases I can come up with, but this one. The result should be "beggh" but it is "begg" instead. Why is the h not showing up, what am I missing?
The algorithm can be linear, I think you are overcomplicating it placing loops inside loops.
I would use something like
function substringChecker(s) {
var longestSub = "",
length = 0,
start = 0,
prev = s[0];
for (var i = 1; i <= s.length; ++i) {
if(i == s.length || s[i] < prev) {
if(length < i-start) {
longestSub = s.substring(start, i);
length = i-start;
}
start = i;
}
prev = s[i];
};
return longestSub;
}
document.write(substringChecker('azcbobobegghakl'));
first I made list of A-z
then check each letter and compare it with the next letter and save it in subString and...
function longest(str) {
//handle the case str is just one letter
if (str.length === 1) return str;
// create a list of alphabet A to Z
const alphabets = [...Array(26)].map(_ => String.fromCharCode(i++), (i = 97));
let longString = "";
let subSting = "";
for (let x = 0; x < str.length; x++) {
let char = str.charAt(x);
const nextChar = str.charAt(x + 1);
let charIndex = alphabets.findIndex(alphabet => alphabet === char);
let nextCharIndex = alphabets.findIndex(alphabet => alphabet === nextChar);
if (nextCharIndex >= charIndex) {
subSting = subSting + nextChar;
} else {
if (!subSting.length) {
subSting = subSting + char;
}
longString = subSting.length > longString.length ? subSting : longString;
subSting = "";
}
}
return longString;
}
console.log(longest("zyba"));

Loop to print iterations separated with a comma, with no comma at the end

I'm a student and am writing a JavaScript "for" loop that prints into innerHTML. Every concatenation of the string is added to the last followed by a comma. how do I make it so the comma is not printed after the last iteration? Just for piece of mind, the commas aren't part of the assignment, I'm just trying to add practical application. no jQuery tho please
window.onload = function(){
var mySeven = 0;
var printSeven = document.getElementById('multiples_seven');
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
mySeven += i;
printSeven.innerHTML += i + ',' + ' ';
}
}
};
Thanks!
You should use join() instead. It's much cleaner and you don't need to worry about edge cases:
var printSeven = document.getElementById('multiples_seven');
var sevens = [];
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
sevens.push(i);
}
}
printSeven.innerText = sevens.join(", ");
Or an approach that avoids the if() statement and unnecessary iterations:
var printSeven = document.getElementById('multiples_seven');
var sevens = [];
for (i = 7; i <= 1000; i += 7){
sevens.push(i);
}
printSeven.innerText = sevens.join(", ");
And for the sake of understanding, here's how you could do this without join():
var printSeven = document.getElementById('multiples_seven');
var maxValue = 1000;
var list = "";
for (i = 7; i <= maxValue; i += 7){
list += i;
if(i + 7 <= maxValue){
list += ", ";
}
}
printSeven.innerText = list;
Use this function:
function reorderData(){
var sevens = Array();
var printSeven = document.getElementById('multiples_seven');
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
sevens.push(i);
}
}
var newDisplaySelectedArray = sevens.join(",");
jQuery( "#multiples_seven" ).val(newDisplaySelectedArray);
}
First off it is better to not manipulate the DOM inside a loop. You should construct your output in a string or array then add it to the DOM in a single operation :
window.onload = function () {
var mySeven = '';
var printSeven = document.getElementById('multiples_seven');
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
mySeven += i + ', ';
}
}
printSeven.innerHTML += mySeven;
};
To delete the trailing comma you have two options : don't add it in the first place or remove it before adding it to the DOM.
Most other answers have concentrated on not adding it, here is a solution which removes it :
window.onload = function () {
var mySeven = '';
var printSeven = document.getElementById('multiples_seven');
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
mySeven += i + ', ';
}
}
printSeven.innerHTML += mySeven.slice (0, -2);
};
A word of caution, if your for loop does not execute at least one iteration you may remove characters you want to display. In the generic case it is easier to build an array and use the join function as shown in other answers here.
It's easier to check if you are at the first item than if you are at the last, so simply add the commas before the number:
window.onload = function(){
var mySeven = 0;
var printSeven = '';
for (i = 1; i <= 1000; i++) {
if (i % 7 == 0){
mySeven += i;
printSeven += (printSeven.length > 0 ? ', ' : '') + i;
}
}
document.getElementById('multiples_seven') += printSeven;
};

Categories