Make cipher code in javascript using for loop and array? - javascript

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');

Related

Iterate through arrays inside a .replace()

I need to replace all letters from a string to other signs (stored in an array).
for (var i = 0; i < letters.length; i++) {
output.value = input.value.replace(letters[i], signs[i]); //this should be global
}
var input = document.getElementById('input');
var output = document.getElementById('output');
var letters = ['a', 'b', 'c'];
var signs = ['.', ':', '-'];
function run() {
for (var i = 0; i < letters.length; i++) {
output.value = input.value.replace(letters[i], signs[i]); //this should be global
}
}
<input type="text" id="input" onkeyup="run();">
<input type="text" id="output">
If the input says "abc" the output should say ".:-"
The problem is the new updated value after the replacing step, what you need to do is store the new value and after replacing the whole set of chars, then set the new value to output.value.
An important detail here is that you need to replace all chars which match with a specific letter, to accomplish that you can build a Regexp and use the flag global g.
new RegExp(letters[i], 'g');
^
|
+---- This is the flag!
Another thing I recommend is to embrace the function addEventListener to bind an event to elements.
var input = document.getElementById('input');
var output = document.getElementById('output');
var letters = ['a', 'b', 'c'];
var signs = ['.', ':', '-'];
function run() {
var currentInput = this.value;
for (var i = 0; i < letters.length; i++) {
var rg = new RegExp(letters[i], 'g');
currentInput = currentInput.replace(rg, signs[i]);
}
output.value = currentInput;
}
input.addEventListener('input', run);
<input type="text" id="input">
<input type="text" id="output">
I would turn you letters and signs into a lookup table like:
{a: ',', b:':' // etc..}
so you don't need to search through the letters with each keyup. You can do this once at the beginning, or just use the format to begin with. The you can just map() it to a new value
var input = document.getElementById('input');
var output = document.getElementById('output');
var letters = ['a', 'b', 'c'];
var signs = ['.', ':', '-'];
let signMap = letters.reduce((a, c, i) => {
a[c] = signs[i]
return a
}, {})
function run() {
output.value = [...input.value].map((i) => signMap[i]).join('')
}
<input type="text" id="input" onkeyup="run();">
<input type="text" id="output">
Another alternative if your letters are always going to be in order is to use the character codes for the lookup in signs. You can also use replace with a generic regex and pass the letter to the function. Then you can avoid the loop altogether. This will ignore input not in the signs, but you could easily just include the original letter if it's not in the signs array.
var input = document.getElementById('input');
var output = document.getElementById('output');
var signs = ['.', ':', '-'];
let offset = 'a'.charCodeAt(0)
function run() {
output.value = input.value.replace(/./g, s => signs[s.charCodeAt(0) - offset] || '' )
}
<input type="text" id="input" onkeyup="run();">
<input type="text" id="output">
My opinion:
I prefer to create one Object to store all mappings, like what signMap does.
create one regex like (a|b|c|ef) (so you don't need to loop each character for input string, then even it can support multiple letters). PS: assuming the elements in Array=letters are not special letters, if yes, you need to adjust Regex Expression for your real case.
then uses String.replace(regex, (replacement)=>{return 'what you need'})
like below simple demo:
var input = document.getElementById('input');
var output = document.getElementById('output');
var letters = ['a','b','c', 'ef'];
var signs = ['.',':','-', '#'];
let regex = new RegExp('('+letters.join('|') + ')', 'g') //assume the elements in Array=letters doesn't have special characters.
let signMap = letters.reduce((pre, cur, curIndex) => {
pre[cur] = signs[curIndex]
return pre
}, {})
function run() {
output.value = input.value.replace(regex, (item)=> {
return signMap[item]
});
}
<input type="text" id="input" onkeyup="run();">
<input type="text" id="output">

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

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;})

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
}

Count occurance of a letter or a word in a sentence

I wonder how I can find how many characters, example e, in a text using a for loop and a increasing substring to go through the whole text.
This is what I got so far.
HTML:
<p id="paragraph"> this is the sentence, how many letters "e" can you find? How many "is" can you find</p>
<input type="text" id="text"/> <input type="button" value="search" onclick="search()"/>
<p id="howmany"></p>
JavaScript:
function search() {
var letter = document.getElementById("text").value;
var text = document.getElementById("paragraph").innerHTML;
var count = 0;
var string = text.substring(0);
for(var i = 0; i < text.length, i++) {
count++
}
document.getElementById("howmany").innerHTML = ("The result is" + count)
}
I only get how many characters there is in the text, but I want to find how many e or is or whatever there is in the text. I know there is something missing but what?
There's no need for a loop for this - you can just use a regex and count the matches:
string.match(/e/g).length
string.match(/is/g).length
That said, there are a bunch of other errors in your code:
function search() {
var letter = document.getElementById("text").value;
var text = document.getElementById("paragraph").innerHTML;
var count = 0;
var string = text.substring(0,text.lenght); // should be length; or else not needed at all
for(var i = 0; i < text.length, i++) {
count++
}
document.getElementsById("howmany").innerHtml = ("The result is" + count) // it's getElementById, not getElements; it's innerHTML, not innerHtml
}
Also: onclick, on clickOn.
My own take on this problem:
function howMany () {
var needle = document.getElementById('text').value.trim(),
textProp = 'textContent' in document ? 'textContent' : 'innerText',
haystack = document.getElementById('paragraph')[textProp].trim(),
result = haystack.match(new RegExp(needle, 'g'));
document.getElementById('howmany')[textProp] = result ? result.length : 0;
}
document.querySelector('input[type=button]').addEventListener('click', howMany);
#howmany::before {
content: 'Matches found: ';
}
#howmany:empty::before {
content: '';
}
<p id="paragraph">This is the sentence, how many letters "e" can you find? How many "is" can you find</p>
<label>String to find: <input id="text" placeholder="what are you looking for?" /></label>
<input type="button" value="search" />
<p id="howmany"></p>
References:
document.getElementById().
document.querySelector().
EventTarget.addEventListener().
in operator.
JavaScript regular expressions.
String.prototype.match().
String.prototype.trim().

Looping Through an Array of Characters

