How to resolve the algorithm Bulls and cows/Player step by step in the D programming language

Published on 12 May 2024 09:40 PM
#D

How to resolve the algorithm Bulls and cows/Player step by step in the D programming language

Table of Contents

Problem Statement

Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equivalent score to how your last guess was scored. Your next guess can be any number from the pruned list. Either you guess correctly or run out of numbers to guess, which indicates a problem with the scoring.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Bulls and cows/Player step by step in the D programming language

Source code in the d programming language

void main() {
    import std.stdio, std.random, std.algorithm, std.range, std.ascii;

    immutable d9 = "123456789";
    auto choices = cartesianProduct(d9, d9, d9, d9).map!(t => [t[]])
                   .filter!(a => a.sort().uniq.count == 4).array;

    do {
        const ans = choices[uniform(0, $)];
        writef("My guess is %s. How many bulls and cows? ", ans);
        immutable score = readln.filter!isDigit.map!q{ a - '0' }.array;
        choices = choices.remove!(c => score !=
            [c.zip(ans).count!(p => p[0] == p[1]),
             c.zip(ans).count!(p => p[0] != p[1] && ans.canFind(p[0]))]);
    } while (choices.length > 1);

    if (choices.empty)
        return "Nothing fits the scores you gave.".writeln;
    writeln("Solution found: ", choices[0]);
}


  

You may also check:How to resolve the algorithm Accumulator factory step by step in the 8th programming language
You may also check:How to resolve the algorithm User input/Text step by step in the hexiscript programming language
You may also check:How to resolve the algorithm Call a foreign-language function step by step in the zkl programming language
You may also check:How to resolve the algorithm Bitmap/Bézier curves/Quadratic step by step in the Delphi programming language
You may also check:How to resolve the algorithm RSA code step by step in the ALGOL 68 programming language