Why the script separates a whole multi-digits number to separated numbers? - javascript

I have a problem in this code.
When i run it, and after that i insert a two digits number, the script separates it. Ex.: enter 12 shows 1 even and 1 odd; enter 26 shows 2 even;
I want it to be mixed, so if i enter a two digits number or more (ex.432152) that needs to be 1 sum, 1 value, and show as 1 even number. Thank you for the opportunity to ask for help here!
function countfromzero() {
if (document.getElementById("maintextbox").value !="") {
CalculateNumbers();
}
}
function CalculateNumbers() {
var arr = [];
var asd = 0;
var evn = 0;
arr = document.getElementById("maintextbox").value;
arr = arr.replace(/, | /g, "");
for (i = 0; i < arr.length; i++) {
if (arr[i] % 2 != 0) {
asd++;
}
else {
evn++;
}
}
document.getElementById("eventextbox").value = evn;
document.getElementById("oddtextbox").value = asd;
}
<input type="text" name="maintextbox" id="maintextbox">
<input type="button" id="buttton" name="Process" value="Process" onclick="countfromzero();"><br>
Even:<input type="text" name="eventextbox" id="eventextbox"><br>
Odd:<input type="text" name="oddtextbox" id="oddtextbox">

Your arr variable is not an array as you apparently wanted it to be.
Change the replace method to a split method (with a slightly different RegEx) and you are done
function countfromzero() {
if (document.getElementById("maintextbox").value !="") {
CalculateNumbers();
}
}
function CalculateNumbers() {
var arr = [];
var asd = 0;
var evn = 0;
var str = document.getElementById("maintextbox").value;
arr = str.split(/[^\d]+/g);
for (i = 0; i < arr.length; i++) {
if (arr[i] % 2 != 0) {
asd++;
}
else {
evn++;
}
}
document.getElementById("eventextbox").value = evn;
document.getElementById("oddtextbox").value = asd;
}
<input type="text" name="maintextbox" id="maintextbox" value="432152">
<input type="button" id="buttton" name="Process" value="Process" onclick="countfromzero();"><br>
Even:<input type="text" name="eventextbox" id="eventextbox"><br>
Odd:<input type="text" name="oddtextbox" id="oddtextbox">

Consider HerrSerker's Answer since it's optimized to allow sequences of numbers, while mine doesn't
You treated your number as an array, and your for-loop iterated through each digit in your number to check if it's even or odd.
You just have to get rid of the loop, and change your "arr" to not be an array anymore.
function countfromzero() {
if (document.getElementById("maintextbox").value != "") {
CalculateNumbers();
}
}
function CalculateNumbers() {
var arr;
var asd = 0;
var evn = 0;
arr = document.getElementById("maintextbox").value;
arr = arr.replace(/, | /g, "");
if (arr % 2 != 0) {
asd++;
} else {
evn++;
}
document.getElementById("eventextbox").value = evn;
document.getElementById("oddtextbox").value = asd;
}
<input type="text" name="maintextbox" id="maintextbox">
<input type="button" id="buttton" name="Process" value="Process" onclick="countfromzero();"> Even:
<input type="text" name="eventextbox" id="eventextbox"> Odd:
<input type="text" name="oddtextbox" id="oddtextbox">

Related

How to display my pascal triangle array as a triangle or just by rows

