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
Related
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>
i have a textbox1 which input by user and textbox2 for user to input numbers which can automatically generate textbox1 value into multiple string such as example below:
Txtbox1 = ABC12345
Txtbox2 = 3
Result will be
ABC12345-1
ABC12345-2
ABC12345-3
You can try using something like this below, but kinda hard to make it 100% as you want, since you haven't shown any HTML.
$("[id^=Txbox]").keyup(function() {
var empty = $("[id^=Txbox]").filter(function() {
return $.trim($(this).val()).length == 0
}).length == 0;
if (empty) {
var str = $("#Txbox1").val();
var number = $("#Txbox2").val();
var arr = [];
for (i = 0; i < number; i++) {
arr.push(str + "-" + i)
}
console.log(arr)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="Txbox1" />
<input id="Txbox2" type="number" />
You can just use button and apply click event.
function getString() {
var finalString = [];
var t = $("#textbox1").val()
var n = $("#textbox2").val();
if (t.toString().trim() != "") {
for (i = 0; i < n; i++) {
finalString.push(t + "-" + (i + 1))
}
}
console.log(finalString)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Text : <input type="text" id="textbox1"><br><br> Number : <input type="text" id="textbox2">
<button type="button" onClick="getString()" id="textbox1">Get</button>
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);" />
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++)
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>