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

org.psjava.algo.math.optimization.MemoizationFactory Maven / Gradle / Ivy

package org.psjava.algo.math.optimization;

import org.psjava.ds.map.MutableMap;
import org.psjava.ds.map.MutableMapFactory;
import org.psjava.ds.set.MutableSet;
import org.psjava.ds.set.MutableSetFactory;

public class MemoizationFactory {

	private MutableMapFactory mapFactory;
	private MutableSetFactory setFactory;

	public MemoizationFactory(MutableMapFactory mapFactory, MutableSetFactory setFactory) {
		this.mapFactory = mapFactory;
		this.setFactory = setFactory;
	}

	public  Memoization create(final MemoizationFunction f) {
		final MutableMap table = mapFactory.create();
		final MutableSet inStack = setFactory.create();
		return new Memoization() {
			@Override
			public O get(I input) {
				if (inStack.contains(input))
					throw new IllegalArgumentException("The function calls infinite recursion. check the logic.");
				inStack.insert(input);
				O v = table.get(input, null);
				if (v == null) {
					v = f.get(input, this);
					table.put(input, v);
				}
				inStack.remove(input);
				return v;
			}
		};
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy