All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.dieterdepaepe.jsearch.problem.npuzzle.PuzzleSearchNodeGenerator Maven / Gradle / Ivy

There is a newer version: 1.0.1
Show newest version
package com.github.dieterdepaepe.jsearch.problem.npuzzle;

import com.github.dieterdepaepe.jsearch.datastructure.lightweight.SingleLinkedListing;
import com.github.dieterdepaepe.jsearch.search.constructive.Heuristic;
import com.github.dieterdepaepe.jsearch.search.constructive.InformedSearchNode;
import com.github.dieterdepaepe.jsearch.search.constructive.SearchNodeGenerator;

import java.util.ArrayList;
import java.util.List;

/**
 * Implementation of {@code SearchNodeGenerator} for solving the N-Puzzle problem.
 * @author Dieter De Paepe
 */
public class PuzzleSearchNodeGenerator implements SearchNodeGenerator {
    @Override
    public List> generateSuccessorNodes(PuzzleSearchNode node, PuzzleEnvironment environment, Heuristic heuristic) {
        List> result = new ArrayList<>(4);
        PuzzleFields startingFieldsState = node.getPuzzleFields();

        for (Move move : Move.values()) {
            PuzzleFields movedFieldsState = environment.getPuzzle().move(startingFieldsState, move);

            //Skip if the move had no effect
            if (movedFieldsState == startingFieldsState)
                continue;

            //Construct the new search node by adding one extra move
            PuzzleSearchNode newNode = new PuzzleSearchNode(
                    movedFieldsState,
                    node.getMoves().extend(move),
                    node.getMovesPerformed() + 1,
                    environment.getTargetState().equals(movedFieldsState));

            //Add heuristic information to the search node
            result.add(new InformedSearchNode<>(newNode, heuristic.estimateRemainingCost(newNode, environment)));
        }

        return result;
    }

    public PuzzleSearchNode createStartState(PuzzleFields fieldState, PuzzleEnvironment environment) {
        return new PuzzleSearchNode(fieldState, SingleLinkedListing.of(), 0, environment.getTargetState().equals(fieldState));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy