Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Tuesday, April 19, 2016

Recursive string reversal function in javascript?

Recursive string reversal function in javascript?


I'm a pretty experienced frontend engineer with a weak CS background. I'm trying to get my head around the concept of recursion. Most of the examples and purported explanations I can find just aren't explaining it in a way I find easy to understand.

I set myself a task of writing a function that will reverse a string recursively. I know there has to be a base condition (i.e. the solution is found), but I can't figure out how to actually write something like this and could use a demo to study.

Could someone provide a sample function?

Answer by Development 4.0 for Recursive string reversal function in javascript?


This is a pretty straightforward C# implementation of the algorithm you asked for. I think it could be rewritten in javascript pretty easily.

/*  C#: The Complete Reference   by Herbert Schildt     Publisher: Osborne/McGraw-Hill (March 8, 2002)  ISBN: 0072134852  */      // Display a string in reverse by using recursion.     using System;     class RevStr {       // Display a string backwards.     public void displayRev(string str) {       if(str.Length > 0)          displayRev(str.Substring(1, str.Length-1));       else          return;         Console.Write(str[0]);     }   }     public class RevStrDemo {     public static void Main() {         string s = "this is a test";       RevStr rsOb = new RevStr();         Console.WriteLine("Original string: " + s);         Console.Write("Reversed string: ");       rsOb.displayRev(s);         Console.WriteLine();     }   }  

Answer by Tom for Recursive string reversal function in javascript?


Something like:

function reverse (str) {      if (str === "") {          return "";      } else {          return reverse(str.substr(1)) + str.charAt(0);      }  }  

So the function is recursive as it calls itself to do the work.

Answer by Gerrat for Recursive string reversal function in javascript?


Try this(untested):

def resurse(s) {      if (s.length == 0) {        return '' // stopping condition      } else {  // return last char + result of function called with chars up to last char        return s.substring(s.length, s.length -1) + recurse(s.substring(1, s.length -1))    }    

Answer by maerics for Recursive string reversal function in javascript?


A tail recursive version, just for kicks (even though JavaScript doesn't perform tail call elimination):

function reverse(str) {    function r(s, acc) {      return (s.length == 0) ? acc : r(s.substr(1), s.charAt(0) + acc);    };    return r(str, '');  };  

Answer by Jonathan Borthwick for Recursive string reversal function in javascript?


It is verbose, but I like making it easy to understand in logical steps:

function rev(soFar, count){     console.log("asString: " + soFar );     console.log("count: " + count);     var len = soFar.length;     var ret = soFar;//ret needs to be a reference to soFar     if(len > count){        var subd = soFar.substring(1,len);        var first = soFar[0];        //we want to inject the first letter at the index position one back from the length, minus what the count is at this point        var indexOfInsert = len-1 - count;//so if count is 0 and length is 5, we want 4 (4 -0)        var asArray = subd.split("");        asArray.splice(indexOfInsert,0,first);        count++;//need to increment count for the next round        var asString = "";      //recreate as string, not array - the default toString() makes this a comma delimited string. It is best toi just recreate it in a loop      for(var i = 0; i

}

Then call it like:

var reversed = rev("Hello",0);  console.log("result",reversed);  

Answer by qweszxcj for Recursive string reversal function in javascript?


So far the best I think:

function reverse(s) {      if (s.length===1) return s;      return reverse(s.slice(1)) + s[0];  }  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.