Skip to main content

Featured Post

Your First Programming Language

What programming language you start with really all depends on where you want to go with programming/coding. The great thing about this field is that there are an absolute abundance of smaller fields that you can go into, all using programming in their own unique ways. For web applications, a good start would be with HTML and later moving your way through CSS, JavaScript, JQuery, PHP, SQL, and any of the JavaScript libraries. Ruby is also a popular choice, so I would recommend checking that out too. For more scientific fields or areas with more machine learning and A.I., Python is generally a great place to start as it is widely used in that field of study. C++ is also a very useful language to know for that, but it can be a little more challenging for beginners. For game and application design, languages such as C#, C, Swift, Kotlin, and Java are most often used for that.

Cricket Scoring

Description
Cricket is a bat-and-ball game played between two teams of 11 players each on a field at the centre of which is a rectangular pitch. The game is played by 120 million players in many countries, making it the world's second most popular sport!

There are 2 batsmen standing on two bases and the ball is played to the strike base. Batsmen run between their bases to increases their 'runs'. If a batsman gets out, a new batsman arrives to their base.
This is only a simplified version of the rules

Let's look at a typical score: 1.2wW6.2b34
There are 5 types of characters:

(number) - The player on strike acquires this many runs to his name.
'.' - A dot ball. No runs.
'b' - A bye, 1 run to the team but not to any particular batsman.
'w' - A wide, 1 run to the team but not to any particular batsman.
The difference between 'w' and 'b' is that a 'b' counts as a ball but 'w' is not a legal ball.

'W' - Strike batsman is out. A new player takes his place, if there is any player left to play out of 11 available. If not, the innings is complete.

Additional Rules:

If the striker scores an odd number, that means he reaches the other base and the batsmen have exchanged their base. If he scores 2, he runs twice and comes back to the same base.
The batsmen exchange their bases after 6 legal balls called an over, that means a 'w' doesn't count as a ball. So a score like '1..2.www' is still one over as it has only 5 legal balls.
Formal Inputs & Outputs
Input description
Ball by Ball Score, a line of string. For example:

1.2wW6.2b34
Output description
Individual scores of batsman that have played and number of extras. For example:

 P1: 7 
 P2: 2 
 P3: 9 
 Extras: 2 
Explanation : P1 hits a 1, P2 a dot ball, P2 hits a 2, Wide, P2 is Out (P3 in place on P2), P3 hits a 6, P3 a dot ball, New Over (P1 on strike), P1 hits a 2, Bye (P3 on strike), P3 hits a 3, P1 hits a 4

Challenge input
WWWWWWWWWW 
1..24.w6 

Solution
in C++


#include <iostream>
#include <array>
#include <string>



constexpr int number_of_players_on_team = 11;

class GameState
{
    struct Player
    {
        std::string name;
        int score;
        Player() : score{ 0 } {}
    };

    std::array<Player, number_of_players_on_team> players;
    std::size_t striking_player_index;
    std::size_t non_striking_player_index;
    int ball;
    int extras;

    std::size_t latest_in() const
    {
        return std::max(striking_player_index, non_striking_player_index);
    }

    std::pair<std::size_t,bool> next_in() const
    {
        if (latest_in() == (players.size() - 1))
        {
            // No more players can take the crease.
            return std::make_pair(0xeff0eff0, false);
        }
        else
        {
            return std::make_pair(latest_in() + 1, true);
        }
    }

    void switch_ends()
    {
        std::swap(striking_player_index, non_striking_player_index);
    }

    bool is_in(std::size_t player_index) const
    {
        return (player_index == striking_player_index) || (player_index == non_striking_player_index);
    }

    bool is_out(std::size_t player_index) const
    {
        return (player_index <= latest_in()) && !is_in(player_index);
    }

    void runs_check_ends(int n_runs)
    {
        if ((n_runs % 2) != 0)
        {
            switch_ends();
        }
    }

public:

    GameState() : striking_player_index{ 0 }, non_striking_player_index{ 1 }, ball{ 0 }, extras{ 0 } {}

    void set_player_name(std::string&& name, std::size_t order) // 1st out, 2nd out, etc... (NOT ZERO INDEXED!)
    {
        players[order - 1].name = std::move(name);
    }

    void legal_ball()
    {
        ++ball;
        if (ball >= 6)
        {
            switch_ends();
            ball = 0;
        }
    }

    void score_runs(int n_runs)
    {
        players[striking_player_index].score += n_runs;
        runs_check_ends(n_runs);
        legal_ball();
    }

    void dot_ball()
    {
        score_runs(0);
    }

    void bye(int n_runs = 1)
    {
        extras += n_runs;
        runs_check_ends(n_runs);
        legal_ball();
    }

    void wide()
    {
        ++extras;
    }

    // Returns true if another batsman takes the crease, false if this ends the innings.
    bool wicket()
    {

        const auto next = next_in();
        striking_player_index = next.first;
        legal_ball();
        return next.second;
    }

    void print_score(std::ostream& oss)
    {
        for (std::size_t i = 0; i < number_of_players_on_team; ++i)
        {
            if (is_in(i) || is_out(i))
            {
                oss << players[i].name << ": " << players[i].score;
                if (is_in(i))
                {
                    // Indicate which batters are still in.
                    oss << '*';
                }
                oss << '\n';
            }
        }
        oss << "Extras: " << extras << '\n';
    }

    std::string striking_player() const
    {
        return players[striking_player_index].name;
    }

    int ball_in_over() const
    {
        return ball;
    }
};

int main()
{
    GameState game;

    // Set up player names.
    for (std::size_t index = 0; index < number_of_players_on_team; ++index)
    {
        const std::size_t order = index + 1;
        game.set_player_name(std::string{ "P" } +std::to_string(order), order);
    }

    std::string input;
    std::getline(std::cin, input);
    for (char ball : input)
    {
#ifdef DEBUG_INFO
        std::cout << game.striking_player() << " is on strike. Ball in over: " << game.ball_in_over() << " Ball: " << ball << "\n";
#endif
        switch (ball)
        {
        case '.':
            game.dot_ball();
            break;
        case 'b':
            game.bye();
            break;
        case 'w':
            game.wide();
            break;
        case 'W':
            game.wicket();
            break;
        default:
            game.score_runs(ball - '0');
            break;
        }
    }
    game.print_score(std::cout);
    std::cin.get();
}

Challenge outputs:

P1: 0
P2: 0
P3: 0
P4: 0
P5: 0
P6: 0
P7: 0
P8: 0*
P9: 0
P10: 0
P11: 0
Extras: 0
and:

P1: 7*
P2: 6*
Extras: 1

Comments

Popular posts from this blog

Decipher A Seven Segment Display

Description Today's challenge will be to create a program to decipher a seven segment display, commonly seen on many older electronic devices. Input Description For this challenge, you will receive 3 lines of input, with each line being 27 characters long (representing 9 total numbers), with the digits spread across the 3 lines. Your job is to return the represented digits. You don't need to account for odd spacing or missing segments. Output Description Your program should print the numbers contained in the display. Challenge Inputs     _  _     _  _  _  _  _   | _| _||_||_ |_   ||_||_|   ||_  _|  | _||_|  ||_| _|     _  _  _  _  _  _  _  _ |_| _| _||_|| ||_ |_| _||_   | _| _||_||_| _||_||_  _|  _  _  _  _  _  _  _  _  _ |_  _||_ |_| _|  ||_ | ||_|  _||_ |_||_| _|  ||_||_||_|  _  _        _  _  _  _  _ |_||_ |_|  || ||_ |_ |_| _|  _| _|  |  ||_| _| _| _||_ Challenge Outputs 123456789 433805825 526837608 954105592 Solution in Go package mai

Continued Fraction

Description In mathematics, a continued fraction is an expression obtained through an iterative process of representing a number as the sum of its integer part and the reciprocal of another number, then writing this other number as the sum of its integer part and another reciprocal, and so on. A continued fraction is an expression of the form             1     x + ----------                1         y + -------                   1             z + ----                  ... and so forth, where x, y, z, and such are real numbers, rational numbers, or complex numbers. Using Gauss notation, this may be abbreviated as [x; y, z, ...] To convert a continued fraction to an ordinary fraction, we just simplify from the right side, which may be an improper fraction, one where the numerator is larger than the denominator. Continued fractions can be decomposed as well, which breaks it down from an improper fraction to its Gauss notation. For example: 16        1 -- = 0 + --- 45

Kolakoski Sequence

Description A Kolakoski sequence (A000002) is an infinite sequence of symbols {1, 2} that is its own run-length encoding. It alternates between "runs" of symbols. The sequence begins: 12211212212211211221211212211... The first three symbols of the sequence are 122, which are the output of the first two iterations. After this, on the i-th iteration read the value x[i] of the output (one-indexed). If i is odd, output x[i] copies of the number 1. If i is even, output x[i] copies of the number 2. There is an unproven conjecture that the density of 1s in the sequence is 1/2 (50%). In today's challenge we'll be searching for numerical evidence of this by tallying the ratio of 1s and 2s for some initial N symbols of the sequence. Input Description As input you will receive the number of outputs to generate and tally. Output Description As output, print the ratio of 1s to 2s in the first n symbols. Sample Input 10 100 1000 Sample Output 5:5 49:51 502:498

Advanced pacman

Description This challenge takes its roots from the world-famous game Pacman. To finish the game, pacman needs to gather all pacgum on the map. The goal of this chalenge is to have a time-limited pacman. Pacman must gather as much pacgum as possible in the given time. To simplify, we will say that 1 move (no diagonals) = 1 unit of time. Formal Inputs & Outputs Input description You will be given a number, the time pacman has to gather as much pacgum as possible, and a table, being the map pacman has to explore. Every square of this map can be one of those things : A number N between (1 and 9) of pacgums that pacman can gather in one unit of time. "X" squares cannot be gone through. "C" will be where pacman starts. "O" (the letter, not zero ) will be a warp to another "O". There can be only 2 "O" on one map; Output description Your program should output the maximum number of pacgums pacman can gather in the given t

Puzzle Me This

Description First they took our jerbs, now they're taking our puzzles! (with your help) Today we're gonna find a way to solve jigsaw puzzles using computers Input Description As I am no designer the input will be purely numerical, feel free to make some visual version of the jigsaw puzzles :) You will first be given the dimension as X, Y Afterwards you will be given list of puzzle pieces and what type their 4 sides connect to (given as up, right, down, left) Their side-connection is given as a number, They connect with their negated number this means that a 1 and -1 connects, 2 and -2 connects etc. 0 means that it doesnt connect with anything. Assume pieces are rotated in the correct direction. fx: 2, 2 0: 0,1,2,0 1: 0,0,2,-1 2: -2,0,0,2 3: -2,-2,0,0 Output Description Output is a 2D picture/matrix of the pieces in their correct position for the example this would be 0 1 3 2 Challenge Input Challenges are generated, so there is a slight chanc

Everyone's A Winner

Description Today's challenge comes from the website fivethirtyeight.com, which runs a weekly Riddler column. Today's dailyprogrammer challenge was the riddler on 2018-04-06. From Matt Gold, a chance, perhaps, to redeem your busted bracket: On Monday, Villanova won the NCAA men’s basketball national title. But I recently overheard some boisterous Butler fans calling themselves the “transitive national champions,” because Butler beat Villanova earlier in the season. Of course, other teams also beat Butler during the season and their fans could therefore make exactly the same claim. How many transitive national champions were there this season? Or, maybe more descriptively, how many teams weren’t transitive national champions? (All of this season’s college basketball results are here. To get you started, Villanova lost to Butler, St. John’s, Providence and Creighton this season, all of whom can claim a transitive title. But remember, teams beat those teams, too.) Outp

Star Battle solver

Background Star Battle is a grid-based logic puzzle. You are given a SxS square grid divided into S connected regions, and a number N. You must find the unique way to place N*S stars into the grid such that: Every row has exactly N stars. Every column has exactly N stars. Every region has exactly N stars. No two stars are horizontally, vertically, or diagonally adjacent. If you would like more information: Star Battle rules and info YouTube tutorial and written tutorial of solving Star Battle puzzles by hand There are many Star Battle puzzles available on Grandmaster Puzzles. Just be aware that some are variants that follow different rules. Challenge Write a program to solve a Star Battle puzzle in a reasonable amount of time. There's no strict time requirement, but you should run your program through to completion for at least one (N, S) = (2, 10) puzzle for it to count as a solution. Feel free to use whatever input/output format is most convenient for you. In the