I was tasked to create a Pascal Triangle by getting a user input as the number of rows and I managed to create an array of it but how do I display it on a line by line basis or a triangle. Also, how can I limit the number of rows the user can input? Thanks for the answers
var user_input = document.getElementById("user_input").value;
function pascal(numberOfRows) {
let pascalsTriangle = new Array(numberOfRows);
for (let i = 0; i < numberOfRows; i++) {
let line = new Array(i + 1);
line[0] = 1;
line[line.length - 1] = 1;
for (let n = 1; n < line.length - 1; n++) {
let previousLine = pascalsTriangle[i - 1];
line[n] = previousLine[n] + previousLine[n - 1]
}
pascalsTriangle[i] = line;
}
return pascalsTriangle
}
function myFunc() {
var input = document.getElementById("user_input").value;
document.getElementById("pascaltriangle").innerHTML = pascal(input)
}
<form>
<input id="user_input" type="number">
<input type="button" onclick="myFunc()" value="Submit">
</form>
<p id="pascaltriangle">Pascal's Triangle</p>
You're only meant to ask one question per question, but...
"Also, how can I limit the number of rows the user can input?"
Check the value before performing the pascal function, perhaps like this to limit it to less than 55:
function myFunc() {
let input = document.getElementById("user_input").value;
let n = parseInt(input);
if (!isNaN(n) && n > 0 && n <55) {
document.getElementById("pascaltriangle").innerHTML = pascal(n);
}
}
When you call pascal you can map that returned nested array to a string using map to deal with each line, join to turn the line to a space-separated string, repeat to pad it with non-breaking spaces, and join again to join those line-strings with <br> to one, multiline HTML string:
pascal(input).map((line, i) =>
" ".repeat(input - i) + line.join(" ")
).join("<br>")
Snippet:
var user_input = document.getElementById("user_input").value;
function pascal(numberOfRows) {
let pascalsTriangle = new Array(numberOfRows);
for(let i = 0; i<numberOfRows; i++) {
let line = new Array(i+1);
line[0] = 1;
line[line.length - 1] = 1;
for (let n = 1; n<line.length - 1; n++){
let previousLine = pascalsTriangle[i-1];
line[n] = previousLine[n] + previousLine[n-1]
}
pascalsTriangle[i] = line;
}
return pascalsTriangle
}
function myFunc() {
var input = document.getElementById("user_input").value;
document.getElementById("pascaltriangle").innerHTML =
pascal(input).map((line, i) =>
" ".repeat(input - i) + line.join(" ")
).join("<br>");
}
<form>
<input id="user_input" type="number">
<input type="button" onclick="myFunc()" value="Submit">
</form>
<p id="pascaltriangle">Pascal's Triangle</p>
This is a very basic implementation, and will not work for greater inputs, as then the number of digits for one number should stretch the pyramid horizontally to keep it balanced.
A way to make this happen is to use a HTML table element:
var user_input = document.getElementById("user_input").value;
function pascal(numberOfRows) {
let pascalsTriangle = new Array(numberOfRows);
for(let i = 0; i<numberOfRows; i++) {
let line = new Array(i+1);
line[0] = 1;
line[line.length - 1] = 1;
for (let n = 1; n<line.length - 1; n++){
let previousLine = pascalsTriangle[i-1];
line[n] = previousLine[n] + previousLine[n-1]
}
pascalsTriangle[i] = line;
}
return pascalsTriangle
}
function myFunc() {
let input = document.getElementById("user_input").value;
document.getElementById("pascaltriangle").innerHTML = "<table>" +
pascal(input).map((line, i) =>
`<tr><td colspan=${input - i}</td><td>${line.join("</td><td></td><td>")}</tr>`
).join("")
+ "</table>";
}
<form>
<input id="user_input" type="number">
<input type="button" onclick="myFunc()" value="Submit">
</form>
<p id="pascaltriangle">Pascal's Triangle</p>
As 2D Array you can use this function.
let numRows = 0,
triangle,
start,
stop;
function pascalRecursive(n, a) {
if (n < 2) return a;
let prevRow = a[a.length-1];
let curRow = [1];
for (let i = 1; i < prevRow.length; i++) {
curRow[i] = prevRow[i] + prevRow[i-1];
}
curRow.push(1);
a.push(curRow);
return pascalRecursive(n-1, a);
}
function myFunc(){
const numRows = document.getElementById('user_input').value;
let triangle = pascalRecursive(numRows, [[1]]);
for(var i = 0; i < triangle.length; i++) {
console.log(triangle[i]+"\n");
}
}
<form>
<input id="user_input" type="number">
<input type="button" onclick="myFunc()" value="Submit">
</form>
<p id="pascaltriangle">Pascal's Triangle</p>

Array push method is duplicating elements and the new Set method is not deleting duplicated elements

I am building a Prime Number multiplication table. I have written the code to get the Prime Numbers depending on the Range the User gives but when I push that prime number to an array. I get duplicates. I tried to get rid of the array using ES6 new set method before looping through them but I still get those duplicates.
const form = document.querySelector('.form');
let formParent = form.parentNode;
let primeNumberArray = [];
form.addEventListener('submit', (e) => {
e.preventDefault();
let startValue = parseInt(document.querySelector('.start').value);
let endValue = parseInt(document.querySelector('.end').value);
let table = document.createElement('table');
for (let i = startValue; i <= endValue; i++) {
let flag = 0;
// looping through 2 to user input number
for (let j = 2; j < i; j++) {
if (i % j == 0) {
flag = 1;
break;
}
}
// if number greater than 1 and not divisible by other numbers
if (i > 1 && flag == 0) {
primeNumberArray.push(i);
let uniqueArray = [...new Set(primeNumberArray)]
console.log(uniqueArray)
for (var k = 0; k < uniqueArray.length; k++) {
(function(k) {
table.innerHTML += `<tr>
<th>${uniqueArray[k]}</th>
</tr>`
}(k));
}
formParent.insertBefore(table, form.nextSibling)
}
}
})
<form class="form">
<fieldset>
<label>start</label>
<input type="number" class="start" />
</fieldset>
<fieldset>
<label>end</label>
<input type="number" class="end" />
</fieldset>
<input type="submit" value="run" />
</form>

