My Learning Blog

Using array destructuring to swap elements-733 - 2/18/2024

using array method on string

773:On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.

The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].

Given the puzzle board board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.

Input: board = [[1,2,3],[4,0,5]] Output: 1 Explanation: Swap the 0 and the 5 in one move.

function slidingPuzzle(board: number[][]): number {
    const start: string = board.flat().join('');
    const target: string = '123450';
    const moves = [
         [1, 3],
         [0, 2, 4],
         [1, 5],
         [0, 4],
         [1, 3, 5],
         [2, 4]
    ];

    const queue:[string,number,number][] = [[start, start.indexOf('0'), 0]];
    const visited: Set<string> = new Set([start]);

    while (queue.length > 0) {
        const [state, zeroIndex, moveCount] = queue.shift()!;
        if (state === target) {
            return moveCount; //
        }

        // Generate and enqueue all possible states from the current state
        for (const move of moves[zeroIndex]) {
            const newState: string[] = state.split('');
            [newState[zeroIndex], newState[move]] = [newState[move], newState[zeroIndex]]; // Swap zero with the neighbor
            const newStringState: string = newState.join('');
            if (!visited.has(newStringState)) {
                visited.add(newStringState);
                queue.push([newStringState, move, moveCount + 1]);
            }
        }
    }

    return -1;

The .flat() method in JavaScript and TypeScript is used to create a new array by flattening input arrays into a new array. This method is particularly useful when dealing with arrays of arrays (nested arrays) and you want to merge them into a single array.

const arr2 = [1, 2, [3, 4, [5, 6]]];
console.log(arr2.flat());
// Output with default depth: [1, 2, 3, 4, [5, 6]]

console.log(arr2.flat(2));
// Output with depth of 2: [1, 2, 3, 4, 5, 6]

The indexOf() method in JavaScript and TypeScript is used to search for a specific element within an array or a substring within a string and returns the first index at which a given element can be found. If the element or substring is not found, it returns -1.

const fruits = ["apple", "banana", "cherry", "date"];
console.log(fruits.indexOf("banana")); // Output: 1

onst greeting = "Hello, world!";
console.log(greeting.indexOf("world")); // Output: 7
console.log(greeting.indexOf("World")); // Output: -1 (case-sensitive search)
console.log(greeting.indexOf("o"));     // Output: 4 (first occurrence)
console.log(greeting.indexOf("o", 5));  // Output: 8 (search starting from index 5)