Decipher any string that is passed - javascript

I am attempting this question on Codewars. I am not sure if am doing it right. Here is the question:
You are given a secret message you need to decipher. Here are the things you need to know to decipher it:
For each word:
the second and the last letter is switched (e.g. Hello becomes Holle)
the first letter is replaced by its character code (e.g. H becomes 72)
Note: there are no special characters used, only letters and spaces:
decipherThis('72olle 103doo 100ya'); // 'Hello good day'
decipherThis('82yade 115te 103o'); // 'Ready set go'
Now I have written this piece of code:
function decipherThis(str)
{
var msg = [];
msg.push(str.charCodeAt(0));
for (var i = 0; i<str.length; i++)
{
if (str[1] == true && str[1] != str[str.length])
{
msg.push(str[str.length]);
//str[1] = str[str.length]);
var news = str;
for (var j = 0; j<news.length; j++)
{
news[1] = news[news.length];
const newNew = delete news[0][1];
msg.push(newNew);
}
}
}
return msg;
};
var google = "hello"
decipherThis(google)
I am getting an error and I think I have created it for a single word. It does not understand words after blank spaces. Please help me fix this.
This is the error traceback:
Response received but no data was written to STDOUT or STDERR.

Please change characterCodeAt to charCodeAt and it will work.
characterCodeAt is not a valid method of a String class

The error is not Javascript related. It might occur because the decipherThis() function is returning an array instead of a string.
You could loop the original string backwards until the second character and concatonate it to the charcode of the first character like this:
function decipherThis(str)
{
var cipher = '',
words = str.split(' ');
for(var w = 0; w < words.length; w++) {
cipher += ' '+words[w].charCodeAt(0);
for(var i = words[w].length-1; i > 0; i--) {
cipher += words[w][i];
}
}
return cipher.trim();
}

Related

How to replace all same charter/string in text with different outcomes?

For example let's say I want to attach the index number of each 's' in a string to the 's's.
var str = "This is a simple string to test regex.";
var rm = str.match(/s/g);
for (let i = 0;i < rm.length ;i++) {
str = str.replace(rm[i],rm[i]+i);
}
console.log(str);
Output: This43210 is a simple string to test regex.
Expected output: This0 is1 a s2imple s3tring to tes4t regex.
I'd suggest, using replace():
let i = 0,
str = "This is a simple string to test regex.",
// result holds the resulting string after modification
// by String.prototype.replace(); here we use the
// anonymous callback function, with Arrow function
// syntax, and return the match (the 's' character)
// along with the index of that found character:
result = str.replace(/s/g, (match) => {
return match + i++;
});
console.log(result);
Corrected the code with the suggestion — in comments — from Ezra.
References:
Arrow functions.
"Regular expressions," from MDN.
String.prototype.replace().
For something like this, I would personally go with the split and test method. For example:
var str = "This is a simple string to test regex.";
var split = str.split(""); //Split out every char
var recombinedStr = "";
var count = 0;
for(let i = 0; i < split.length; i++) {
if(split[i] == "s") {
recombinedStr += split[i] + count;
count++;
} else {
recombinedStr += split[i];
}
}
console.log(recombinedStr);
A bit clunky, but works. It forgoes using regex statements though, so probably not exactly what you're looking for.

How to make element in Array change its' place

I'm beginner in JS. I've tried to understand Caesar Cipher ROT13, but it was too complicated for me. So I've tried to write my own code. Here it is below:
function encrip() {
var alphabet = ["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 str = "Ni Hao";
var string = str.toUpperCase();
for (var i = 0; i < string.length; i++) {
for (var k = 0; k < alphabet.length; k++) {
if(string.charAt(i) == alphabet[k]) {
/* console.log(string.charAt(i) + ' ' + alphabet.indexOf(alphabet[k])); */
}
}
}
}
encrip();
But I am stuck. How to do:
1. Get value from var str and then access to var alphabet , after change each letter from var str value to next 3 from alphabet (var str each element's current position would be changed) For example: Input: Ni Hao ==> output: QL KDR
2. Create universal code, I mean, not only for changing position by 3, but when I give value '5', each element would be changed by next 5 positions from alphabet. So output can be changed when I change its' value
I hope I explained everything clearly. Thanks everyone in advance for help!!
you can use the following function to encrypt english words, the 1st parameter is the string to encrypt and the 2nd for shifting
function encryp(str,pos){
var alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var strUC=str.toUpperCase();
var enc="";
for(var i=0;i<strUC.length;i++){
if(strUC.charAt(i)!=" "){
enc+=alpha.charAt((alpha.indexOf(strUC.charAt(i))+pos)%26)
}
else{
enc+=" "
}
// in your case pos=3
}
return enc;
}
console.log(encryp("NiHao",3));
You don't need two for loops to do this. Iterate over the input string and find the index of each character in the alphabet array, if found add the shift to it to get the encrypted character.
To handle overflow use the modulus operator to cycle through the array.
Also I assume that you are not going use any special symbols to do the encryption.
function encrip(string, shift) {
var alphabet = ["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"];
string = string.toUpperCase();
let arr = [];
for (var i = 0; i < string.length; i++) {
let char = alphabet.indexOf(string[i]) !== -1 ? alphabet[(alphabet.indexOf(string[i]) %26) + shift] : " ";
arr.push(char);
}
let encryp = arr.join("");
console.log(encryp);
return encryp;
}
encrip("Ni Hao", 3);
First of all, instead of your inner for loop scanning the whole alphabet array, you can use the built-in function indexOf:
alphabet.indexOf('K') // returns 10
Secondly, you'll want to build up your enciphered string in a separate variable. For each letter, get the index of that letter in the alphabet, add your cipher offset parameter to that index and add the resulting letter from the alphabet to your new string. An important step is that when you add to the index of the letter, you want to make sure the resulting index is within range for the alphabet array. You can do that using the % (modulo) operator, which will wrap high values back round to the start of the array. In full:
function encipher(input, offset) {
var alphabet = ["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 str = input.toUpperCase();
var result = '';
for (var i = 0; i < str.length; i++) {
letterIndex = alphabet.indexOf(str.charAt(i));
if (letterIndex === -1) {
result += str[i]; // if the letter isn't found in the alphabet, add it to the result unchanged
continue;
}
cipheredIndex = (letterIndex + offset) % alphabet.length; // wrap index to length of alphabet
result += alphabet[cipheredIndex];
}
console.log(result);
}
encipher('Ni Hao', 5); // output: 'SN MFT'

Printing in Javascript

i have a question that seems basic but i can't seem to figure it out.
Write a program that takes the value of a variable called “input” (declared as any whole number at the top of your program) and outputs a square made of asterisks () as large as the number (input). For example, if the “input” is declared with the value 5, your program would display a square made of 25 asterisks() – ie ; 5 asterisks () high, by 5 asterisks () long.
The code i've come up with so far is below. I don't really understand how to make a string continuously print. If i did star = i then it turns into numbers and will print the numbers. So how do i make it so they connect? I also can't figure out where i should put the new line. console.log(star "\n"); gives me an error. Please help :)
var input = 2;
var star = "*";
var i = 0;
do {
console.log(star);
i++;
} while (i < input);
You can use String.repeat() (ES6 only) along with \r\n to add new line
var input = 5,
star = "*",
str = [],
i = 0;
do {
str.push( Array(input).join(star) ); // use array(length).join
i++;
} while (i < input);
str = str.join("\r\n"); // add breaklines
console.log(str);
console.log Will output a single line to the console containing whatever you pass it as an argument. You are trying to print a line of n asterisks n times.
The first step you should take is constructing the string of asterisks. You can concatenate a string to another with the + operator:
var input = 2;
var star = "*";
var line = "";
for(var i = 0; i < input; i++) {
line = line + star;
}
Once you have constructed line you can then print it n times:
for(var i = 0; i < input; i++) {
console.log(line);
}
Hint: You could create an empty array and then create a loop ending at your wanted number of asterisks after which you will join all the members of the array together. (Writing the code here wouldn't help you much since you mentioned it's an homework).
You could approach this in two ways. If we call your input value n, then we can log either n strings each consisting of n stars, or we can log a single string, containing (n * n) stars, with line breaks after every nth star.
Below is an example of a function that could do this task.
function stars (input) {
var output = ''
for (var i = 0; i < input; i++) {
for (var j = 0; j < input; j++) {
output += '*'
}
output += '\n'
}
return output
}
You can use the repeat-function to print a character multiple times.
var input = 2;
var star = "*";
var i = 0;
while(i++ < input){
console.log(star.repeat(input));
}
This repeats the * character input times in input lines.

Longitudinal redundancy check in Javascript

I'm working with a system that integrates a Point of Sell (POS) device, I use chrome serial to scan ports and be able to read credit card data.
The problem I'm facing is that I need to concat the LRC from a string in this format:
STX = '\002' (2 HEX) (Start of text)
LLL = Length of data (doesn't include STX or ETX but command).
Command C50 {C = A message from PC to POS, 50 the actual code that "prints" a message on POS}
ETX = '\003' (3 HEX) (End of text)
LRC = Longitudinal Redundancy Check
A message example would be as follows:
'\002014C50HELLO WORLD\003'
Here we can see 002 as STX, 014 is the length from C50 to D, and 003 as ETX.
I found some algorithms in C# like this one or this one and even this one in Java, I even saw this question that was removed from SO on Google's cache, which actually asks the same as I but had no examples or answers.
I also made this Java algorithm:
private int calculateLRC(String str) {
int result = 0;
for (int i = 0; i < str.length(); i++) {
String char1 = str.substring(i, i + 1);
char[] char2 = char1.toCharArray();
int number = char2[0];
result = result ^ number;
}
return result;
}
and tried passing it to Javascript (where I have poor knowledge)
function calculateLRC2(str) {
var result = 0;
for (var i = 0; i < str.length; i++) {
var char1 = str.substring(i, i + 1);
//var char2[] = char1.join('');
var number = char1;
result = result ^ number;
}
return result.toString();
}
and after following the Wikipedia's pseudocode I tried doing this:
function calculateLRC(str) {
var buffer = convertStringToArrayBuffer(str);
var lrc;
for (var i = 0; i < str.length; i++) {
lrc = (lrc + buffer[i]) & 0xFF;
}
lrc = ((lrc ^ 0xFF) + 1) & 0xFF;
return lrc;
}
This is how I call the above method:
var finalMessage = '\002014C50HELLO WORLD\003'
var lrc = calculateLRC(finalMessage);
console.log('lrc: ' + lrc);
finalMessage = finalMessage.concat(lrc);
console.log('finalMessage: ' + finalMessage);
However after trying all these methods, I still can't send a message to POS correctly. I have 3 days now trying to fix this thing and can't do anything more unless I finish it.
Is there anyone that knows another way to calculate LRC or what am I doing wrong here? I need it to be with Javascritpt since POS comunicates with PC through NodeJS.
Oh btw the code from convertStringToArrayBuffer is on the chrome serial documentation which is this one:
var writeSerial=function(str) {
chrome.serial.send(connectionId, convertStringToArrayBuffer(str), onSend);
}
// Convert string to ArrayBuffer
var convertStringToArrayBuffer=function(str) {
var buf=new ArrayBuffer(str.length);
var bufView=new Uint8Array(buf);
for (var i=0; i<str.length; i++) {
bufView[i]=str.charCodeAt(i);
}
return buf;
}
Edit After testing I came with this algorithm which returns a 'z' (lower case) with the following input: \002007C50HOLA\003.
function calculateLRC (str) {
var bytes = [];
var lrc = 0;
for (var i = 0; i < str.length; i++) {
bytes.push(str.charCodeAt(i));
}
for (var i = 0; i < str.length; i++) {
lrc ^= bytes[i];
console.log('lrc: ' + lrc);
//console.log('lrcString: ' + String.fromCharCode(lrc));
}
console.log('bytes: ' + bytes);
return String.fromCharCode(lrc);
}
However with some longer inputs and specialy when trying to read card data, LRC becomes sometimes a Control Character which in my case that I use them on my String, might be a problem. Is there a way to force LRC to avoid those characters? Or maybe I'm doing it wrong and that's why I'm having those characters as output.
I solved LRC issue by calculating it with the following method, after reading #Jack A.'s answer and modifying it to this one:
function calculateLRC (str) {
var bytes = [];
var lrc = 0;
for (var i = 0; i < str.length; i++) {
bytes.push(str.charCodeAt(i));
}
for (var i = 0; i < str.length; i++) {
lrc ^= bytes[i];
}
return String.fromCharCode(lrc);
}
Explanation of what it does:
1st: it converts the string received to it's ASCII equivalent (charCodeAt()).
2nd: it calculates LRC by doing a XOR operation between last calculated LRC (0 on 1st iteration) and string's ASCII for each char.
3rd: it converts from ASCII to it's equivalent chat (fromCharCode()) and returns this char to main function (or whatever function called it).
Your pseudocode-based algorithm is using addition. For the XOR version, try this:
function calculateLRC(str) {
var buffer = convertStringToArrayBuffer(str);
var lrc = 0;
for (var i = 0; i < str.length; i++) {
lrc = (lrc ^ buffer[i]) & 0xFF;
}
return lrc;
}
I think your original attempt at the XOR version was failing because you needed to get the character code. The number variable still contained a string when you did result = result ^ number, so the results were probably not what you expected.
This is a SWAG since I don't have Node.JS installed at the moment so I can't verify it will work.
Another thing I would be concerned about is character encoding. JavaScript uses UTF-16 for text, so converting any non-ASCII characters to 8-bit bytes may give unexpected results.

Print out last character of all words in a string

What are some clean ways to print out last characters of all words in a string. For example, a phrase like "laugh ride lol hall bozo " --> "hello" and "dog polo boo sudd noob smiley ride " --> goodbye.
These lines would return "1" and undefined. Any help is much appreciated.
var decrypt = function (message) {
var solution = [];
for (var i = 0; i < message.length; i++) {
if(message.charAt(i)===" ") {
return solution.push(message.charAt(i-1));
};
};
};
var resulta = decrypt("laugh ride lol hall bozo ")
console.log(resulta); // logs "hello"
var resultb = decrypt("dog polo boo sudd noob smiley ride ")
console.log(resultb); // logs "goodbye"
Don't return inside the loop, just append the charater to the result. When the loop is done, return what you want. Since you apparently want to return a string, you don't need an array.
var decrypt = function (message) {
var solution = '';
for (var i = 0; i < message.length; i++) {
if(message.charAt(i)===" ") {
solution += message.charAt(i-1);
};
};
return solution;
};
var resulta = decrypt("laugh ride lol hall bozo ")
console.log(resulta); // logs "hello"
var resultb = decrypt("dog polo boo sudd noob smiley ride ")
console.log(resultb); // logs "goodbye"
Assuming the words are separated by spaces you can do it in one line:
var decrypt = function (message) {
return (message+" ").match(/\w\s/g).join("").replace(/\s/g,"");
}
The regex /\w\s/g will match a word character followed by a space. The .match() method will return an array of all such matches. .join() will join the array elements into a string. And then .replace() will remove the spaces from that string.
Note that I'm using (message+" ") to add an extra space to the input string just in case it doesn't already have one at the end.
Also the code I showed doesn't allow for strings that don't have any "word characters" in them. If you want to test for that you need two lines:
var decrypt = function (message) {
var m = (message+" ").match(/\w\s/g);
return m ? m.join("").replace(/\s/g,"") : "";
//include default value for non match here^^
}
Another clean solution is
var decrypt = function (message) {
return message.split(' ')
.map(function(word) { return word.slice(-1); })
.join('');
}
This is relies on Array.prototype.map, which was added in ES5 with support for all modern browsers (http://kangax.github.io/compat-table/es5/#Array.prototype.map).
Considering you only care about the last character of each word, I would loop through the string in reverse. This allows you to also print the last character in the string without appending a space on the end of the encoded message.
function decrypt(message) {
var c, secret = '', lastSpace = true;
for (var i = (message || '').length - 1; i >= 0; i--, lastSpace = c === ' ') {
c = message.charAt(i);
if (lastSpace) secret = c + secret;
}
return secret;
}

Categories

Resources