Count frequency of each letter - javascript - javascript

I'm utilizing JSBin to write a block of JS code to accept an input string, then return each letter included in the string (removing duplicate letters and other characters), then counting how many times each letter was utilized in the string. I am trying to integrate regex for additional practice.
The code I've written is not removing duplicates, nor is it properly counting the frequency of each character. Can somebody please tell me what I have done wrong?
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="text" id="input"></input>
<button onclick="count()">Count letters</button>
<br>
<br>
<div id="output">Result</div>
</body>
</html>
Here is the JS:
function count() {
var x = document.getElementById("input").value.toString();
var y = "";
var z = [];
//Removal of white spaces and other characters.
x = x.replace(/[^a-z]/gi,"");
//Elimination of duplicate letters.
for (var i = 0; i < x.length; i++) {
if (/x.charAt(i)/i.test(y) === false) {
y += x.charAt(i);
}
}
//Count how many of each letter exists within the input string.
for(var i = 0; i < y.length; i++) {
for (var j = 0; j < y.length; j++) {
var freq = 0;
if (y.charAt(i) == y.charAt(j)) {
freq += 1;
}
z.push(freq);
}
}
//Write result to HTML document.
for (var i = 0; i < y.length; i++) {
document.write(y.charAt(i));
document.write(", ");
document.write(z[i]);
document.write("<br>");
}
}
Thank you so much for your help!

You are thinking too complicated. Just iterate through normalized string, and count letters:
window.count = function() {
var input = document.getElementById("input").value.toString();
var result = {};
input = input.replace(/[^a-z]/gi,"");
var letters = input.split('');
for(index in letters) {
result[letters[index]] = result[letters[index]] +1 || 1;
}
document.querySelector('#output').innerHTML = JSON.stringify(result);
}
demo fiddle

You can do it in a single replace function. This is an example.
function getFreq(str){
var freq={};//an object to fill
/*var tmp = result not required*/ str.toLowerCase()
.replace(/[a-z]/ig, function(match /*that is [a-z]*/){
freq[match] = (freq[match] || 0) + 1;//fill object
return match;//do not change str
});
console.log(JSON.stringify(freq));
return freq;
}
<input type="text" onchange="getFreq(this.value);" />

Related

How to change display function based on select options chosen?

I have a problem with the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Q3</title>
<script type="text/javascript">
function showvar(x) {
let sum = 0;
let ssq=0;
let N = x.length;
for (let i = 0; i < x.length; i++) {
sum = sum + x[i];
ssq+=x[i]*x[i];
}
let variance=(ssq-sum*sum/N)/(N-1)
return variance;
}
function showsd(x) {
let sum = 0;
let ssq=0;
let N = x.length;
for (let i = 0; i < x.length; i++) {
sum = sum + x[i];
ssq+=x[i]*x[i];
}
let variance=(ssq-sum*sum/N)/(N-1)
let sd=Math.sqrt(variance)
return sd;
}
function display() {
let numbers = document.getElementById("numbers").value.split(" ");
for (let i = 0; i < numbers.length; i++) {
numbers[i] = parseFloat(numbers[i]);
}
let v = showvar(numbers);
let sd = showsd(numbers);
document.getElementById("display").innerHTML = "variance = " + v;
document.getElementById("display").innerHTML = "Standard deviation = " + sd;
}
</script>
</head>
<body>
<p>
<br><br>
</p>
<input type="text" id="numbers">
<select>
<option>Standard deviation</option>
<option>variance</option>
</select>
<button type="button" onclick="display()">Calculate</button>
<p id="display">answer goes here</p>
</body>
</html>
I need to make it so that the paragraph will display the correct value based on the option that is selected. So, for example, if I put in some numbers and choose variance, then it will show me the value for variance. I currently just have code for each different option, but I need to somehow put it together. Any help is greatly appreciated.
Update your display function to add an if condition:
function display() {
let numbers = document.getElementById("numbers").value.split(" ");
for (let i = 0; i < numbers.length; i++) {
numbers[i] = parseFloat(numbers[i]);
}
if(document.getElementById("options").value === "variance") {
document.getElementById("display").innerHTML = "variance = " + showvar(numbers);
} else {
document.getElementById("display").innerHTML = "Standard deviation = " + showsd(numbers);
}
}
Also add an id to the select tag:
<select id="options">
<option>Standard deviation</option>
<option>variance</option>
</select>

Getting blank screen after running Google web app script

I am working on a check-in app though Google Sheets and want to make a search function that that takes a sport name as input in an HTML form and then returns information about the sport from the sheet in a HTML table. However, when I try to test the web app, nothing happens. How can I fix this?
Here is my code:
Index.html
<!DOCTYPE html>
<html>
<head>
<?!= HtmlService.createHtmlOutputFromFile('Stylesheet').getContent(); ?>
</head>
<body>
<fieldset id="tasks-panel">
<legend>Sports</legend>
<form name="sport-form" id="sport-form">
<label for="sport-name">Search a sport by name:</label>
<input type="text" name="sport-name" id="sport-name" />
<button onclick='addTable()' id='submit-button'>Press this</button>
</form>
<p>List of things:</p>
<div id="toggle" style="display:none"></div>
</fieldset>
<?!= HtmlService.createHtmlOutputFromFile('Javascript').getContent(); ?>
</body>
</html>
Javascript.html
<script>
function addTable() {
var sportInput = $('sport-name').value();
var columnNames = ["Names", "Times"];
var dataArray = google.script.run.getSportData(sportInput);
var myTable = document.createElement('table');
$('#divResults').append(myTable);
var y = document.createElement('tr');
myTable.appendChild(y);
for(var i = 0; i < columnNames.length; i++) {
var th = document.createElement('th'),
columns = document.createTextNode(columnNames[i]);
th.appendChild(columns);
y.appendChild(th);
}
for(var i = 0 ; i < dataArray.length ; i++) {
var row= dataArray[i];
var y2 = document.createElement('tr');
for(var j = 0 ; j < row.length ; j++) {
myTable.appendChild(y2);
var th2 = document.createElement('td');
var date2 = document.createTextNode(row[j]);
th2.appendChild(date2);
y2.appendChild(th2);
}
}
}
</script>
Code.gs
//Setting up global variables
var ss = SpreadsheetApp.openById("-spreadsheetID-");
var sheet = ss.getSheetByName("Sheet1");
var sportsFromSheet = sheet.getRange("D4:D12");
var namesFromSheet = sheet.getRange("B4:B12").getValues();
var timesFromSheet = sheet.getRange("A4:A12").getValues();
var NAMES = [];
var TIMES = [];
var OUTPUT = [];
//doGet function
function doGet() {
return HtmlService.createTemplateFromFile('Index').evaluate()
.setTitle('Check In Data')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
//Gets both names and times of checked-in people
function getSportData(input) {
var sportInput = input;
getNamesInSport(sportInput);
getTimesInSport(sportInput);
OUTPUT = [
[NAMES],
[TIMES]
];
Logger.log(OUTPUT);
return OUTPUT;
}
//Puts the names of every person from an inputted sport into an array.
function getNamesInSport(input) {
var data = sportsFromSheet.getValues();
for (var i = 0; i < data.length; i++) {
if(data[i] == input){
NAMES.push(namesFromSheet[i][0]);
}
}
}
//Puts the times of every person from an inputted sport into an array.
function getTimesInSport(input){
var data = sportsFromSheet.getValues();
for (var i = 0; i < data.length; i ++) {
if(data[i] == input){
TIMES.push(timesFromSheet[i][0]);
}
}
}
JQuery id selectors must be prefixed with # so to grab the value from the the 'sport-name' input you'll need to select it using
var sportInput = $('#sport-name').val();
Additionally, as Robin comments above, if you want to use the JQuery library you'll need to load it, the code you've shown indicates you might not have done this?
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
Although if this were the case you'd probably be seeing a '$ is not defined' error straight away.

Save and return randomly generated strings in local storage

Okay so basically what I'm trying to do is to display all the randomly generated strings on the page, after being saved in sessionStorage. So far, my createRandom function works fine on its own, but when I added the returnRandom function both stopped working. I appreciate any suggestions.
Here is the javascript:
function createRandom()
{
var text = "";
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i = 0; i < 5; i++ )
text += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
document.getElementById("randomstring").innerHTML= text;
sessionStorage.setItem(text, text);
returnRandom();
}
document.getElementById("button").addEventListener("click", createRandom, false);
// //returns session storage values
function returnRandom() {
var key = "";
var i = 0;
for (var i = 0, i <= sessionStorage.length - 1, i++) {
key = sessionStorage.key(i);
var item = sessionStorage.getItem(key);
document.getElementById("randomreturn").innerHTML += item;
}
}
And here is the html:
<h2 id="randomstring">Random</h2>
<div id="button">
<p class="buttontext">Click Me</p>
</div>
<h3 id="randomreturn"></h3>
Your for loop expression should have semicolons, not commas
for (var i = 0; i <= sessionStorage.length - 1; i++)

