Home > Blockchain >  How to fill String/Array with character recursion
How to fill String/Array with character recursion

Time:07-22

i have a little issue in JS-Code and I would appreciate your help So i have an Array like this:

let topMap= [
'................**********........................',
'...............*..........*.......................',
'..........*****............*........*.............',
'.........*.................*.......*.*....*****...',
]

Now i can fill a Line in this map with character '*'. I split this Array in to a String, set a character at position and transfer back in to Array.

const getCharFromArrayPosition = (x, y) => topMap[x][y]

const replaceChar = (x,y) => { 
topMap= topMap.map(x => x.split(''))
topMap[x][y] = char
topMap = topMap.map(x => x.join(''))
}

const floodFill = (x,y) => {

    if(getCharFromArrayPosition(x,y) !== char){
        replaceChar(x,y)
        floodFill(x,y 1)
    }
    return topMap 
}

So if i console.log(floodFill(0,0) i get this

  '**************************........................',
  '...............*..........*.......................',
  '..........*****............*........*.............',
  '.........*.................*.......*.*....*****...',

I am filling the y-position and it is okey but, how can i fill the x-position too with recursion? Or in other words how to fill from one character to other ? thank you

CodePudding user response:

Right now, your recursion is only going in a single direction - to the right.

floodFill(x, y   1)

Recurse in all directions instead. You'll also need to keep track of indicies visited to avoid endless recursion. An array of arrays may be easier to work with than an array of strings, too.

const topMap = [
  '................**********........................',
  '...............*..........*.......................',
  '..........*****............*........*.............',
  '.........*.................*.......*.*....*****...',
].map(str => [...str]);

const visited = new Set();
const floodFill = (y, x) => {
  const key = y   '_'   x;
  if (visited.has(key) || topMap[y]?.[x] === undefined || topMap[y][x] !== '.') {
    return;
  }
  visited.add(key);
  topMap[y][x] = '*';
  floodFill(y, x   1);
  floodFill(y, x - 1);
  floodFill(y   1, x);
  floodFill(y - 1, x);
}
floodFill(0, 0);
console.log(topMap.map(subarr => subarr.join('')));

  • Related