How can I add 5 numbers on a empty array using 1 textbox?

I want to enter five numbers into the array using one text box. And find the max number print it when I click the result button. I want to enter a number one by one when I clicked the add button it automatically add one by one to the array. HTML with JavaScript
var input = document.getElementById('input').value;
function Add(numbers) {
numbers = [];
for(int x = 0; x < 5; x++) {
var numbers = input[x];
}
return numbers;
}
function findMax(arr) {
var max = arr[0];
for(var i = 0; i < arr.length; i ++) {
if(arr[i] > max) max = arr[i];
}
return max;
}
function Result() {
document.write(document.getElementById('demo').innerHTML = findMax(arr))
}
<p id = "demo">Print here the result</p>
<input type = "text"; id = "input">
<button onclick = "Add()">Add</button>
<button onclick = "Result()">Result</button>
To get all the 5 elements in an array using a single textbox, if they are seperated by single space do this:
var arr = input.split(' ');
This will create an array 'arr' with the numbers in it!
Actually there are many errors, that needs to be fixed, in the code you wrote:
You are declaring the numbersarray twice, inside your add function, while you should be declaring it only once globally outside of it.
You don't need a loop to add the input value into the array, just use .push().
You don't need to return the numbers array after adding an element.
Don't use document.write() to show the result, just use document.getElementById('demo').innerHTML = findMax(numbers).
Make sure to pass the right numbers array to your findMax()function, instead of arr in findMax(arr).
Demo:
This is a demo with these errors corrected.
var input = document.getElementById('input');
var numbers = [];
function Add() {
if (numbers.length < 5) {
numbers.push(+input.value);
input.value = "";
}
}
function findMax(arr) {
var max = arr[0];
for (var i = 1; i < arr.length; i++) {
if (arr[i] > max)
max = arr[i];
}
return max;
}
function Result() {
console.log(numbers);
document.getElementById('demo').innerHTML = findMax(numbers);
}
<p id="demo">Print here the result</p>
<input type="text" ; id="input">
<button onclick="Add()">Add</button>
<button onclick="Result()">Result</button>
You can try this code bellow :
<body>
<p id = "demo">Print here the result</p>
<input type = "text"; id = "input">
<button onclick = "Add()">Add</button>
<button onclick = "Result()">Result</button>
<script>
var numbers=[];
function Add() {
var input = document.getElementById('input').value;
if(input != ""){
numbers.push(parseFloat(input));
}
document.getElementById('input').value="";
console.log(numbers);
}
function Result() {
console.log(numbers);
document.getElementById('demo').innerHTML = Math.max.apply(null, numbers);;
}
</script>
</body>

Count the numbers in an array then write them out

