How can i do a simple switch of characters from using indexes - javascript

Greetings I am trying to do a simple swap by comparing 2 numbers from a string and the switching the higher number to the left. I am using a while loop to make the changes but i get a TypeError: input is not a function chartest.html:32:4
I do not see what i am doing wrong can anyone look at my code. Here is a look at my code.
<body>
<form>
Enter numbers to be sorted from into high to low
<input id="num" type="text" value="" >
<br>output<input id="forTest" type="text">
<br><button type="button" onclick="calc(); return false" >Enter</button>
<input type="reset">
</form>
<p id="what"></p>
<script>
function calc()
{
var input = document.getElementById("num").value;
var wordlength = input.length;
var i = 0;
while(i < wordlength -1)
{
a = input.charAt(i);
b = input.charAt(i+1);
if(a < b)
{
input(i) = b;
input(i+1) =a;
}
i++;
}
alert(input);
//document.getElementById("forTest").value = testString;
//document.getElementById("what").innerHTML = testString;
}
</script>
</body>

Functional programming is your friend :)
var input = document.getElementById("num").value;
var arrayOfChars=input.split(""); //Or split by comma or whatever
var sortedArrayOfChars=arrayOfChars.sort(sortingFunction);
function sortingFunction(a,b){return a-b;}
Or, as a 1 liner...
input.split("").sort(function(a,b){return a-b;})

Related

simple javascript string calculator

I am trying to build a simple javascript calculator that will ask user to input name and it will display a number according to input, each letter in string will have a value like a=1 and b=2. If we insert acb in input it should display abc=1+2+3 =6.
thanks
<input type="text" id="myText" value="">
<button onclick="myFunction()">Try it</button>
<p id="calc"></p>
<script>
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("calc").innerHTML = x;
}
</script>
Try this, it uses a simple a=1 to z=26 code. If a special character or number is entered, they are treated as 0. This does work for uppercase and lowercase letters.
function myFunction() {
var x = document.getElementById("myText").value;
var total = 0;
for (var i = 0; i < x.length; i++) {
var temp = x.toLowerCase().charCodeAt(i) - 96;
if ((temp > 0) & (temp < 27)) {
total = total + temp;
}
}
document.getElementById("calc").innerHTML = total;
}
<input type="text" id="myText" value="">
<button onclick="myFunction()">Try it</button>
<p id="calc"></p>

How to generate column numbers and display them on html using JavaScript

I'm a newbie in JavaScript. I want to generate some numbers and display the whole on html element.
Bellow is the code I wrote. I'm only getting a single number generated on html but I'm getting what I want on the console.
var b;
function gen(){
for (var i = 0; i < 10; i++){
b = Math.random().toString();
console.log(b);
document.getElementById('output').innerHTML = b;
};
}
<h1>Generate Phone numbers</h1>
<p>
<input type="button" value="Generate" class="btn" onclick="gen()">
<p>
<span id="output"></span>
Please how do I get what is exactly on the console to html when I click generate button?
Thanks you
You can use insertAdjacentHTML method:
var b;
function gen(){
for (var i = 0; i < 10; i++){
b = Math.random().toString();
document.getElementById('output').insertAdjacentHTML('beforeend', b);
};
}
<h1>Generate Phone numbers</h1>
<p>
<input type="button" value="Generate" class="btn" onclick="gen()">
<p>
<span id="output"></span>
Add a temporary variable to the outside of the loop. Then assign that value to the innerHTML of your span tag.
var phoneNumber = "";
for (var i = 0; i < 10; i++){
b = Math.random().toString();
console.log(b);
phoneNumber += b;
};
document.getElementById("output").value = phoneNumber;

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()" />

Prompting the user for 10 inputs, sotring it in an array, finding the average, and printing numbers less than average

