Code Monkey home page Code Monkey logo

classiccomputerscienceproblemsinjava's People

Contributors

davecom avatar jeffmorin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

classiccomputerscienceproblemsinjava's Issues

Difficulty with the backtracking algorithm

  • I don't understant how the following code works:
  • In particular, I have difficulties with the function backtrackingSearch
// CSP.java
// From Classic Computer Science Problems in Java Chapter 3
// Copyright 2020 David Kopec
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package chapter3;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CSP<V, D> {
	private List<V> variables;
	private Map<V, List<D>> domains;
	private Map<V, List<Constraint<V, D>>> constraints = new HashMap<>();

	public CSP(List<V> variables, Map<V, List<D>> domains) {
		this.variables = variables;
		this.domains = domains;
		for (V variable : variables) {
			constraints.put(variable, new ArrayList<>());
			if (!domains.containsKey(variable)) {
				throw new IllegalArgumentException("Every variable should have a domain assigned to it.");
			}
		}
	}

	public void addConstraint(Constraint<V, D> constraint) {
		for (V variable : constraint.variables) {
			if (!variables.contains(variable)) {
				throw new IllegalArgumentException("Variable in constraint not in CSP");
			}
			constraints.get(variable).add(constraint);
		}
	}

	// Check if the value assignment is consistent by checking all constraints
	// for the given variable against it
	public boolean consistent(V variable, Map<V, D> assignment) {
		for (Constraint<V, D> constraint : constraints.get(variable)) {
			if (!constraint.satisfied(assignment)) {
				return false;
			}
		}
		return true;
	}

	public Map<V, D> backtrackingSearch(Map<V, D> assignment) {
		// assignment is complete if every variable is assigned (our base case)
		if (assignment.size() == variables.size()) {
			return assignment;
		}
		// get the first variable in the CSP but not in the assignment
		V unassigned = variables.stream().filter(v -> !assignment.containsKey(v)).findFirst().get();
		// get the every possible domain value of the first unassigned variable
		for (D value : domains.get(unassigned)) {
			// shallow copy of assignment that we can change
			Map<V, D> localAssignment = new HashMap<>(assignment);
			localAssignment.put(unassigned, value);
			// if we're still consistent, we recurse (continue)
			if (consistent(unassigned, localAssignment)) {
				Map<V, D> result = backtrackingSearch(localAssignment);
				// if we didn't find the result, we will end up backtracking
				if (result != null) {
					return result;
				}
			}
		}
		return null;
	}

	// helper for backtrackingSearch when nothing known yet
	public Map<V, D> backtrackingSearch() {
		return backtrackingSearch(new HashMap<>());
	}
}

  • in backtrackingSearch the line
    V unassigned = variables.stream().filter(v -> !assignment.containsKey(v)).findFirst().get(); will return the same v value
    • before I call recursively backtrackingSearch
    • and after I comme back from the recursive call of backtrackingSearch especially when that call returns null

Error in constructor of Gene class -- Listing 2.4 on page 29

Listing 2.4 on page 29:

// BUG: this code contains an error -- fails to read last three characters of string
for (int i = 0; i < geneStr.length() - 3; i += 3) {
    codons.add(new Codon(geneStr.substring(i, i + 3)));
}
// Here is an example of a corrected version:
final int len = geneStr.length();
final int partitionSize = 3;
for (int i = 0; i < len; i += partitionSize) {
    codons.add(new Codon(geneStr.substring(i, Math.min(len, i + partitionSize))));
}
// Test case that fails with original implementation
Codon ttt = new Codon("TTT");
System.out.println(myGene.linearContains(ttt)); // true
System.out.println(myGene.binaryContains(ttt)); // true

Note: I would recommend to only update this code on GitHub, as clearly this is being used to read in sample input data for the algorithm.

Book really needs some code update

Found a bunch of code errors on Chapter 2, and seems that they have been fixed here, would be nice to have the book updated to reflect the code.

For instance Node<MazeLocation> solution1 = GenericSearch.dfs(m.start, m::goalTest, m::successors); start property is final.

Glad to see that the enum switch was also replaced by proper enum declaration ...

Simplify CSP when all variables have the same domain

Hi,
You can simplify code for your samples, by adding an additional constructor which assigns the same domain to all variables.

public CSP(List<V> variables, List<D> domain) {
     assert variables != null;
     assert domain != null;

     this.variables = variables;
     this.domains = new HashMap<>();

     for (V variable : variables) {
         domains.put(variable, domain);
         constraints.put(variable, new ArrayList<>());
     }
 }

The creation of the CSP for MapColouringConstraint will reduce to

final CSP<String, String> csp = new CSP<>(variables, List.of("red", "green", "blue"));

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.