It's still old school JS week for newbies at the academy.
I have created an input that makes it possible for a user to put some numbers in a input to write out an array.
Now what I'm trying to do next is writing out a paragraph with a counter for each number, like with how many times the number has been used.
If the array was [0,0,1,1,1,2,2,2,2];
And I want it to write it out something like this:
"How many times does your number appears in your array:"
0: 2
1: 3
2: 4
So far I got it to print out the numbers from the input, but I can't find a way to make it write out like above.
var numbers = [];
function numbarray() {
numbers.push(document.getElementById("box").value);
document.getElementById("text1").innerHTML = "";
document.getElementById("text1").innerHTML += numbers.join(", ");
}
<input type="text" id="box" placeholder="0-9 with comma" />
<input type="button" value="Click" onclick="numbarray()" />
<br>
Your array:<span id="text1"></span><br>
After tinkering, failing and googling since yesterday morning I've figure I try out SO again, since I've learned more from this site then I could ever imagine.
Thank you so much in advance
This solution features an object for counting the frequency of the numbers with a focus of occurrence.
function count() {
var numbers = document.getElementById("box").value
.split(',')
.map(Number)
.filter(isFinite),
distribution = numbers.reduce(function (r, a) {
r[a] = (r[a] || 0) + 1;
return r;
}, {});
document.getElementById("text1").innerHTML = numbers.join(", ");
document.getElementById("distribution").innerHTML = Object.keys(distribution)
.sort(function (a, b) {
return distribution[b] - distribution[a];
})
.map(function (k) {
return k + ': ' + distribution[k];
}).join('<br>');
}
<input type="text" id="box" placeholder="0-9 with comma" />
<input type="button" value="Click" onclick="count()" /><br>
Your array: <span id="text1"></span><br>
How many times does your number appears in your array:<br>
<div id="distribution"></div>
var numbers = [];
function numbarray() {
numbers = [];
numbers = numbers.concat(document.getElementById("box").value.split(','));
var hash = {};
for(var i=0; i<numbers.length; i++) {
if (typeof hash[numbers[i]] === 'undefined') hash[numbers[i]] = 0;
hash[numbers[i]] ++;
}
document.getElementById("text1").innerHTML = "";
for(var k in hash) {
document.getElementById("text1").innerHTML += k + ': ' + hash[k] + '\n';
}
}
<input type="text" id="box" placeholder="0-9 with comma" />
<input type="button" value="Click" onclick="numbarray()" />
<br>
Your array:<span id="text1"></span><br>
function numbarray() {
var nums = {}; // Use a dictionary for tallying numbers
var numStrings = document.getElementById("box").value.split(","); // Split by commas
// Just tally up each number
for (var i = 0; i < numStrings.length; i++){
var num = numStrings[i];
if (num in nums){
nums[num]++;
}
else {
nums[num] = 1;
}
}
var keys_ = Object.keys(nums); // Get the keys and sort them
keys_.sort();
document.getElementById("text1").innerHTML = "<br>"; // Reset the html
for (var key in keys_){
// Print out each number and its tally
document.getElementById("text1").innerHTML = key + ": " + nums[key] + "<br>";
}
}
Not sure if I totally understand what you are trying to do, but if you want to display the count of each number, you should first get the count of each number, then place them in your DOM, through a function such as:
var numbers = [];
var numbersObject = {};
function numbarray() {
numbers.push(document.getElementById("box").value);
//put numbers in object to get count of each
for(i=0; i<numbers.length; i++){
if(numbersObject[numbers[i]]){
numbersObject[numbers[i]]++
}else{
numbersObject[numbers[i]] = 1
}
}
//prepare HTML
var content = '';
for(var key in numbersObject){
content += key + ':' + numbersObject[key] + '<br>';
}
document.getElementById("text1").innerHTML = content
}

How do I count the number of occurrences of a character in a string using textboxes?

I want to count the number of times the single character, denoted by letter, occurs in str.
I have tried this code but I constantly receive back a value of just 1.
var x = document.getElementById('txt1').value;
var y = document.getElementById('txt2').value;
var letter = x;
var str = y;
for (var i = count = 0; i < str.length; count +++(letter === str[i++]));
count;
alert(i);
something like this? http://jsfiddle.net/swm53ran/96/
<input id="txt1" value="i"/>
<input id="txt2" value="This is my string"/>
<script type="text/javascript">
var x =document.getElementById('txt1').value;
var y = document.getElementById('txt2').value;
var letter = x;
var str = y;
var count = 0;
var arrayX = str.split('');
console.log(arrayX);
for (var i = 0; i < arrayX.length; i++) {
if (arrayX[i] == letter) {
count++;
}
}
alert(count);
</script>
The current problem is this part of your for loop: count +++(letter === str[i++]), let's walk through what happens:
If letter === str[i], add one (true) to count.
Add one to i.
Count is incremented.
Repeat unless i >= str.length.
As you can see, count is always incremented by at least 1, sometimes 2. i is also incremented in each repetition.
What you need is a for-loop that looks like:
for (var i = count = 0; i < str.length; count += (str[i++] == letter));
function getNumber(){
var str = document.getElementById('txt1').value;
var letter = document.getElementById('txt2').value;
var count;
for (var i = count = 0; i < str.length; count += (str[i++] == letter));
document.querySelector('p').innerText = count;
}
str: <input type="text" id="txt1"><br>
letter: <input type="text" id="txt2"><br>
<button onclick="getNumber()">Get Result</button><br>
result: <p></p>
Or full experience at this jsFiddle
Here ^^, count is only incremented if letter == str[i], so if that condition is false, count remains unchanged.
Or, perhaps less succinctly, you can use a regular expression (regex) to the same effect:
var regex = new RegExp(letter, 'g');
var count = (letter.length) ? str.match(regex).length : 0;
Here's a basic implementation using regex instead of splitting or writing a loop.
function go() {
var letter = document.getElementById('txt1').value;
var str = document.getElementById('txt2').value;
var re = new RegExp(letter,"g");
var count = (str.match(re || []).length);
alert(count);
}
<label for="txt1">Character</label>
<input type="text" id="txt1" maxlength="1" />
<br/>
<label for="txt2">String</label>
<input type="text" id="txt2" />
<input type="button" value="go" onclick="go()" />

Categories

Resources