Search code examples
javascriptarraysalgorithmreverse

Can't find a solution for array reverse algorithm problem


I have a requirement where I have to reverse an array without changing the index of '#' presents in an array, like below example:

  • Array [18,-4,'#',0,8,'#',5] should return [5, 8, "#", 0, -4, "#", 18], here numbers should be reversed, excluding '#' while keeping the same index.

I have tried to get the correct output, but it doesn't seem to be correct in all scenarios: var arr = [18,-4,'#',0,8,'#',5]; // giving result is correct var arr1 = [18,-4,0,'#',8,'#',5]; // result is not correct

var reverse = function(numbers, start, end){
	var temp = numbers[start];
  numbers[start] = numbers[end];
  numbers[end] = temp;
}
var flip = function(numbers) {
var start = 0;
var end = numbers.length-1;
	for(var i=0;i<parseInt(numbers.length/2);i++) {
  	if(numbers[i] === '#') {
    	start = i+1;
      end = numbers.length - i - i;
      reverse(numbers, start, end);
    } else if (numbers[numbers.length - i - 1] === '#') {
    	start = i;
      end = numbers.length - i - 2;
      reverse(numbers, start, end);
    } else {
    	reverse(numbers, start, end);
    }
  }
  return numbers;
}

var arr = [18,-4,'#',0,8,'#',5];
var arr1 = [18,-4,0,'#',8,'#',5];
console.log(flip(arr));
console.log(flip(arr1));


Solution

  • You could simplify the function and use only two indices, the start and end and check if the value at the indices should stay, then choose another index for swapping.

    const
        swap = (array, a, b) => [array[a], array[b]] = [array[b], array[a]],
        flip = numbers => {
            var start = 0,
                end = numbers.length - 1;
    
            while (start < end) {
                if (numbers[start] === '#') {
                    start++;
                    continue;
                }
                if (numbers[end] === '#') {
                    end--;
                    continue;
                }
                swap(numbers, start++, end--);
            }
            return numbers;
        },
        array1 = [18, -4, '#', 0, 8, '#', 5],
        array2 = [18, -4, 0, '#', 8, '#', 5];
    
    console.log(...flip(array1));
    console.log(...flip(array2));