Converting form text in HTML into an array in JS

I am attempting to create an online solver for the maximum subarray problem.
https://en.wikipedia.org/wiki/Maximum_subarray_problem
I planned on taking user-input numbers from a textbox and converting them into an int array in JS, however my JS does not seem to be running at all.
Here is my HTML
<!DOCTYPE html>
<html>
<head>
<title> findMaxSum </title>
<script src="findMaxSum.js" type="text/javascript"></script>
</head>
<body>
<h1> findMaxSum </h1>
<form id="formarray" action="">
<p> Enter numbers with spaces, i.e. "1 2 3 4 5": </p>
<input type="text" id="array"> <br>
<button id="sum">findMaxSum!</button>
<br>
</form>
<p id="answer">The answer is: </p>
</body>
</html>
and my JS. note: the map(function(item)) part of the code is intended to break apart the string from the form into an int array.
"use strict";
function findMaxSum() {
var array = document.getElementById("array").split(" ").map(function(item) {
return parseInt(item, 10);
});
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
var loopSum = 0;
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
loopSum += array[i];
if (currentMax < loopSum) {
currentMax = loopSum;
} else if (loopSum < 0) {
loopSum = 0;
}
}
document.getElementById("answer").innerHTML = "The answer is: " + currentMax;
}
window.onload = findMaxSum;
Currently, when I type in numbers into the textbox and submit, the numbers disappear and nothing happens. Any help is greatly appreciated.
Your array variable is object. You have to split the value of <input type="text" id="array"> not the object element.
var array = document.getElementById("array");
array = array.value.split(" ").map(function (item) {
return parseInt(item, 10);
});
Or simpler:
var array = document.getElementById("array").value.split(" ").map(function (item) {
return parseInt(item, 10);
});
Change your code -
function findMaxSum() {
var array = document.getElementById("array").value.split(" ").map(function(item) {
return parseInt(item, 10);
});
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
var loopSum = 0;
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
loopSum += array[i];
if (currentMax < loopSum) {
currentMax = loopSum;
} else if (loopSum < 0) {
loopSum = 0;
}
}
document.getElementById("answer").innerHTML = "The answer is: " + currentMax;
}
window.onload = findMaxSum;
Problem is you are using button inside form, which is by default of type submit type, that is the reason why the page goes blank, it gets submitted. So either you don't use form tag or make the button as button type.
<button id="sum" type='button'>findMaxSum!</button> <!-- type attribute added -->
Below is the sample updated code, hope it helps you.
"use strict";
function findMaxSum() {
var array = document.getElementById("array").value.split(/\s/);
var max = Math.max.apply(Math, array);
document.getElementById("answer").innerHTML = "The answer is: " + max;
}
window.onload = function() {
document.getElementById("sum").onclick = findMaxSum;
};
<h1> findMaxSum </h1>
<form id="formarray" action="">
<p>Enter numbers with spaces, i.e. "1 2 3 4 5":</p>
<input type="text" id="array">
<br>
<button id="sum" type='button'>findMaxSum!</button>
<br>
</form>
<p id="answer">The answer is:</p>
To achieve the solution of the problem, you need to make following changes.
Update the event binding place
window.onload = function() {
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
};
function findMaxSum() {
// remove the update binding code from here
// logic should come here
}
Resolve a JS error
document.getElementById("array").value.split(" ")
Update the html to avoid page refresh (add type)
<button id="sum" type='button'>findMaxSum!</button>
Update the logic to address the problem
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
var counter = i+1;
while (counter < array.length) {
var loopSum = array[i];
for (var j = (i+1); j <= counter; j++) {
loopSum += array[j];
if(loopSum > currentMax) {
currentMax = loopSum;
}
}
counter++;
}
}
Here is a plunker - http://plnkr.co/edit/AoPANUgKY5gbYYWUT1KJ?p=preview

