草庐IT

java - 有 3 个容器(2 个满的和 1 个空的)并尝试从中创建 x 数量

coder 2024-04-01 原文

注意:遇到下面这个问题,想把问题归纳并实现,结果发现并不容易。这个问题让我发疯。这不是家庭作业问题,只是出于好奇。

问题

There are three containers whose sizes are 10 pints, 7 pints and 4 pints respectively. The 7-pint and 4-pint containers start out full of water, but the 10-pint container is initially empty.

Since there are no marks on the containers, you can pour the contents of one container into another and stop under the following conditions:

  1. the source container is empty
  2. the destination container is full

What sequence of moves should you make if you want to isolate exactly 2 pints of water?

Source: page 102, Question 3.8

解决方案

使用 directed graph data structure 很容易回答这个问题其中节点包含 tuples代表某种状态。

我们从初始状态(节点)开始,然后我们创建一个代表可能的下一个状态的节点,我们将它连接到初始节点,然后运行 ​​BFS寻找最短路径。

  • 每个状态(或节点)的模式:<10-pint container, 7-pint container, 4-pint container>

  • 初始状态或节点:<0, 7, 4> .

连接到初始状态(或节点)的节点:<7, 0, 4> , <4, 7, 0> , 正如您从图片中看到的那样。

一般性问题

But suppose if want to generalized the problem, suppose we have three containers whose sizes are x, y and z pints respectively such that x >= y >= z.

The y-pint and z-pint containers start out full of water but the x-pint container is initially empty.

What sequence of moves should you make if you want to isolate exactly a pints of water?

建议通用版本的解决方案

这里 ( DropBox , GitHub ) 是我目前的源代码。

这是主类中的两个重要方法。他们根据所有可能性填充图形,并且还确保没有重复节点。

public static void fillGraph(int x, int y, int z) {

    TupleContainer initialState = new TupleContainer(x, y, z);
    TupleContainer currentState = initialState;
    Iterator<TupleContainer> it, it_1, it_2, it_3;
    Graph.addNode(initialState);

    it = addAdjacentEdgesToTuple(currentState).iterator();
    while (it.hasNext()) {
        it_1 = addAdjacentEdgesToTuple(it.next()).iterator();
        while (it_1.hasNext()) {
            it_2 = addAdjacentEdgesToTuple(it.next()).iterator();
            while (it_2.hasNext()) {
                it_3 = addAdjacentEdgesToTuple(it.next()).iterator();
                while (it_3.hasNext()) {
                    addAdjacentEdgesToTuple(it.next()).iterator();
                }
            }
        }
    }

public static Collection<TupleContainer> addAdjacentEdgesToTuple(
        TupleContainer currentState) {
    TupleContainer tempTupleContainer;
    Collection<TupleContainer> CollectionLevel;
    Iterator<TupleContainer> it;

    CollectionLevel = currentState.MixUpContainers();
    it = CollectionLevel.iterator();

    while (it.hasNext()) {
        tempTupleContainer = it.next();
        if (graphContains(tempTupleContainer) != null)
            Graph.addNode(tempTupleContainer);
        else
            tempTupleContainer = graphContains(tempTupleContainer);
        Graph.addEdge(currentState, tempTupleContainer);
    }
    return CollectionLevel;
}

我的问题

我的代码只是将图形填充到 4 的深度,但我如何设置深度并使其递归运行,或者如何使其运行直到考虑所有可能性而不进入无限循环。这个通用问题的算法是什么?

最佳答案

嗯...可能有更好的算法,但如果你只是想任意深度递归而不进入无限循环,你可以使用广度优先搜索只访问每个节点一次,即如果它还没有被访问过:

public class Test {

    public static void main(String[] args) throws Exception {
        State initialState = new State(null, 0, 7, 4);

        Set<State> reached = new HashSet<>();
        Queue<State> pending = new ArrayDeque<>();
        pending.add(initialState);
        while (!pending.isEmpty()) {
            State state = pending.remove();

            if (isGoal(state)) {
                printPathTo(state);
                return;
            }

            for (State s : state.adjacentStates()) {
                if (!reached.contains(s)) {
                    reached.add(s);
                    pending.add(s);
                }
            }
        }

        System.out.println("There appears to be no solution.");
    }

    private static boolean isGoal(State state) {
        for (int a : state.content) {
            if (a == 2) {
                return true;
            }
        }
        return false;
    }

    private static void printPathTo(State state) {
        if (state != null) {
            printPathTo(state.previous);
            System.out.println(state);
        }
    }
}

class State {

    final static int[] capacity = { 10, 7, 4 };

    final int[] content;
    final State previous;

    public State(State previous, int... content) {
        this.content = content;
        this.previous = previous;
    }

    Iterable<State> adjacentStates() {
        List<State> result = new ArrayList<>();
        for (int i = 0; i < content.length; i++) {
            for (int j = 0; j < content.length; j++) {
                if (i != j) {
                    int[] newContent = Arrays.copyOf(content, content.length);
                    int movedQuantity = Math.min(content[i], capacity[j] - content[j]);
                    newContent[i] -= movedQuantity;
                    newContent[j] += movedQuantity;
                    result.add(new State(this, newContent));
                }
            }
        }
        return result;
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(content);
    }

    @Override
    public boolean equals(Object obj) {
        return Arrays.equals(content, ((State) obj).content);
    }

    @Override
    public String toString() {
        return Arrays.toString(content);
    }
}

关于java - 有 3 个容器(2 个满的和 1 个空的)并尝试从中创建 x 数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27347915/

有关java - 有 3 个容器(2 个满的和 1 个空的)并尝试从中创建 x 数量的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  3. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  4. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  5. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  6. ruby - 如何使用 RSpec::Core::RakeTask 创建 RSpec Rake 任务? - 2

    如何使用RSpec::Core::RakeTask初始化RSpecRake任务?require'rspec/core/rake_task'RSpec::Core::RakeTask.newdo|t|#whatdoIputinhere?endInitialize函数记录在http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/RakeTask#initialize-instance_method没有很好的记录;它只是说:-(RakeTask)initialize(*args,&task_block)AnewinstanceofRake

  7. ruby - 为什么 SecureRandom.uuid 创建一个唯一的字符串? - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?

  8. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  9. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

  10. ruby - 有人可以帮助解释类创建的 post_initialize 回调吗 (Sandi Metz) - 2

    我正在阅读SandiMetz的POODR,并且遇到了一个我不太了解的编码原则。这是代码:classBicycleattr_reader:size,:chain,:tire_sizedefinitialize(args={})@size=args[:size]||1@chain=args[:chain]||2@tire_size=args[:tire_size]||3post_initialize(args)endendclassMountainBike此代码将为其各自的属性输出1,2,3,4,5。我不明白的是查找方法。当一辆山地自行车被实例化时,因为它没有自己的initialize方法

随机推荐