The title is the question in mind.
Here is what I have so far:
html>
<head>
<title> New Document </title>
</head>
<script type = "text/javascript">
var i;
var elmt = nums[10];
var ask = prompt("Please enter 10 numbers");
var sum = 0
for(var i =0, i< elmt.length; i++;):
sum += parseInt(elmt[i], 10);
var avg = sum/elmt.length;
document.write("The sum of all the elements is: " + sum + " The average is: " +avg);
<body>
</body>
</html>
I'm not really sure what I'm doing to be honest. I tried researching arrays and this questions and similar ones so I can try to learn the syntax but to no avail. I'm practicing this on my own to try and learn. Please don't bash, I'm not asking anyone to do this FOR me, hints would be ok. I'm not some teenager endlessly dumping in code and hoping the internet does my homework.
EDIT1:
<html>
<head>
<title> nums </title>
</head>
<script type = "text/javascript">
var sum =0;
var belowAvg = 0;
var num = new Array(10);
var sum = 0
var i;
for(i = 0; i<10; i++;):
{
num[i] = eval(prompt("Enter a number"));
sum = sum + num[i];
}
avg = sum/10;
for (i=0; i<10; i++)
{
if ( num[i] < avg)
{
belowAvg++;
}
}
alert ("average is" + avg);
alert (belowAvg + "numbers are less than the average");
</script>
<body>
</body>
</html>
EDIT2:
Ok, now I'm extremely lost. Everyone had good answers and all but my understanding isn't enough to apply any of them unfortunately. I've been playing around with all suggestions and I'm still lost. Can anyone show me an example maybe? I didn't want my hand to be held, but....
You're almost there, but you're only prompting once and placing the input in to a variable. You need to prompt 10 times if you want 10 numbers (otherwise you need to parse the input and extract 10 numbers from it).
Assuming you wanted a few methods of populating elmt through ask (here i use input instead of ask and nums instead of elmt--but we're talking minor semantics):
Method one, prompt 10 times:
// initialize array with 10 elements
var nums = new Array(10);
// iterate over each element and prompt for value
for (var i = 0; i < nums.length; i++){
var input = prompt('Enter number ' + (i + 1) + ' of ' + (nums.length + 1));
// place value (as a number) into the array
nums[i] = new Number(input);
}
/* sum/average code */
Method two, prompt once and String.prototype.split:
// initialize array with 10 elements
var nums = new Array(10);
// prompt for 10 numbers
var input = prompt('Enter ' + (nums.length + 1) + ' numbers separated by commas:');
var values = input.split(',');
// check we have the right amount
if (values.length == nums.length){
// iterate over the values
for (var i = 0; i < nums.length; i++){
// place the input (as a number) into the array
nums[i] = new Number(values[i]);
}
}
/* sum/average code */
Method three, input boxes:
<script>
function average(){
// initialize array with 10 elements
var nums = new Array(10);
// iterate over the elements
for (var i = 0; i < nums.length; i++){
// grab <input> based on id attribute
var input = document.getElementById('num' + i);
// insert the value (cast as a number) in to the array
nums[i] = new Number(input.value); // case to number
}
/* sum/average code */
}
</script>
<p>Enter 10 numbers:</p>
<input type="text" id="num0" />
<input type="text" id="num1" />
<input type="text" id="num2" />
<input type="text" id="num3" />
<input type="text" id="num4" />
<input type="text" id="num5" />
<input type="text" id="num6" />
<input type="text" id="num7" />
<input type="text" id="num8" />
<input type="text" id="num9" />
<button onclick="average()">Click to average</button>

Make cipher code in javascript using for loop and array?

I need to use a for loop to add 2 random letters to the string inputed into the text box and returned in the encrypted string box when the button is clicked.
So, for example, if cat was inputted it could return like cynarwtpp. I am new to for loops and unsure how to proceed from here, I need to use a for loop that will cycle through the alphabet array. any help would be greatly appreciated.
Javascript:
<script type="text/javascript">
var uncoded_array = uncoded.split("");
var coded_str = "";
var alphabet = new Array("a","b","c","d","e","f","g","h","i","j","k","l","m",
"n","o","p","q","r","s","t","u","v","w","x","y","z");
</script>
Html:
<form action="">
Enter a String: <input type="text" name="uncoded" ></br>
<input type="button" value="cipher" onClick=document.forms[0].coded.value= ></br>
Encrypted String: <input type="text" name="coded" ></br>
This is what I would do
html
Enter a String: <input type="text" id="uncoded" />
<input type="button" value="cipher" onclick="cypher(); return false;" />
Encrypted String: <input type="text" id="coded" />
js
function cypher() {
var coded = document.getElementById('coded');
var uncoded = document.getElementById('uncoded');
coded.value = uncoded.value.split('').map(function (char) {
return char + randomLetter() + randomLetter();
}).join('');
}
function randomLetter() {
return Math.random().toString(36).replace(/[^a-zA-Z]/gi, '')[0];
}
Here is a simple approach.
1) From this answer I learned to pick random element from array.
var item1 = alphabet[Math.floor(Math.random()*alphabet.length)];
var item2 = alphabet[Math.floor(Math.random()*alphabet.length)];
In your case 2 random letter from array.
2) In the for iteration, I have taken a string length and used to add the random element after each letter and concatenated together.
var alphabet = new Array("a","b","c","d","e","f","g","h","i","j","k","l","m",
"n","o","p","q","r","s","t","u","v","w","x","y","z");
var original = "cat";
var encrypted = "";
for (var i=0; i<original.length; i++ ) {
var item1 = alphabet[Math.floor(Math.random()*alphabet.length)];
var item2 = alphabet[Math.floor(Math.random()*alphabet.length)];
encrypted += original[i] + item1 + item2;
}
alert(encrypted);
JSFiddle
Here's a simple function that performs the string operation. Just feed it the value of the first form input, and dump its result into the second form input.
function cipher(str) {
var rand,
output = '',
chars = 'abcdefghijklmnopqrstuvwxyz';
for (i=0; i<str.length; i++) {
output += str[i];
for (j=0; j<2; j++) {
output += chars[Math.floor(Math.random() * chars.length)];
}
}
return output;
}
cipher('cat');

Categories

Resources