2

var n = "reversestrings", k=3;

want to reverse string in chunk of 'k',

Answer would be : ver sre tse nir gs;

if Last word less then 'k' then don't need to reverse.

I am using below code but not getting expected answer.

var n = 'stringreverses', k = 3, str = '', s = '';
    var c = 0;
    for( var i=0; i<n.length; i++ ){
        if( c<k ){
            c++
            str += n[i];
            s=str.split('').reverse().join('');
        }
        else{
            console.log("-" + s);
            c=0;
        }
    }
5
  • Why not start at the end of the string, and work backwards? Commented Apr 27, 2017 at 9:56
  • LOL @AtaurRahmanMunna, you got it right :) Commented Apr 27, 2017 at 9:59
  • 1
    Homework questions are allowed. The OP has shown their effort. Commented Apr 27, 2017 at 9:59
  • 1
    @AtaurRahmanMunna if you guys have answer could you answer for same Commented Apr 27, 2017 at 10:01
  • 1
    @evolutionxbox read the link meta.stackoverflow.com/questions/334822/… Commented Apr 27, 2017 at 10:03

5 Answers 5

1

First we need to split input to chunks with the same size (the last one can be smaller), next we reverse every chunk and concatenate at the end.

var input = "123456",
    chunks = input.match(new RegExp('.{1,' + k + '}', 'g'));

var result = chunks.map(function(chunk) {
    return chunk.split('').reverse().join(''); 
}).join('');
Sign up to request clarification or add additional context in comments.

1 Comment

This is not taking care of the condition that if 2 or 1 characters are left they shall not be reversed.
0

Homework or not, here is a good use case to start with strings.

Here is a C approach but you have more in Javascript.

In fact you want to reverse by chunk so deal with chunk. How to create a chunk of string ? a way is to use slice https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/slice

var str = "abcdef";
console.log(str.slice(0,2));

So you have an easy way to slice your string into chunk.

Then you have to iterate over it, there is no good way of doing it actually there is dozen but you could do it from backward to the beginning of the string:

for( i=str.length ; i>0 ; i -= k ){
    // i will go from the end of your str to
    // the beginning by step of k(=3) and you can use i - k and i 
    // to slice your string (as we see it before)
    // you have to take care of the last part that could be less than 
    // 3
}

then you have to format the result, the most easy way to do that is to concatenate results into a string here it is :

var strRes = "";
strRes += "res 1";
strRes += "res 2";
console.log(strRes); // should screen "res 1res 2"

As it is homework, I wont make a jsfiddle, you have here all the pieces and it's up to you to build the puzzle.

hope that help

Comments

0

$(function() {
	var n = 'reversestrings', k = 3;
    var revString = "";
    for (var i =0; i<=n.length; i++) {
		if (i%k == 0) {
			 l = parseInt(k) + parseInt(i);
			 var strChunk = n.substring(i,l);
			 var innerStr = "";
			 for (var j =0; j<strChunk.length; j++) {
				 var opp = parseInt(strChunk.length) - parseInt(j) - 1;
				 innerStr = innerStr + strChunk.charAt(opp);
			}
			revString = revString + " "+innerStr;
		}
	}
    alert(revString);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

2 Comments

Pass the 'n' variable value and 'k' variable value what ever you want and see the output. Revert me in case of any issue
Really, jQuery?
0

My take on this. Pure JS without even built-in functions:

    function reverseSubStr(str) {
      var right = str.length - 1, reversedSubStr = '';
      while(right >= 0) {
        reversedSubStr += str[right];
        right--;  
      }
      return reversedSubStr;
    }

    function reverseStr(str) {
      var initialStr = str, newstr = '', k = 3, substr = ''
      for(var i = 1; i <= initialStr.length; i++) {
        substr += initialStr[i - 1]; // form a substring
        if(i % k == 0) { // once there are 3 symbols - reverse the substring
          newstr += reverseSubStr(substr) + " "; // ... and add space
          substr = ''; // then clean temp var
        }
      }
      return newstr += substr; // add the remainder of the string - 'gs' - and return the result
    }
  var str = 'reversestrings';
  console.log(reverseStr(str)); //ver sre tse nir gs

Comments

0

I like @Jozef 's approch but here is mine as well for those who are not much into Regex -

//Taking care of Tail Calling
function reverStrInChunk(str, k, r=''){
 let index=0, revStr,
 res = str.substring(index, k), remStr;
 
 revStr = res.split("").reverse().join("");
 
remStr = str.substring(k, str.length);

r = r + revStr; 


if(remStr.length>k){ 
 
 return reverStrInChunk(remStr,k, r+" ");
 }
else if(remStr.length<k) {

return r +" "+remStr;
}else{

  return r +" "+ remStr.split("").reverse().join("");
}
}

var aStr = reverStrInChunk('reversestrings',3);//ver sre tse nir gs

console.log(aStr);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.