I was in codewars this morning and there is this Kata asking for a function to reverse a string passed as parameter through recursion method.
The best solution listed for this problem was this.
function reverse(str) {
return str.length > 1 ? reverse(str.slice(1)) + str[0] : str;
}
I researched for this all this morning and I still don't know what is happening here:
+ str[0]
Can somebody please clarify this for me?
The essence of the function is the following:
Take the substring from the second character to the last
Apply the reverse function recursively
Take the first character and append it to the end of the result of the recursive call
Return the result
This results in the following logic, the (recursive) function calls indicated by brackets:
(A B C D E)
((B C D E) A)
(((C D E) B) A)
((((D E) C) B) A)
(((((E) D) C) B) A)
str.slice(1) "chops off" the first letter of the string and returns the rest of it. So 'abcd'.slice(1) gives you 'bcd'.
str[0] is the first letter of the string. 'abcd'[0] is 'a'.
So, str.slice(1) + str[0] is taking the first letter of the string and "moving" it to the end: 'abcd' becomes 'bcda'.
This does not address the recursive nature of the solution, but it answers your question about + str[0].
I'll try to rewrite the function in a more "human-readable" way
reverse = str => {
// If there is still string to reverse
if (str.length > 1) {
let firstChar = str[0]
let strWithoutFirstChar = str.slice(1)
// Notice only a part of the string 'comes back' here
// console.log(strWithoutFirstChar) // Might help
return reverse(strWithoutFirstChar) + firstChar
}
// Else return result as is
else {
return str
}
}
This is the same function, but without ternaries and declaring well named variables.
If you uncomment the console.log() line and call:
reverse('help');
The output should be:
elp
lp
p
'pleh'
Hope it helps!
The + operator is a concatenator for string.
You can instead use concat this :
var reverse = str => str.length > 1 ? reverse(str.slice(1)).concat(str[0]) : str;
console.log(reverse("123456789")); // 987654321
Related
I am a total newbie and currently learning Javacript.
I encountered this problem on JSChallenger and have been struggling with it.
Here's my code:
// Write a function that takes a string (a) and a number (n) as argument
// Return the nth character of 'a'
function myFunction(a, n)
{let string = a;
let index = n;
return string.charAt(index);
}
Can anyone point out my errors?
Thanks so much!
Here's a very short solution
function find( a, b){
return a[b]
}
console.log(find('how',1));
although you need to do some tests in the function to check if the input for b is greater than the length of a else it would fail.
You can do that like this
function find( a, b){
if(a.length<b-1){
return 'error';
}
return a[b]
}
console.log(find('how',5));
that way your code would be free from error
Try this one
function myFunction(a, n){
return a[n - 1];}
// there is a shorter way to do this since you want to find what's missing here is what's missing.
function myFunction(a, n){
let string = a;
let index = n-1;
return string.charAt(index);
}
JS string's index starts enumerating from 0 so the n should be decremented by 1
// Write a function that takes a string (a) and a number (n) as argument
// Return the nth character of 'a'
function myFunction(a, n)
{
let string = a;
let index = n;
return string.charAt(index-1);
}
the easiest way to write it would be:
// Write a function that takes a string (a) and a number (n) as argument
// Return the nth character of 'a'
function myFunction(a,n) {
return a[n - 1];
}
Meaning return from string "a" of myFunction the index "[n-1]" , "n-1" it's a needed operation to get the right index because string index start enumerating from 0.
It is very easy you can just return the a[n]
but it is not the right answer because as you know the strings in JavaScript are zero-indexed so the right answer is
function myFunction(a, n) {
return a[n - 1]
}
Happy Coding & keep Learning
also this solution works too, with empty space at first of string we can remove that counting from zero :
function myFunction(a, n) {
return ` ${a}}`[n]
}
but this is just another solution. not tested. and you can check this repo for other JSchallenger solutinos: JSchallenger solutions
in javascript, you can write this simple code to solve your problem
ex:
let string = "Hello";
let n = 2;
return string[n];
function myFunction(a, n) {
return a.charAt(n - 1);
}
console.log(myFunction("hello", 2));
I think so this is best way
that is a tricky question if you look to the test cases you will notice that it ignore counting from zero
function myFunction(a, n) {
return a.charAt(n-1);
}
I am trying to make the code below repeat string s n number of times, however, it will always repeat n - 1 times, because I need to pass a decrement to exit the recursion or I will exceed the max call stack.
function repeatStr (n, s) {
while(n > 1) {
result = repeatStr(-n, s)
return s = s.concat(s)
}
}
repeatStr(3, "Hi")
What can I change to make it recurse correctly?
Recursion involves making a function call itself and AVOIDS using a loop. You have a loop in the recursive function which is a big red flag.
Do something like this:
If n is 1 return s else return s concatenated to the result of the function with n - 1.
function repeatStr (n, s) {
if (n == 1)
return s;
else
return s.concat(repeatStr(n - 1, s))
}
repeatStr(3, "Hi")
Because you're new to programming and JavaScript, let's work up to the solution. Start with a simple case, e.g. repeatStr(3, "Hi"). One simple answer may be:
function repeatStr(n, s) {
return "HiHiHi";
}
Here, we assume what the inputs are always 3 and "Hi". We don't have a while loop, and we don't have recursion. We have the correct answer for those specific inputs but no other inputs are supported.
Let's make the answer a little bit harder:
function repeatStr(n, s) {
return "Hi" + "Hi" + "Hi";
}
Here, again, we are assuming the inputs are 3 and "Hi". We still don't have a while loop nor do we have recursion.
Okay, let's start using one of your inputs:
function repeatStr(n, s) {
return s + s + s;
}
Here, we are finally using the string that's passed in as s. We can handle inputs other than "Hi" to generate a correct answer. But, we're still assuming the number input is 3.
Finally, let's have a look at n:
function repeatStr(n, s) {
let result = "";
while (n > 0) {
n = n - 1;
result = result + s;
}
return result;
}
Okay, here we take both inputs n and s into consideration and we solve the problem by appending s exactly the number n times needed. This is a while loop solution, not a recursion solution. Our while loop has the action result = result + s; repeated exactly n times where we use n as a countdown and stop when we reach 0.
Now, we have all that background, let's look at one version of the recursion solution.
function repeatStr(n, s) {
if (n <= 0) {
return "";
}
return s + repeat(n - 1, s);
}
Even in recursion form we retain the countdown feature. This time the countdown is used to drive the recursion instead of a while loop. We still counting down to 0 where we have an if-return guard condition that's needed to terminate the recursion. i.e. when n <= 0, we exit with the simple empty string "". Then for the more complex case, it is solving any nth version by expressing in terms of the (n-1) th version. Another way of looking at it is this:
repeatStr(3, "Hi") === "Hi" + repeatStr(2, "Hi")
=== "Hi" + "Hi" + repeatStr(1, "Hi")
=== "Hi" + "Hi" + "Hi" + repeatStr(0, "Hi")
=== "Hi" + "Hi" + "Hi" + ""
If you want to get a little clever, JavaScript has a conditional which can be used in place of your if statement:
function repeatStr(n, s) {
return (n <= 0) ? "" : s + repeat(n - 1, s);
}
Hope that makes sense.
Adding a decomposed approach to the other nice answers in this thread -
const concat = a => b =>
a.concat(b)
const repeat = n => f =>
x => n && repeat(n - 1)(f)(f(x)) || x
const hello =
repeat(3)(concat("Hi"))
console.log(hello("Alice"))
console.log(hello(""))
HiHiHiAlice
HiHiHi
I've completely drawn a blank on how to get a string to return properly inside of an if statement.
function truncateString(str, num) {
var s = str;
var n = num;
if(s > n.length) {
return s.slice(0, n - 3).concat("...");
} else return s;
}
truncateString("This string is too long", 11);
I know I've got it all wrong but can't figure out how to make it work.
Please do not post the solution, just remind me how to return the string correctly within an if statement.
It's fine, you just swapped the arguments by mistake.
if(s > n.length)
should be
if(s.length > n)
Basically a number do not have a property called length with it,
if(s.length > n)
Full code would be,
function truncateString(str, num){
var s = str;
var n = num;
if(s.length > n) {
return s.slice(0, n - 3).concat("...");
}
else {
return s;
}
}
truncateString("This string is too long", 11);
//"This str..."
You're accessing the .length property on the wrong object. (You're asking for the number length instead of the string length). This means your if statement's primary condition never executes, and the function returns the whole string every time.
I believe you have at least one error on the logic. Instead of comparing s with n.length, you need to compare str/s length with num/n.
And I think what you were trying to use is the conditional ternary operator ?:
The next is a modified version of yours.
function truncateString(str, num)
{
var s = str;
var n = num;
return (s.length > n) ? s.slice(0, n - 3).concat("...") : s;
}
alert(truncateString("This string is too long", 11));
Variable 'n' holds a primitive value but not an object.That's why there is no 'length' property of variable 'n'. So n.length statement returns 'undefined' value. Finally s > n.length statement returns false and if block never executes. You could use s.length instead.Here 's' holds string value and string is also primitive value in JavaScript but at run time string value converts into its wrapper String Object whenever you try to access any property of it including length property.
I am attempting to write a JavaScript function, OneLetterOff, that will take in a String, and an Array of accepted words (WordList).
It should return an array of words from the WordList that only differ from the word given in the String by only one letter, at a single position.
For example:
WordList = ["marc", "bark", "parc", "shark", "mark"];
OneLetterOff("park", WordList); // should return ["bark", "parc", "mark"]
Words that pass the test have to be of the same length, and we can safely assume they are all lower case letters.
How do I use Regular Expressions to solve this algorithm? Essentially, are there ways other than having to use Regular Expressions to solve it?
Thank you so much for your help.
Regular expressions are not the best for it but to give you an idea:
"mark".match(/.ark|p.rk|pa.k|par./) //true
You can, of course, build regular expressions automatically and just "." might not be what you are looking for, depending on the possible characters you need to include.
I suggest you figure out the rest on your own as it looks a lot like homework ;-)
There are many non-regexp ways to solve it. For short words pre-compiled regexp will probably be the most efficient though.
You are looking for words in a list with a Levenshtein distance of 1 from a given word.
As found at Algorithm Implementation/Strings/Levenshtein distance, a JavaScript implementation of the algorithm is as follows:
function levenshteinDistance (s, t) {
if (s.length === 0) return t.length;
if (t.length === 0) return s.length;
return Math.min(
levenshteinDistance(s.substr(1), t) + 1,
levenshteinDistance(t.substr(1), s) + 1,
levenshteinDistance(s.substr(1), t.substr(1)) + (s[0] !== t[0] ? 1 : 0)
);
};
Using that method with Array.prototype.filter (polyfill needed for IE<9) to include only items with a distance of 1, we get a very simple bit of code:
var oneLetterOff = function (word, list) {
return list.filter(function (element) {
return levenshteinDistance(word, element) === 1;
});
};
oneLetterOff('park', ['marc', 'bark', 'parc', 'shark', 'mark']);
// returns ["bark", "parc", "mark"]
One great feature to this approach is that it works for any distance--just change what you're comparing to in the filter.
If you really wanted to use regular expressions (which I would not recommend for this), you would need to:
Iterate the given word to create a set of strings representing regular expression subpatterns where each has one char optional
Combine those string subpatterns into a regular expression using new RegExp()
Iterate the list of words testing them against the expresison
When you get a match, add it to a set of matches
Return the set of matches
It wouldn't take long to write, but given the answer I gave above I think you'll agree it would be a silly approach.
Here is my solution inspired by JAAuide and using all the power of JavaScript functions
function lDist (s, t) {
/* If called with a numeric `this` value
returns true if Levenshtein distance between strings s and t <= this
else
returns the Levenshtein distance between strings s and t */
return this.constructor === Number ? lDist.call (null, s, t) <= this :
s.length && t.length
? Math.min (lDist (s.slice (1), t) + 1,
lDist (t.slice (1), s) + 1,
lDist (s.slice (1), t.slice (1)) + (s.charAt (0) !== t.charAt (0)))
: (s.length || t.length) };
['marc', 'bark', 'parc', 'shark', 'mark'].filter (lDist.bind (1, 'park'));
See the jsFiddle
In javascript:
"Id".localeCompare("id")
will report that "id" is bigger. I want to do ordinal (not locale) compare such that "Id" is bigger. This is similar to String.CompareOrdinal in C#. How can I do it?
I support the answers given by Raymond Chen and pst. I will back them up with documentation from my favorite site for answers to JavaScript questions -- The Mozilla Developer Network. As an aside, I would highly recommend this site for any future JavaScript questions you may have.
Now, if you go to the MDN section entitled String, under the section "Comparing strings", you will find this description:
C developers have the strcmp() function for comparing strings. In JavaScript, you just use the less-than and greater-than operators:
var a = "a";
var b = "b";
if (a < b) // true
print(a + " is less than " + b);
else if (a > b)
print(a + " is greater than " + b);
else
print(a + " and " + b + " are equal.");
A similar result can be achieved using the localeCompare method inherited by String instances.
If we were to use the string "Id" for a and "id" for b then we would get the following result:
"Id is less than id"
This is the same result that Yaron got earlier when using the localeCompare method. As noted in MDN, using the less-than and greater-than operators yields similar results as using localeCompare.
Therefore, the answer to Yaron's question is to use the less-than (<) and greater-than (>) operators to do an ordinal comparison of strings in JavaScript.
Since Yaron mentioned the C# method String.CompareOrdinal, I would like to point out that this method produces exactly the same results as the above JavaScript. According to the MSDN C# documentation, the String.CompareOrdinal(String, String) method "Compares two specified String objects by evaluating the numeric values of the corresponding Char objects in each string." So the two String parameters are compared using the numeric (ASCII) values of the individual characters.
If we use the original example by Yaron Naveh in C#, we have:
int result = String.CompareOrdinal("Id", "id");
The value of result is an int that is less than zero, and is probably -32 because the difference between "I" (0x49) and "i" (0x69) is -0x20 = -32. So, lexically "Id" is less than "id", which is the same result we got earlier.
As Raymond noted (and explained) in a comment, an "ordinal" non-locale aware compare is as simple as using the various equality operators on strings (just make sure both operands are strings):
"a" > "b" // false
"b" > "a" // true
To get a little fancy (or don't muck with [[prototype]], the function is the same):
String.prototype.compare = function (a, b) {
return ((a == b ? 0)
? (a > b : 1)
: -1)
}
Then:
"a".compare("b") // -1
Happy coding.
Just a guess: by inverting case on all letters?
function compareOrdinal(ori,des){
for(var index=0;index<ori.length&&index<des.length;index++){
if(des[index].charCodeAt(0)<ori[index].charCodeAt(0)){
return -1;
break;
}
}
if(parseInt(index)===des.length-1){
return 0;
}
return 1;
}
compareOrdinal("idd","id");//output 1
if you need to compare and find difference between two string, please check this:
function findMissingString() {
var str1 = arguments[0];
var str2 = arguments[1];
var i = 0 ;
var j = 0 ;
var text = '' ;
while(i != (str1.length >= str2.length ? str1.length : str2.length )) {
if(str1.charAt(i) == str2.charAt(j)) {
i+=1 ;
j+=1;
} else {
var indexing = (str1.length >= str2.length ? str1.charAt(i) : str2.charAt(j));
text = text + indexing ;
i+=1;
j+=1;
}
}
console.log("From Text = " + text);
}
findMissingString("Hello","Hello world");