Passing the value of a sub-array into CharCodeAt in JavaScript - javascript

Essentially I am working on this coding challenge on FreeCodeCamp. The start of the challenge mentions this to start with...
A common modern use is the ROT13 cipher, where the values of the
letters are shifted by 13 places. Thus 'A' ↔ 'N', 'B' ↔ 'O' and so on.
Write a function which takes a ROT13 encoded string as input and
returns a decoded string.
So far I have passed the string to an array, with each part of the string in its own array (a sub-array). From there I figure I would use a loop to go through each character in the string (in each sub-array) and pass the CharCodeAt method to each one.
My problem lies with passing each individual character to go through CharCodeAt.
This is a part of the total function which follows below:
To me this makes sense, as I 'am passing each sub-array value in a variable
var foo = container[i][k];
// var output = container.map(function mapHandler(){foo.charCodeAt(k)});
function rot13(str){
var container, j = 0;
while(j <= str.length - 1){
container = str.split(' ');
j++;
}
for(var i = 0; i < container.length; i++){
for(var k = 0; k < container[i].length; k++){
var foo = container[i][k];
var map = Array.prototype.map;
var output = map.call(foo, function(x){ return x.charCodeAt(k);});
// var output = container.map(function mapHandler(){foo.charCodeAt(k)});
// output.charCodeAt(k);
}
}
return output;
}
rot13("SERR PBQR PNZC") should decode to "FREE CODE CAMP"
Could anyone just help get to this point? I don't want the whole solution!
Thanks in advance!

You can turn a string into array of single letters by splitting it with an empty string:
var arr = str.split("")
Then you can use for example .map() to change each letter into decoded one:
var decoded = arr.map(x=> {
// decode x
})

Related

How to reverse a string using only one variable

How to reverse string using next conditions:
1) if string isn't parameter of function,
2) if string is place in global scope,
3) use loop like for, while,
4) can add one variable
Note: Can't use method .join, .split, .reverse and so on...
If it possible and not so hard for you make explain your solution, very grateful !
In other words, this is what you got:
let s = 'any string';
let p; // feel free to use at your discretion
// your code here. No further variables, no functions and no built-ins
// should console.log the reversed string
I'm understand that my solution is very close to my desire (conditions), but i can't generate other solution.
function convers(s){ //parameter
var str = "";//empty string for new converted string
for(var i = s.length-1; i >= 0; i--)//loop decremebtation that count from end of string
str+=s[i];//store result and assignments to str
return str;// declare result
}
console.log(convers("abcdef"));
I looked this source:
javascript reverse string algorithm
Is there a faster Reverse String Algorithm for JavaScript? - but it is useless for me, sorry.
I'm sorry if my explanation is not clear enough. Sorry for my English, I'm beginner here :))))
You could use a new variable for the reverted string and use the length property for iterating.
var string = 'abcdef',
reverse = '';
while (reverse.length !== string.length) {
reverse += string[string.length - 1 - reverse.length];
}
string = reverse;
console.log(string);
A bit shorter.
var string = 'abcdef',
reverse = '';
while (reverse.length !== string.length) {
reverse = string[reverse.length] + reverse;
}
string = reverse;
console.log(string);
Please check below condition I hope it will help you
1) if string isn't parameter of function
function convers(s){ //parameter
s = s.toString();
var str = "";//empty string for new converted string
for(var i = s.length-1; i >= 0; i--)//loop decremebtation that count from end of string
str+=s[i];//store result and assignments to str
return str;// declare result
}
console.log(convers(132));
2) if string is place in global scope
function convers(){ //parameter
var str = "";//empty string for new converted string
for(var i = dd.length-1; i >= 0; i--)//loop decremebtation that count from end of string
str+=dd[i];//store result and assignments to str
return str;// declare result
}
var dd ="123";
console.log(convers());
3) can add one variable
function convers(s,dd){ //parameter
var str = "";//empty string for new converted string
for(var i = s.length-1; i >= 0; i--)//loop decremebtation that count from end of string
str+=s[i];//store result and assignments to str
return str +dd;// declare result
}
function CallConvers(){
var dd = "ADD";
console.log(convers("abcdef",dd));
}
CallConvers();

Adding numbers within a string