I would like to loop an array for a specific set of characters that is constantly changing. From there on I want to toggle case the letters, and I've been told to use this specific code but I can't get it to work. The code MUST loop through an array of characters, where the characters are coming from an "input" textbox. How can I fix this?
I should mention that I'm doing this for class in high school, so I'm no where near perfect at coding.
<html>
<head>
<script type="text/javascript">
function toggleCase() {
var i = document.getElementById("input").value.length;
var word = document.getElementById("input").value;
var chop =new array(i);
for (a=i; a <= i; a++) {
character[i] = word.slice(i-1,i)
if (character[i] == character[i].toUpperCase;){
character[i] = character[i].toLowerCase();
}
else {
character[i] = character[i].toUpperCase();
}
}
var final
for (a=i; a <= i; a++) {
final += character[i];
}
document.getElementById("output").value = final
}
</script>
</head>
<body>
<p>Enter letters for conversion:</p>
<form>
<input type="text" name="input" id="input" value="sample" maxlength="10"><br />
<input type="text" name="output" id="output" value="" /> <br/>
<input type="checkbox" name="toggle" value="ToggleCase" onClick="toggleCase(this.form)">Toggle Case<br/>
</form>
</body>
</html>
Maybe you should take a look at some api's and howtos but here is your code:
<html>
<head>
<script type="text/javascript">
function toggleCase() {
var text = document.getElementById("input").value;
var character = new Array(text.length);
for (i=0, a = text.length; i < a; i++) {
character[i] = text[i];
if (character[i] == character[i].toUpperCase){
character[i] = character[i].toLowerCase();
}
else {
character[i] = character[i].toUpperCase();
}
}
document.getElementById("output").value = character.join('');
}
</script>
</head>
<body>
<p>Enter letters for conversion:</p>
<form>
<input type="text" name="input" id="input" value="sample" maxlength="10"><br />
<input type="text" name="output" id="output" value="" /> <br/>
<input type="checkbox" name="toggle" value="ToggleCase" onClick="toggleCase()">Toggle Case<br/>
</form>
</body>
</html>
function toggleCase() {
var str = document.getElementById("input").value;
for (var i=0; i<str.length; i++) {
str[i] = (str[i]==str[i].toUpperCase() ? str[i].toLowerCase() : str[i].toUpperCase());
}
document.getElementById("output").value = str;
}
that's a for loop that does the job. and remember .toUpperCase and .toLowerCase are functions
You might want to take a look at the String's split method.
var str = 'foo bar baz';
The simplest way to convert a string into a char array is by passing an empty string into the split method.
var charArray = str.split(''):
// charArray === ['f','o','o' ... 'b','a','z'];
Also a FYI, passing a space character into split will give you an array of words.
var wordArray = str.split(' ');
// wordArray === ['foo', 'bar', 'baz'];
I'm a little unclear what you have to solve but it looks like you want a function convert upper case letter into lowercase letters and vise versa.
var userInput = document.getElementById('someTextBox');
// If you want to be fancy you could use JQuery
// var userInput = $(#someTextBox').value()
function toggledCase( str ) {
var characters = str.split('');
// The split method still uses iteration so should be able to say it
// satisfies the argument of looping through each character.
// Split just provides a good abstraction to interface with.
var toggledCharacters = [];
var i;
var ch;
for( i in characters ) {
// For in loops on strings will return the indexes instead
// of the characters
ch = characters[i];
if( ch.toUpperCase() === ch ){
toggledCharacters.push( ch.toLowerCase() );
} else {
toggledCharacters.push( ch.toUpperCase() );
}
// If you like one-liners,
// the conditional if statement could be replace with a ternay statement.
// toggledCharacters.push( ( ch.toUpperCase() === ch ) ?
// ch.toLowerCase() : ch.toUpperCase();
}
return toggledCharacters;
}
My toggledCharacters method only returns an array of characters, so if you want back as a string you could make a for loop;
var arr = toggledCharacters('Foo'); // str = 'fOO';
var str = '';
var i, ch;
for ( i in arr ) {
str += arr[i]; // += is just a short hand notation of saying
// str = str + arr[i];
}
If you are lazy and like one-liners, take a look at functional programming. It's kinda out of scope since you are still in High School.
var arr = toggledCharacters('Foo'); // str = 'fOO';
var str = arr.reduce( function(str, ch) {
return str + ch;
} );
Anyway, this looks a lot cleaner to me than what the teacher outlined.
function toggledCharacters(input) {
input = input.split('');
var output = [];
var i, ch;
for( i in input ) {
output.push( ( input[i].toUpper() === input[i] ) ?
input[i].toLower() : input[i].toUpper()
);
}
return output.reduce(
function(str, ch) {
return str + ch;
}
);
}
Edit:
Oh, I just notice that nowhere in that code the is the check's box boolean value being evaluated.
var checkBox = document.getElementByName('toggle');
var inputTextBox = document.getElementById('input');
var outputTextBox = document.getElementById('output');
var result = inputTextBox.value;
if( checkBox.checked ) {
result = toggleCase( result );
}
outputTextBox.value = result;
Oh another FYI since you are a beginner. Make sure you know to use the browser's console.
If you are on Firefox, grab the firebug app.
Chrome, press Ctrl-Shift-C.
IE has one as well, I just don't care to ever use it.
The console makes it easier to experiment with JS then compared to making html demo page and assuming the code is working as it should.
Plus, these developer tools can show you underlying methods of an object. It makes for a great and quick way to learn JS.

Categories

Resources