Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Reverse a string with numbers, but don't reverse 1 and 0?

I am learning random algorithms, and I am currently stock in one, where I have to reverse a string that contains numbers, but I am not to reverse 1 and 0 in the string e.g, 2345678910 would be 1098765432.

Here's what I've done so far:

function split(str) {
  let temp = [];
  temp = str.split('');
  const backwards = [];
  const totalItems = str.length - 1;
  for (let i = totalItems; i >= 0; i--) {
    backwards.push(temp[i]);

  }
  return backwards.join('').toString();

}
console.log(split("10 2 3 U S A"));
console.log(split("2345678910"));

I am currently having the issue of not reversing the 10.

What am I doing wrong?

like image 419
user8107351 Avatar asked Jan 23 '19 15:01

user8107351


3 Answers

You can replace 10 with a specified character which does not exist in the text, and after running the implemented algorithm replace it back with 10.

let out_of_alphabet_character = '#';
var reg_for_the_alphabet = new RegExp(out_of_alphabet_character, "g");

function specific_revert(str) {
  str = str.replace(/(10)/g, out_of_alphabet_character);
  let temp = [];
  
  temp = str.split('');
  const backwards = [];
  const totalItems = str.length - 1;
  for (let i = totalItems; i >= 0; i--) {
    backwards.push(temp[i]);
  }
  return backwards.join('').toString().replace(reg_for_the_alphabet, '10');
}
console.log(specific_revert("10 2 3 U S A"));
console.log(specific_revert("234567891010"));
like image 121
OmG Avatar answered Nov 01 '22 09:11

OmG


You can reduce over the matched array from using a regular expression. It's more costly than a for/loop that concatenates strings, but it was fun figuring it out.

function split(str) {
  const re = /([A-Z23456789 ]+)|(10)/g
  return str.match(re).reduce((acc, c) => {

    // if the match is 10 prepend it to the accumulator
    // otherwise reverse the match and then prepend it
    acc.unshift(c === '10' ? c : [...c].reverse().join(''));
    return acc;      
  }, []).join('');
}

console.log(split('2345678910'));
console.log(split('10 2 3 U S A'));
console.log(split('2 3 U S A10'));
like image 4
Andy Avatar answered Nov 01 '22 10:11

Andy


Just check for the special case & code the normal logic or reversing as usual

    const reverse = str => {
    	let rev = "";
    	for (let i = 0; i < str.length; i++) {
        	if (str[i] === '1' && i + 1 < str.length && str[i+1] === '0') {
            	rev = '10' + rev;
                i++;
            } else rev = str[i] + rev;
        }
        
        return rev;
    }
    
    console.log(reverse("10 2 3 U S A")); // returns A S U 3 2 10
    console.log(reverse("2345678910")); // returns 1098765432
like image 3
Danyal Imran Avatar answered Nov 01 '22 09:11

Danyal Imran