I want to take a string of numbers and characters and add up the numbers.
For example: "In 2015, I want to know how much does iPhone 6+ cost?"
Output: 2021
Here is my current code:
var str = "In 2015, I want to know how much does iPhone 6+ cost?";
function sumFromString(str){
var punctuationless = str.replace(/['!"#$%&\\'()\*+,\-\.\/:;<=>?#\[\\\]\^_`{|}~']/g,"");
var finalString = punctuationless.replace(/\s{2,}/g," ");
var StringList = finalString.split(" ");
var sum = [];
for (i = 0; i < StringList.length; i++)
if (isInt(StringList[i])
sum.add(StringList[i]);
sum.reduce( (prev, curr) => prev + curr );
}
sumFromString(str);
My code takes a string and strips it of punctuation and then places each individual word/number into the array, StringList.
I can't get the next part to work.
What I tried was to iterate through each value in the array. The if statement is supposed to check if the array element is an integer. If so, it will add the integer to an empty array called sum. I then add all the values of the array, sum, together.
Much simpler:
function sumFromString(str) {
return (str.match(/\d+/g)||[]).reduce((p,c)=>+c+p);
}
Note in particular that I use +c+p - +c casting the current value from a string to a number, then adding it to p. This matches all the numbers in the string - getting an empty array if there were none - and reduces that.
For the sake of variety, here's a way to do it without regular expressions:
var myString = "5 bunnies ate 6 carrots in 2days.";
var myArray = myString.split('');
var total = 0;
for (var i = 0; i < myArray.length; i++) {
if (!isNaN(parseInt(myArray[i]))) {
total += parseInt(myArray[i]);
}
}
Fiddle Demo
note: If there's a chance myString could be null, you'd want to add a check before the split.
Split the string into an array of all characters with the split function and then run the filter function to get all numbers. Use the map function to go through all elements that include numbers, and delete characters from them that aren't digits.
Then use reduce to get the sum of all numbers. Since we're dealing with strings here, we have to perform type conversion to turn them into numbers.
string.split(' ').filter(function(word) {
return /\d+/.test(word) }
}).map(function(s) {
return s.replace(/\D/, '')
}).reduce(function(a,b) {
return Number(a) + Number(b);
});

Javascript Array Issues

The task at hand;
Return true if the string in the first element of the array contains
all of the letters of the string in the second element of the array.
For example, ['hello', 'Hello'], should return true because all of the
letters in the second string are present in the first, ignoring case.
The arguments ['hello', 'hey'] should return false because the string
'hello' does not contain a 'y'.
Lastly, ['Alien', 'line'], should return true because all of the
letters in 'line' are present in 'Alien'.
My attempted solution that isn't working;
function mutation(arr) {
if (arr[0].toLowerCase().indexOf(arr[1].toLowerCase()) >= 0){
return true;
}else{
return false;
}
return arr;
}
mutation(['hello', 'hey']);
Can someone please explain to me why it isn't working. I am not looking for an answer just an explanation so that I can understand better.
Many thanks
Try this:
$('#id').click(function() {
var arr = ['hello','hey'];
var isExist = false;
for (i = 0;i < arr[1].length; i++) {
if(arr[0].toLowerCase().indexOf(arr[1][i].toLowerCase()) >= 0)
isExist = true;
else {
isExist = false;
break;
}
}
if (isExist)
alert('true'); // In case of all chars of 2nd present in 1st arr
});
what you are doing is that, you are converting first element to lower case and than trying to find the second element in first array.
your solution will work for the cases where the whole second element exists in first element as a sub string or both elements are exactly same.
for example it'll work for following examples
['hello', 'Hello']
['hello', 'ell']
['hello', 'He']
But it will not work when letters in second string are shuffled first string. for following examples your solution will fail.
['Alien', 'line']
['hello', 'elo']
['hello', 'Hol']
If whole second word does not exists as it is in first word your solution will not work.
Let me know if this is helpful. i'll provide you the solution if you need.
As another answer correctly states, your code does not work because it's looking in the first string for the second string, in its entirety, with the letters in the same order. Instead, you need to look at each letter in the second string individually and check that it's in the first string.
We'll adopt the strategy of "Programming in English and going backward". The English for the overall problem is:
Does every letter to check match?
We can write this in JavaScript as
letters_to_check . every(matches)
We can calculate letters_to_check as input[1].toLowerCase().split('').
Now we have to write the matches function, which can be expressed in English as
Is the letter found in the string to check against?
So we write
function matches(letter) { return string_to_heck_against.search(letter); }
string_to_check_against is of course input[0].
The entire program is thus:
function mutation(input) {
// Check if a letter is in the string to be checked against.
function matches(letter) { return string_to_check_against.search(letter); }
var string_to_check_against = input[0].toLowerCase();
var string_to_check = input[1].toLowerCase();
var letters_to_check = string_to_check.split('');
return letters_to_check . every(matches);
}
If you are programming in ES6, this could be written as
function mutation([source, target]) {
return target .
toLowerCase() .
split('') .
every(letter => source.toLowerCase().search(letter));
}
According to your output you have to check all the characters of array second string with array first string. For this you have to check all characters are available or not in the first string, not using the direct string. If we use strings directly, it will look for total string not for the characters.
Try the following:
var arr = ['Alien', 'line'];
var arr1 = ['hello','hey'];
var arr2 = ['hello','Hello'];
function mutation(arr) {
var str1 = arr[0].toLowerCase();
var str2 = arr[1].toLowerCase();
var o = false;
for (var i=0;i<str2.length;i++) {
o = (str1.indexOf(str2[i]) !== -1);
if (!o) break;
}
return o;
}
console.log('first arr : ', mutation(arr));
console.log('second arr :', mutation(arr1));
console.log('third arr :', mutation(arr2));
This is my working code. You can check. The idea is to transfer both strings in the array to lowercase. Then we compare both strings together.
I take every single letter from the shorter string, then use the indexOf function to check if it's in the longer string. Every time there is a match, the valule no1 or no2 will increase.
If the value of no1 or no2 equal with the length of the shorter string, it means all the letters in the shorter string is inside the longer string.
function mutation(arr) {
// transfer both strings in the array to lower case
var val1 = arr[0].toLowerCase();
var val2 = arr[1].toLowerCase();
// check if val2 is shorter than val1
if(val1.length >= val2.length){
var no1 = 0;
// Check every if any letter in val2 is in val1
for(var i = 0; i < val2.length; i++){
if(val1.indexOf(val2[i]) != -1){
// plus 1 if there is a match
no1++;
}
}
// check if the value of no1 equals to length of val2
if(no1 == val2.length){
return true;
}else{
return false;
}
}else if(val2.length > val1.length){
var no2 = 0;
for(var j = 0; j < val1.length; j++){
if(val2.indexOf(val1[j]) != -1){
no2++;
}
}
if(no2 == val1.length){
return true;
}else{
return false;
}
}
}

New to javascript, how to write reverse iteration?

I'm currently taking an introduction CIS class at my university and one of the projects is javascript. It is split into two unrelated parts and I was able to do the second part but I'm stuck on the first one. My professor wants me to write an iteration that will display in a reverse order whatever name I write in the prompt screen. So if I write "John Smith" it will display "htims nhoj". The issue is that I have no idea how to write it.
<html>
<body>
<script>
var namIn = window.prompt("Enter name:" );
var namAr = namIn.split("");
var namArLen = namAr.length;
document.write(namAr + "<br /> Length: " + namArLen);
</script>
</body>
</html>
Strings in JavaScript have a function called split() which turn them in to Arrays. Arrays in JavaScript have a function called reverse() which reverse their order, and a function called join() which turn them back into Strings. You can combine these into:
"John Smith".split("").reverse().join("")
This returns:
"htimS nhoJ"
Also, and I don't know if this is a typo, but you can throw a toLowerCase() to get 100% of what your question is after:
"John Smith".split("").reverse().join("").toLowerCase()
returns:
"htims nhoj"
As for the question in your title, you can specify the direction of a for loop in the last argument like so:
var reversed = [];
var name = "John Smith".split("");
for(var i = name.length-1; i >= 0; i--) {
reversed.push(name[i]);
}
console.log(reversed.join(""));
Which will output:
"htimS nhoJ"
There's no need to split this string into an array. Just use the charAt() function and a simple for loop.
var name = window.prompt("Enter name:");
var reverse = "";
for (var i = name.length - 1; i >=0; i--) {
reverse += name.charAt(i);
}
console.log(reverse)
Instead of converting the string to an array first, you're just reading the characters out of the string directly.
You can accomplish this by iterating only half the number of characters.
DEMO: http://jsfiddle.net/vgG2P/
CODE:
var name = "Bob Dylan".split("");
// The counters will meet in the middle.
// --------------+----------------------
// first char last char | inc dec
// -------v-------------v-----------v----v----v
for(var i = 0, j = name.length-1; i < j; i++, j--) {
var temp = name[i]; // Store the `i` char
name[i] = name[j]; // Replace the `i` char with the `j` char
name[j] = temp; // Replace the `j` char with the `i` char we stored
}
console.log(name.join("")); "nalyD boB"
EXPLANATION:
What we did was split the characters into an Array, and maintain two counters, one that increments from the first character at 0, and the other that decrements from the last character at .length - 1. Then simply swap the characters.
The iteration continues while your incrementing counter is less than your decrementing counter. Since they will meet in the middle, you'll end up incrementing only half the total length.
We can also build the halves of the result without using an Array:
DEMO: http://jsfiddle.net/vgG2P/1/
var name = "Bob Dylan";
var start = "", end = ""
for(var i = 0, j = name.length-1; i < j; i++, j--) {
end = name.charAt(i) + end
start += name.charAt(j)
}
if (i === j)
start += name.charAt(i)
console.log(start + end); "nalyD boB"
I'm assuming that your professor would not be asking you how to reverse a string if he hasn't yet introduced you to the concept of arrays and loops. Basically, a string like John Smith is just an array of characters like this:
0123456789
John Smith
Again, thinking in the sense that a string is just an array of characters, you have have 10 characters that need to be reversed. So how do you go about doing this? Well, you basically need to take the last character h from the "array" you're given and make it the first character in a new "array" you're going to create. Here's an example:
var known = 'John Smith';
var reversed = ''; // I'm making an empty string aka character array
var last = known.length - 1 // This is the index of the last character
for (var i = 0; i < known.length; i++)
{
temp += known[last - i];
}
(You can see it working here)
So what's happening?
We're looping over known starting at 0 and ending at 9 (from the first character to the last)
During each iteration, i is incrementing from 0 - 9
last always has a value of 9
last - i will give us indexes in reverse order (9, 8, 7, ..., 0)
So, when i is 0, last - i is 9 and known[9] is "h"; repeat this process and you get the reversed string
Hopefully this helps explain a little better what's happening when you call reverse() on an array.
(1) A more straight forward way without built-in functions:
function reverse(str) {
let reversed_string = "";
for (let i = str.length - 1; i >= 0; i--) {
reversed_string += str[i];
}
return reversed_string;
}
(2) Using ES2015 'for' helper function:
function reverse(str) {
let reversed_string = "";
for (let character of str) {
reversed_string = character + reversed_string;
}
return reversed_string;
}
(3) Using ES6 syntax and ES5.1 reduce():
function reverse(str) {
return str.split('').reduce((reversed, char) => char + reversed, '');
}
// reduce takes in 2 arguments. (1) arrow function, and (2) empty string.
Chances are, for an interview, that you will not able to use the built-in functions, especially for "reverse()".

Any javascript string function?

Some outside code is giving me a string value like..
null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,
now i have to save this value to the data base but putting 0 in place of null in javascript. Is there any javascript string releated function to do this conversion?
You can simply use the replace function over and over again until all instances are replaced, but make sure that all your string will ever contain is the character sequence null or a number (and obviously the delimiting comma):
var str = "null,402,2912,null"
var index = str.indexOf("null");
while(index != -1) {
str = str.replace("null", "0");
index = str.indexOf("null");
}
You need to run a for loop because the function String.replace(search, rplc) will replace only the first instance of search with rplc. So we use the indexOf method to check, in each iteration, if the required term exists or not. Another alternative (and in my opinion, a better alternative would be:
var str = "null,402,2912,null"
var parts = str.split(",");
var data = []
for(var i=0; i<parts.length; i++) {
data[data.length] = parts[i]=="null"?0:parseInt(parts[i]);
}
Basically, what we are doing is that since you will anyways be converting this to an array of numbers (I presume, and sort of hope), we first split it into individual elements and then inspect each element to see if it is null and make the conversion accordingly.
This should answer your needs:
var str = 'null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390';
str.split(",").map(function (n) { var num = Number(n); return isNaN(num) ? 0 : num; });
The simplest solution is:
var inputString = new String("null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,");
var outputString = inputString.replace("null", "0");
What I understood from your question is:
You want to replace null with 0 in a string.
You may use
string = "null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,"
string.replace(/null/g,0)
Hope it helps.

Categories

Resources