A bit stuck with the "triangle" program in Javascript

I have a bit of an issue at the moment that I am hoping one of you can help me with. I have tried several things, and I just can't get it. I am trying to print a triangle of asterisks using JavaScript. The program is to ask the user for the amount of rows, and then the direction. I haven't even started with the direction yet because I can't get the rows to work. Odd thing is that I can get it to print out the triangle hard-coding the function call.
This is the JS file:
function myTriangle(){
var result = "";
var totalRows = document.getElementById('rows').value;
var direction = document.getElementById('UpOrDown').value;
for (var i = 1; i <= totalRows; i++){
document.writeln("count");
for (var j = 1; j <= 1; j++)
{
result += "*";
}
result += "<br/>";
}
return result;
}
var answer = myTriangle();
document.getElementById('myDiv').innerHTML = answer;
This is the HTML file:
<!DOCTYPE html>
<head>
<title>Lab 2</title>
<script src="scripts.js", "div.js"></script>
</head>
<body>
<form name="myForm">
<fieldset>
<legend>Input Fields</legend>
rows: <input type="text" id="rows" /><br>
direction: <input type="text" id="UpOrDown" /><br>
press: <input type="button" value="GO!" id="myButton"
onclick="myTriangle();"/>
</fieldset>
</form>
<div id="myDiv">
</div>
</body>
The output will be something like this:
*
**
***
****
*****
Generally there are four types of triangle -
1.)* 2.) *** 3.) * 4.) ***
** ** ** **
*** * *** *
Code for 1 -
var ast = [],
i, j = 4;
for (i = 0; i < j; i++) {
ast[i] = new Array(i + 2).join("*");
console.log(ast[i]);
}
Code for 2 -
var ast = [],
i, j = 4;
for (i = j-1; i >=0; i--) {
ast[i] = new Array(i + 2).join("*");
console.log(ast[i]);
}
Code for 3 -
var ast = [],
i, j = 4;
for (i = 0; i < j; i++) {
ast[i] = new Array(j - i).join(' ') + new Array(i + 2).join("*");
console.log(ast[i]);
}
Code for 4 -
var ast = [],
i, j = 4;
for (i = j-1; i >=0; i--) {
ast[i] = new Array(j - i).join(' ') + new Array(i + 2).join("*");
console.log(ast[i]);
}
To print asterisk in document rather than console -
document.getElementById('anyElement').innerHTML+=ast[i] + '<br />';
document.writeln will completely wipe the page unless it's called while the page is loading.
Therefore it will destroy myDiv, causing the getElementById to fail.
Furthermore, I'm not sure what you're trying to achieve with that <script> tag, but it looks like you need two of them.
EDIT: Oh, and this: for (var j = 1; j <= 1; j++) will only ever iterate once.
EDIT 2: Here's my implementation of a solution.
This isn't a valid script tag.
<script src="scripts.js", "div.js"></script>
You need to break it up into two tags:
<script src="scripts.js"></script>
<script src="div.js"></script>
This is my solution, it uses es2015 .replace() but there is a nice
polyfill for es5 as well here:
var output = document.getElementById('output');
function triangle (size) {
for (var i = 1; i <= size; i++) {
output.innerHTML += '*'.repeat(i) + '<br>';
}
}
triangle(2);
This is a solution in ES3/5
var output = document.getElementById('output');
function triangle(size) {
var allLines = '';
for (var i = 1; i <= size; i++) {
var oneLine = createLine(i);
allLines += oneLine;
}
return allLines;
}
function createLine(length) {
var aLine = '';
for (var j = 1; j <= length; j++) {
aLine += '*';
}
return aLine + "<br/>";
}
output.innerHTML += triangle(3);
<div id='output'></div>

Categories