Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function hackTAS(S) {
- console.time()
- // get the row length
- w = S[0].length + 1
- // join board rows to 1d array with a wall ('#') to deny horizonthal moves between rows
- S = S.join`#`
- // add an id to each item indexed by the it's coordinates
- // if there is more than 9 items, then extend the id with some separator for example: ':'
- T = {}
- id = 1
- for (i = 0; i < S.length; i++)
- if (!"# SE".includes(S[i])) {
- T[i] = id + ':'
- id++
- }
- // initial board. key is "0"
- B = [Buffer(S)]
- // initial queue: [position, board key (or mask), hitpoint, level (or move count), fish]
- Q = [[S.indexOf('S'), "0", 1, 0, 0]]
- // directions for simple moves and with fish moves
- D = [[[-w],[-1],[1],[w]],
- [[-w,-2*w],[-1,-2,-3],[1,2,3],[w,2*w]]
- ]
- // process the queue
- for ([p, m, h, s, f] of Q) {
- // debug
- //console.log("p", p, "m", m, "s", s, "h", h, f ? "fish": "");
- //(B[m] + "").match(RegExp(".{"+w+"}", "g")).map(s => console.log(s))
- // loop on the four direction ULRD
- for (i of D[f]) {
- // keep the original variables
- mm = m
- hh = h
- ff = f
- // loop on moves in distance (the reason, fish can move 1,2,3 cells horizontally and 1,2 in vertically)
- for (j of i) {
- // get cell value
- v = B[m][j += p]
- // check the exit point
- if (v == 69){
- console.timeEnd()
- return s + 1
- }
- // check special items 'B', 'C', 'D', 'F'
- if (v > 43) {
- // unknow item then stop (for example 'S', we came back to the start point)
- if (!T[j]) break;
- // item 'D'
- if (v == 68) {
- // if hitpoint == 1 then increase hp
- hh += hh < 2
- // item 'F'
- } else if (v == 70) {
- // set fish flag
- ff = 1
- // item 'B'
- } else if (v == 66) {
- // decrease hp if no fish
- hh -= f == 0
- // item 'C'
- } else if (v == 67) {
- // unset fish if we have or decrease hitpoint
- ff ? ff = 0
- : hh--
- }
- // stop this thread, if we died, hp == 0
- if (hh == 0)
- break
- // add the new item id to the board key
- mmm = mm + T[j]
- // clone the current board to the new (if we don't have board with new key)
- // and clear visited cells (we can move freely to anywhere again)
- mmm in B
- ? 0
- : B[mmm] = Buffer((B[mm] + "").replace(/\+/g, ' '))
- mm = mmm
- // set cell to visited ('+')
- B[mm][j] = 43
- // add position to the queue
- Q.push([j, mm, hh, s + 1, ff])
- if (ff == 0) break
- // empty cell, ' '. we can move freely
- } else if (v == 32) {
- // set cell to visited ('+')
- B[mm][j] = 43
- // add position to the queue
- Q.push([j, mm, hh, s + 1, ff])
- // wall, '#'
- } else if (v < 43)
- // stop moving in this direction
- break
- }
- }
- }
- console.timeEnd()
- return -1
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement