Peter McNulty
Peter McNulty

Reputation: 99

Trying to duplicate and then concatenate each item of an array to itself

So I have an array acting like a map that looks something like this:

......#...........#...#........
.#.....#...##.......#.....##...
......#.#....#.................
..............#.#.......#......
.....#.#...##...#.#..#..#..#..#
.......##...#..#...........#...
.......#.##.#...#.#.........#..
..#...##............##......#.#
.......#.......##......##.##.#.
...#...#........#....#........#
#............###.#......#.....#
..#........#....#..#..........#
..#..##....#......#..#......#..
........#......#......#..#..#..
..#...#....#..##.......#.#.....
.....#.#......#..#....#.##.#..#
.... and so on

The challenge I'm doing asks me to repeat the pattern to the right many times (doesn't specify how much)

I used the split() function to make an array with each line as an item, and I had a stab at duplicating and concatenating each array item with the following code:


TreeMap = treeMapFile.split('\n')

 function ExtraTreeMap(map) { 
   
 for (i=0; i<map; i++) {
       map[i] = map[i].concat(map[i])
}
return map
 }

FinalMap = ExtraTreeMap(TreeMap)

But it just returns the same Array...

Any ideas/help would be much appreciated!

Upvotes: 0

Views: 49

Answers (1)

Nick
Nick

Reputation: 16576

You're pretty close. Here's a solutiont that uses map[i] += map[i] since map[i] itself is just a string. Also, it joins with a newline character at the end, assuming the output should once again be a string.

const treeMapFile = `......#...........#...#........
.#.....#...##.......#.....##...
......#.#....#.................
..............#.#.......#......
.....#.#...##...#.#..#..#..#..#
.......##...#..#...........#...
.......#.##.#...#.#.........#..
..#...##............##......#.#
.......#.......##......##.##.#.
...#...#........#....#........#
#............###.#......#.....#
..#........#....#..#..........#
..#..##....#......#..#......#..
........#......#......#..#..#..
..#...#....#..##.......#.#.....
.....#.#......#..#....#.##.#..#`;

function extraTreeMap(treeMap) { 
  const map = treeMap.split('\n')
  for (let i = 0; i < map.length; i++) {
    map[i] += map[i];
  }
  return map.join('\n');
}

const finalMap = extraTreeMap(treeMapFile);

console.log(finalMap);

Upvotes: 1

Related Questions