问:
Find all the Solutions to this Number Puzzle in the Shortest Time Possible

History

My company sends out a weekly newsletter to everyone within the company. Included in these newsletters is a riddle, along with a shoutout to whomever in the company was the first to email/provide a solution to last week's riddle. Most of these riddles are quite trivial, and honestly pretty dull for a tech company, but there was one, several months back, that caught my attention.

The Original Riddle:

Given the shape below:

You have the Natural Numbers from 1 to 16. Fit them all into this shape, such that all the contiguous rows and contiguous columns sum up to 29.

For example, one such solution to this puzzle (which was the "canonical" solution I submitted to the newsletter) was the following:

However, in the course of solving it, I found some rather interesting information:

There are significantly more solutions than just that one; in fact, there are 9,368 Solutions.

If you expand the ruleset to only require that rows and columns be equal to each other, not necessarily 29, you get 33,608 solutions:

4,440 Solutions for a sum of 27.

7,400 Solutions for a sum of 28.

9,368 Solutions for a sum of 29.

6,096 Solutions for a sum of 30.

5,104 Solutions for a sum of 31.

1,200 Solutions for a sum of 32.

So me and my coworkers (though mostly just my manager, since he was the only other person than me with "General Purpose" programming skills) set out on a challenge, that lasted for most of the month—we had other, actual job-related obligations we had to attend to—to try to write a program which would find every single solution in the fastest way possible.

Original Statistics

The very first program I wrote to solve the problem simply checked random solutions over and over, and stopped when it found a solution. If you've done Mathematical analysis on this problem, you probably already know that this shouldn't have worked; but somehow I got lucky, and it took the program only a minute to find a single solution (the one I posted above). Repeat runs of the program often took as much as 10 or 20 minutes, so obviously this wasn't a rigorous solution to the problem.

I switched over to a Recursive Solution which iterated through every possible permutation of the puzzle, and discarded lots of solutions at once by eliminating sums that weren't adding up. I.E. if the first row/column I was comparing already weren't equal, I could stop checking that branch immediately, knowing that nothing else permuted into the puzzle would change that.

Using this algorithm, I got the first "proper" success: the program could generate and spit out all 33,608 solutions in about 5 minutes.

My manager had a different approach: knowing based on my work that the only possible solutions had sums of 27, 28, 29, 30, 31, or 32, he wrote a multi-threaded solution which checked possible sums only for those specific values. He managed to get his program to run in only 2 minutes. So I iterated again; I hashed all possible 3/4 digit sums (at the start of the program; it's counted in the total runtime) and used the "partial sum" of a row to look-up the remaining value based on a previously completed row, rather than testing all remaining values, and brought the time down to 72 seconds. Then with some multi-threading logic, I got it down to 40 seconds. My manager took the program home, performed some optimizations on how the program ran, and got his down to 12 seconds. I reordered the evaluation of the rows and columns, and got mine down to 8 seconds.

The fastest either of us got our programs after a month was 0.15 seconds for my manager, and 0.33 seconds for me. I ended up claiming that my program was faster though, since my manager's program, while it did find all solutions, wasn't printing them out into a text file. If he added that logic to his code, it often took upwards of 0.4-0.5 seconds.

We've since allowed our intra-personal challenge to subsist, but of course, the question remains: can this program be made faster?

That's the challenge I'm going to pose to you guys.

Your Challenge

The parameters we worked under relaxed the "sum of 29" rule to instead be "all rows/columns' sums equal", and I'm going to set that rule for you guys too. The Challenge, therefore, is: Write a program that finds (and Prints!) all solutions to this riddle in the shortest time possible. I'm going to set a ceiling on submitted solutions: If the program takes more than 10 seconds on a relatively decent computer (<8 years old), it's probably too slow to be counted.

Also, I have a few Bonuses for the puzzle:

Can you generalize the solution so that it works for any set of 16 numbers, not just int[1,16]? Timing score would be evaluated based on the original prompt number set, but passed through this codepath. (-10%)

Can you write the code in a way that it gracefully handles and solves with duplicate numbers? This isn't as straightforward as it might seem! Solutions which are "visually identical" should be unique in the result set. (-5%)

Can you handle negative numbers? (-5%)

You can also try to generate a solution that handles Floating-Point Numbers, but of course, don't be shocked if that fails utterly. If you do find a robust solution though, that might be worth a large bonus!

For all intents and purposes, "Rotations" are considered to be unique solutions. So a solution that is just a rotation of a different solution counts as its own solution.

The IDEs I have working on my computer are Java and C++. I can accept answers from other languages, but you may need to also provide a link to where I can get an easy-to-setup runtime environment for your code.

答:
C++ - 300 Milliseconds

Per request, I've added my own code to solve this puzzle. On my computer, it clocks in at an average of 0.310 seconds (310 milliseconds) but depending on variance can run as quickly as 287 milliseconds. I very rarely see it rise above 350 milliseconds, usually only if my system is bogged down with a different task.

These times are based on the self-reporting used in the program, but I also tested using an external timer and get similar results. Overhead in the program seems to add about 10 milliseconds.

Also, my code doesn't quite handle duplicates correctly. It can solve using them, but it doesn't eliminate "visually identical" solutions from the solution set.

```<code>#include<iostream>
#include<vector>
#include<random>
#include<functional>
#include<unordered_set>
#include<unordered_map>
#include<array>
#include<thread>
#include<chrono>
#include<fstream>
#include<iomanip>
#include<string>
#include<mutex>
#include<queue>
#include<sstream>
#include<utility>
#include<atomic>
#include<algorithm>

//#define REDUCE_MEMORY_USE

typedef std::pair<int, std::vector<std::pair<int, int>>> sumlist;
typedef std::unordered_map<int, std::vector<std::pair<int, int>>> summap;
typedef std::array<int, 16> solution_space;

class static_solution_state {
public:
    std::array<int, 16> validNumbers;
    summap twosums;
    size_t padding;
    std::string spacing;

    static_solution_state(const std::array<int, 16> & _valid);

    summap gettwovaluesums();
    std::vector<sumlist> gettwovaluesumsvector();
};

static_solution_state::static_solution_state(const std::array<int, 16> & _valid)
    : validNumbers(_valid) {
    twosums = gettwovaluesums();
    padding = 0;
    for (int i = 0; i < 16; i++) {
        size_t count = std::to_string(validNumbers[i]).size();
        if (padding <= count) padding = count + 1;
    }
    spacing.resize(padding, ' ');
}

class solution_state {
private:
    const static_solution_state * static_state;
public:
    std::array<int, 16> currentSolution;
    std::array<bool, 16> used;
    std::array<int, 7> sums;
    size_t solutions_found;
    size_t permutations_found;
    size_t level;
    std::ostream * log;

    solution_state(const static_solution_state & _sstate);
    solution_state(static_solution_state & _sstate) = delete;
    void setLog(std::ostream & out);
    const int & operator[](size_t index) const;

};

solution_state::solution_state(const static_solution_state & _sstate) {
    static_state = &_sstate;
    sums = { 0 };
    used = { false };
    currentSolution = { -1 };
    solutions_found = 0;
    permutations_found = 0;
    level = 0;
}

void solution_state::setLog(std::ostream & out) {
    log = &out;
}

const int & solution_state::operator[](size_t index) const {
    return static_state->validNumbers[currentSolution[index]];
}

int getincompletetwosum(const static_solution_state & static_state, const solution_state & state);
void permute(const static_solution_state & static_state, solution_state & state, volatile bool & reportProgress, const volatile size_t & total_tests, volatile bool & done);
void setupOutput(std::fstream & out);
void printSolution(const static_solution_state & static_state, const solution_state & state);
constexpr size_t factorial(const size_t iter);

const bool findnext2digits[16]{
    false, false, false,
    true, false,
    false, true, false,
    true, false,
    true, false,
    true, false,
    true, false
};

const int currentsum[16]{
    0, 0, 0,
    1, 1,
    2, 2, 2,
    3, 3,
    4, 4,
    5, 5,
    6, 6
};

const int twosumindexes[7][2]{
    { 0, -1},
    { 2, -1},
    { 5, -1},
    { 5, -1},
    { 0,  7},
    { 11, 4},
    { 10, 9}
};

const std::array<size_t, 17> facttable = [] {
    std::array<size_t, 17> table;
    for (int i = 0; i < 17; i++) table[i] = factorial(i);
    return table;
}();

const int adj = 1;

std::thread::id t1id;

int main(int argc, char** argv) {
    //std::ios_base::sync_with_stdio(false);
    std::array<int, 16> values = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 };
    if (argc == 17) {
        for (int i = 0; i < 16; i++) {
            values[i] = atoi(argv[i + 1]);
        }
    }
    auto start = std::chrono::high_resolution_clock::now();
    const static_solution_state static_state(values);
#if defined(REDUCE_MEMORY_USE)
    const int num_of_threads = max(1u, min(thread::hardware_concurrency(), 16u));
#else
    const int num_of_threads = 16;
#endif
    std::vector<solution_state> states(num_of_threads, static_state);
    for (int i = 0; i < num_of_threads; i++) {
        int start = i * 16 / num_of_threads;
        states[i].permutations_found += start * factorial(16) / 16;
    }
    std::fstream out;
    setupOutput(out);
    std::locale loc("");
    std::cout.imbue(loc);
    volatile bool report = false;
    volatile bool done = false;
    volatile size_t tests = 0;

    std::thread progress([&]() {
        auto now = std::chrono::steady_clock::now();
        while (!done) {
            if (std::chrono::steady_clock::now() - now > std::chrono::seconds(1)) {
                now += std::chrono::seconds(1);

                size_t t_tests = 0;
                for (int i = 0; i < num_of_threads; i++) t_tests += states[i].permutations_found - i * factorial(16) / num_of_threads;
                tests = t_tests;
                report = true;
            }
            std::this_thread::yield();
        }
    });

    if (num_of_threads <= 1) {

        states[0].setLog(out);
        permute(static_state, states[0], report, tests, done);

    }
    else {
        std::vector<std::thread> threads;
#if defined(REDUCE_MEMORY_USE)
        std::vector<std::fstream> logs(num_of_threads);
#else
        std::vector<std::stringstream> logs(num_of_threads);
#endif
        for (int i = 0; i < num_of_threads; i++) {
            threads.emplace_back([&, i]() {
                if (i == 0) t1id = std::this_thread::get_id();
                int start = i * 16 / num_of_threads;
                int end = (i + 1) * 16 / num_of_threads;
#if defined(REDUCE_MEMORY_USE)
                logs[i].open("T"s + to_string(i) + "log.tmp", ios::out);
#endif
                logs[i].imbue(loc);
                states[i].setLog(logs[i]);

                for (int j = start; j < end; j++) {

                    states[i].currentSolution = { j };
                    states[i].level = 1;
                    states[i].used[j] = true;
                    permute(static_state, states[i], report, tests, done);

                }
            });
        }

        std::string buffer;
        for (int i = 0; i < num_of_threads; i++) {
            threads[i].join();
#if defined(REDUCE_MEMORY_USE)
            logs[i].close();
            logs[i].open("T"s + to_string(i) + "log.tmp", ios::in);
            logs[i].seekg(0, ios::end);
            auto length = logs[i].tellg();
            logs[i].seekg(0, ios::beg);
            buffer.resize(length);
            logs[i].read(&buffer[0], length);
            logs[i].close();
            remove(("T"s + to_string(i) + "log.tmp").c_str());
            out << buffer;
#else
            out << logs[i].str();
#endif
        }
    }
    done = true;
    out.close();

    if (num_of_threads > 1) {
        size_t t_tests = 0;
        for (int i = 0; i < num_of_threads; i++) t_tests += states[i].permutations_found - i * factorial(16) / num_of_threads;
        tests = t_tests;
    }

    size_t solutions = 0;
    for (const auto & state : states) {
        solutions += state.solutions_found;
    }

    auto end = std::chrono::high_resolution_clock::now();

    progress.join();

    auto duration = end - start;
    auto secondsDuration = std::chrono::duration_cast<std::chrono::milliseconds>(duration);
    std::cout << "Total time to process all " << tests << " results: " << std::setprecision(3) << std::setiosflags(std::ostream::fixed) << (secondsDuration.count()/1000.0) << "s" << "\n";
    std::cout << "Solutions found: " << solutions << std::endl;
    //system("pause");
    return 0;
}

void permute(const static_solution_state & static_state, solution_state & state, volatile bool & reportProgress, const volatile size_t & total_tests, volatile bool & done) {
    if (done) return;
    if (state.level >= 16) {
        if (reportProgress) {
            reportProgress = false;
            std::cout << "Current Status:" << "\n";
            std::cout << "Test " << total_tests << "\n";
            std::cout << "Contents: {";
            for (int i = 0; i < 15; i++) std::cout << std::setw(static_state.padding - 1) << state[i] << ",";
            std::cout << std::setw(static_state.padding - 1) << state[15] << "}" << "(Partial Sum: " << state.sums[0] << ")" << "\n";
            std::cout << "=====================" << "\n";
        }
        printSolution(static_state,state);
        state.solutions_found++;
        state.permutations_found++;
    }
    else {
        if (state.level == 3) state.sums[0] = state[0] + state[1] + state[2];

        if (!findnext2digits[state.level]) {
            for (int i = 0; i < 16; i++) {
                if (!state.used[i]) {
                    state.currentSolution[state.level] = i;
                    state.used[i] = true;
                    state.level++;
                    permute(static_state, state, reportProgress, total_tests, done);
                    state.level--;
                    state.used[i] = false;
                }
            }
        }
        else {
            int incompletetwosum = getincompletetwosum(static_state, state);
            if (static_state.twosums.find(incompletetwosum) == static_state.twosums.end()) {
                state.permutations_found += facttable[16 - state.level];
            }
            else {
                size_t successes = 0;
                const std::vector<std::pair<int, int>> & potentialpairs = static_state.twosums.at(incompletetwosum);
                for (const std::pair<int, int> & values : potentialpairs) {
                    if (!state.used[values.first] && !state.used[values.second]) {
                        state.currentSolution[state.level] = values.first;
                        state.currentSolution[state.level + 1] = values.second;
                        state.used[values.first] = true;
                        state.used[values.second] = true;
                        state.level += 2;
                        permute(static_state, state, reportProgress, total_tests, done);
                        state.level -= 2;
                        state.used[values.first] = false;
                        state.used[values.second] = false;

                        successes++;
                    }
                }
                state.permutations_found += facttable[16 - state.level - 2] * ((16 - state.level) * (15 - state.level) - successes);
            }
        }
    }
}

int getincompletetwosum(const static_solution_state & static_state, const solution_state & state) {
    int retvalue = state.sums[0];
    int thissum = currentsum[state.level];
    for (int i = 0; i < 2 && twosumindexes[thissum][i] >= 0; i++) {
        retvalue -= state[twosumindexes[thissum][i]];
    }
    return retvalue;
}

constexpr size_t factorial(size_t iter) {
    return (iter <= 0) ? 1 : iter * factorial(iter - 1);
}

void setupOutput(std::fstream & out) {
    out.open("puzzle.txt", std::ios::out | std::ios::trunc);
    std::locale loc("");
    out.imbue(loc);
}

void printSolution(const static_solution_state & static_state, const solution_state & state) {
    std::ostream & out = *state.log;
    out << "Test " << state.permutations_found << "\n";
    static const auto format = [](std::ostream & out, const static_solution_state & static_state, const solution_state & state, const std::vector<int> & inputs) {
        for (const int & index : inputs) {
            if (index < 0 || index >= 16) out << static_state.spacing;
            else out
                << std::setw(static_state.padding)
                << state[index];
        }
        out << "\n";
    };
    format(out, static_state, state, { -1, -1, -1,  0,  1,  2 });
    format(out, static_state, state, { 15,  9, 14, 10, -1,  3 });
    format(out, static_state, state, { -1,  8, -1, 11, 12,  4, 13 });
    format(out, static_state, state, { -1,  5,  6,  7});

    out << "Partial Sum: " << (state.sums[0]) << "\n";
    out << "=============================" << "\n";
}

summap static_solution_state::gettwovaluesums() {
    summap sums;
    for (int i = 0; i < 16; i++) {
        for (int j = 0; j < 16; j++) {
            if (i == j) continue;
            std::pair<int,int> values( i, j );
            int sum = validNumbers[values.first] + validNumbers[values.second];
            sums[sum].push_back(values);
        }
    }
    return sums;
}

std::vector<sumlist> static_solution_state::gettwovaluesumsvector() {
    std::vector<sumlist> sums;
    for (auto & key : twosums) {
        sums.push_back(key);
    }

    std::sort(sums.begin(), sums.end(), [](sumlist a, sumlist b) {
        return a.first < b.first;
    });
    return sums;
}
</code>```

Body:
C++ - 300 Milliseconds

Per request, I've added my own code to solve this puzzle. On my computer, it clocks in at an average of 0.310 seconds (310 milliseconds) but depending on variance can run as quickly as 287 milliseconds. I very rarely see it rise above 350 milliseconds, usually only if my system is bogged down with a different task.

These times are based on the self-reporting used in the program, but I also tested using an external timer and get similar results. Overhead in the program seems to add about 10 milliseconds.

Also, my code doesn't quite handle duplicates correctly. It can solve using them, but it doesn't eliminate "visually identical" solutions from the solution set.

#include<iostream>
#include<vector>
#include<random>
#include<functional>
#include<unordered_set>
#include<unordered_map>
#include<array>
#include<thread>
#include<chrono>
#include<fstream>
#include<iomanip>
#include<string>
#include<mutex>
#include<queue>
#include<sstream>
#include<utility>
#include<atomic>
#include<algorithm>

//#define REDUCE_MEMORY_USE

typedef std::pair<int, std::vector<std::pair<int, int>>> sumlist;
typedef std::unordered_map<int, std::vector<std::pair<int, int>>> summap;
typedef std::array<int, 16> solution_space;

class static_solution_state {
public:
    std::array<int, 16> validNumbers;
    summap twosums;
    size_t padding;
    std::string spacing;

    static_solution_state(const std::array<int, 16> & _valid);

    summap gettwovaluesums();
    std::vector<sumlist> gettwovaluesumsvector();
};

static_solution_state::static_solution_state(const std::array<int, 16> & _valid)
    : validNumbers(_valid) {
    twosums = gettwovaluesums();
    padding = 0;
    for (int i = 0; i < 16; i++) {
        size_t count = std::to_string(validNumbers[i]).size();
        if (padding <= count) padding = count + 1;
    }
    spacing.resize(padding, ' ');
}

class solution_state {
private:
    const static_solution_state * static_state;
public:
    std::array<int, 16> currentSolution;
    std::array<bool, 16> used;
    std::array<int, 7> sums;
    size_t solutions_found;
    size_t permutations_found;
    size_t level;
    std::ostream * log;

    solution_state(const static_solution_state & _sstate);
    solution_state(static_solution_state & _sstate) = delete;
    void setLog(std::ostream & out);
    const int & operator[](size_t index) const;

};

solution_state::solution_state(const static_solution_state & _sstate) {
    static_state = &_sstate;
    sums = { 0 };
    used = { false };
    currentSolution = { -1 };
    solutions_found = 0;
    permutations_found = 0;
    level = 0;
}

void solution_state::setLog(std::ostream & out) {
    log = &out;
}

const int & solution_state::operator[](size_t index) const {
    return static_state->validNumbers[currentSolution[index]];
}

int getincompletetwosum(const static_solution_state & static_state, const solution_state & state);
void permute(const static_solution_state & static_state, solution_state & state, volatile bool & reportProgress, const volatile size_t & total_tests, volatile bool & done);
void setupOutput(std::fstream & out);
void printSolution(const static_solution_state & static_state, const solution_state & state);
constexpr size_t factorial(const size_t iter);

const bool findnext2digits[16]{
    false, false, false,
    true, false,
    false, true, false,
    true, false,
    true, false,
    true, false,
    true, false
};

const int currentsum[16]{
    0, 0, 0,
    1, 1,
    2, 2, 2,
    3, 3,
    4, 4,
    5, 5,
    6, 6
};

const int twosumindexes[7][2]{
    { 0, -1},
    { 2, -1},
    { 5, -1},
    { 5, -1},
    { 0,  7},
    { 11, 4},
    { 10, 9}
};

const std::array<size_t, 17> facttable = [] {
    std::array<size_t, 17> table;
    for (int i = 0; i < 17; i++) table[i] = factorial(i);
    return table;
}();

const int adj = 1;

std::thread::id t1id;

int main(int argc, char** argv) {
    //std::ios_base::sync_with_stdio(false);
    std::array<int, 16> values = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 };
    if (argc == 17) {
        for (int i = 0; i < 16; i++) {
            values[i] = atoi(argv[i + 1]);
        }
    }
    auto start = std::chrono::high_resolution_clock::now();
    const static_solution_state static_state(values);
#if defined(REDUCE_MEMORY_USE)
    const int num_of_threads = max(1u, min(thread::hardware_concurrency(), 16u));
#else
    const int num_of_threads = 16;
#endif
    std::vector<solution_state> states(num_of_threads, static_state);
    for (int i = 0; i < num_of_threads; i++) {
        int start = i * 16 / num_of_threads;
        states[i].permutations_found += start * factorial(16) / 16;
    }
    std::fstream out;
    setupOutput(out);
    std::locale loc("");
    std::cout.imbue(loc);
    volatile bool report = false;
    volatile bool done = false;
    volatile size_t tests = 0;

    std::thread progress([&]() {
        auto now = std::chrono::steady_clock::now();
        while (!done) {
            if (std::chrono::steady_clock::now() - now > std::chrono::seconds(1)) {
                now += std::chrono::seconds(1);

                size_t t_tests = 0;
                for (int i = 0; i < num_of_threads; i++) t_tests += states[i].permutations_found - i * factorial(16) / num_of_threads;
                tests = t_tests;
                report = true;
            }
            std::this_thread::yield();
        }
    });

    if (num_of_threads <= 1) {

        states[0].setLog(out);
        permute(static_state, states[0], report, tests, done);

    }
    else {
        std::vector<std::thread> threads;
#if defined(REDUCE_MEMORY_USE)
        std::vector<std::fstream> logs(num_of_threads);
#else
        std::vector<std::stringstream> logs(num_of_threads);
#endif
        for (int i = 0; i < num_of_threads; i++) {
            threads.emplace_back([&, i]() {
                if (i == 0) t1id = std::this_thread::get_id();
                int start = i * 16 / num_of_threads;
                int end = (i + 1) * 16 / num_of_threads;
#if defined(REDUCE_MEMORY_USE)
                logs[i].open("T"s + to_string(i) + "log.tmp", ios::out);
#endif
                logs[i].imbue(loc);
                states[i].setLog(logs[i]);

                for (int j = start; j < end; j++) {

                    states[i].currentSolution = { j };
                    states[i].level = 1;
                    states[i].used[j] = true;
                    permute(static_state, states[i], report, tests, done);

                }
            });
        }

        std::string buffer;
        for (int i = 0; i < num_of_threads; i++) {
            threads[i].join();
#if defined(REDUCE_MEMORY_USE)
            logs[i].close();
            logs[i].open("T"s + to_string(i) + "log.tmp", ios::in);
            logs[i].seekg(0, ios::end);
            auto length = logs[i].tellg();
            logs[i].seekg(0, ios::beg);
            buffer.resize(length);
            logs[i].read(&buffer[0], length);
            logs[i].close();
            remove(("T"s + to_string(i) + "log.tmp").c_str());
            out << buffer;
#else
            out << logs[i].str();
#endif
        }
    }
    done = true;
    out.close();

    if (num_of_threads > 1) {
        size_t t_tests = 0;
        for (int i = 0; i < num_of_threads; i++) t_tests += states[i].permutations_found - i * factorial(16) / num_of_threads;
        tests = t_tests;
    }

    size_t solutions = 0;
    for (const auto & state : states) {
        solutions += state.solutions_found;
    }

    auto end = std::chrono::high_resolution_clock::now();

    progress.join();

    auto duration = end - start;
    auto secondsDuration = std::chrono::duration_cast<std::chrono::milliseconds>(duration);
    std::cout << "Total time to process all " << tests << " results: " << std::setprecision(3) << std::setiosflags(std::ostream::fixed) << (secondsDuration.count()/1000.0) << "s" << "\n";
    std::cout << "Solutions found: " << solutions << std::endl;
    //system("pause");
    return 0;
}

void permute(const static_solution_state & static_state, solution_state & state, volatile bool & reportProgress, const volatile size_t & total_tests, volatile bool & done) {
    if (done) return;
    if (state.level >= 16) {
        if (reportProgress) {
            reportProgress = false;
            std::cout << "Current Status:" << "\n";
            std::cout << "Test " << total_tests << "\n";
            std::cout << "Contents: {";
            for (int i = 0; i < 15; i++) std::cout << std::setw(static_state.padding - 1) << state[i] << ",";
            std::cout << std::setw(static_state.padding - 1) << state[15] << "}" << "(Partial Sum: " << state.sums[0] << ")" << "\n";
            std::cout << "=====================" << "\n";
        }
        printSolution(static_state,state);
        state.solutions_found++;
        state.permutations_found++;
    }
    else {
        if (state.level == 3) state.sums[0] = state[0] + state[1] + state[2];

        if (!findnext2digits[state.level]) {
            for (int i = 0; i < 16; i++) {
                if (!state.used[i]) {
                    state.currentSolution[state.level] = i;
                    state.used[i] = true;
                    state.level++;
                    permute(static_state, state, reportProgress, total_tests, done);
                    state.level--;
                    state.used[i] = false;
                }
            }
        }
        else {
            int incompletetwosum = getincompletetwosum(static_state, state);
            if (static_state.twosums.find(incompletetwosum) == static_state.twosums.end()) {
                state.permutations_found += facttable[16 - state.level];
            }
            else {
                size_t successes = 0;
                const std::vector<std::pair<int, int>> & potentialpairs = static_state.twosums.at(incompletetwosum);
                for (const std::pair<int, int> & values : potentialpairs) {
                    if (!state.used[values.first] && !state.used[values.second]) {
                        state.currentSolution[state.level] = values.first;
                        state.currentSolution[state.level + 1] = values.second;
                        state.used[values.first] = true;
                        state.used[values.second] = true;
                        state.level += 2;
                        permute(static_state, state, reportProgress, total_tests, done);
                        state.level -= 2;
                        state.used[values.first] = false;
                        state.used[values.second] = false;

                        successes++;
                    }
                }
                state.permutations_found += facttable[16 - state.level - 2] * ((16 - state.level) * (15 - state.level) - successes);
            }
        }
    }
}

int getincompletetwosum(const static_solution_state & static_state, const solution_state & state) {
    int retvalue = state.sums[0];
    int thissum = currentsum[state.level];
    for (int i = 0; i < 2 && twosumindexes[thissum][i] >= 0; i++) {
        retvalue -= state[twosumindexes[thissum][i]];
    }
    return retvalue;
}

constexpr size_t factorial(size_t iter) {
    return (iter <= 0) ? 1 : iter * factorial(iter - 1);
}

void setupOutput(std::fstream & out) {
    out.open("puzzle.txt", std::ios::out | std::ios::trunc);
    std::locale loc("");
    out.imbue(loc);
}

void printSolution(const static_solution_state & static_state, const solution_state & state) {
    std::ostream & out = *state.log;
    out << "Test " << state.permutations_found << "\n";
    static const auto format = [](std::ostream & out, const static_solution_state & static_state, const solution_state & state, const std::vector<int> & inputs) {
        for (const int & index : inputs) {
            if (index < 0 || index >= 16) out << static_state.spacing;
            else out
                << std::setw(static_state.padding)
                << state[index];
        }
        out << "\n";
    };
    format(out, static_state, state, { -1, -1, -1,  0,  1,  2 });
    format(out, static_state, state, { 15,  9, 14, 10, -1,  3 });
    format(out, static_state, state, { -1,  8, -1, 11, 12,  4, 13 });
    format(out, static_state, state, { -1,  5,  6,  7});

    out << "Partial Sum: " << (state.sums[0]) << "\n";
    out << "=============================" << "\n";
}

summap static_solution_state::gettwovaluesums() {
    summap sums;
    for (int i = 0; i < 16; i++) {
        for (int j = 0; j < 16; j++) {
            if (i == j) continue;
            std::pair<int,int> values( i, j );
            int sum = validNumbers[values.first] + validNumbers[values.second];
            sums[sum].push_back(values);
        }
    }
    return sums;
}

std::vector<sumlist> static_solution_state::gettwovaluesumsvector() {
    std::vector<sumlist> sums;
    for (auto & key : twosums) {
        sums.push_back(key);
    }

    std::sort(sums.begin(), sums.end(), [](sumlist a, sumlist b) {
        return a.first < b.first;
    });
    return sums;
}


问:
Calculate the Super-Logarithm
This should be a simple challenge.

Given a number \$n \ge 0\$, output the super-logarithm (or the \$\log^*\$, log-star, or iterated logarithm, which are equivalent since \$n\$ is never negative for this challenge.) of \$n\$.

$$\log^*(n) = \begin{cases}
0  & \text{ if } n \le 1 \\
1 + \log^*(\log(n)) & \text{ if } n > 1
\end{cases}$$

This is one of the two inverse functions to tetration. The other is the super-root, which is in a related question.

Examples

```<code>Input       Output
0           0
1           0
2           1
3           2
4           2
...
15          2
16          3
...
3814279     3
3814280     4
</code>```

Rules

You do not need to support decimals, though you may.

You need to support input of at least \$3814280 =  \left\lceil e^{e^e} \right\rceil\$.

You may not hard-code the values like 3814280. (Your program must theoretically support higher numbers.) I want an algorithm to be implemented.

Shortest code wins.

Related OEIS

答:
Mathematica, 29 bytes

Simple as all hell, and works for comically large as well as negative inputs:

```<code>f[x_]:=If[x>1,1+f[Log[x]],0]
</code>```

ContentLicense: CC BY-SA 4.0

Title: Calculate the Super-Logarithm

Body:
Mathematica, 29 bytes

Simple as all hell, and works for comically large as well as negative inputs:

f[x_]:=If[x>1,1+f[Log[x]],0]

ContentLicense: CC BY-SA 3.0


问:
Print numbers from 1 to 10
This might be a very simple challenge, but I am surprised it hasn't been done on code-golf yet:

Print all Integers from 1 to 10 inclusive in ascending order to standard output.

Your output format can be whatever your language supports. This includes arbitrary separators (commas, semicolons, newlines, combinations of those, etc., but no digits), and prefixes and postfixes (like [...]). However, you may not output any other numbers than 1 through 10. Your program may not take any input. Standard loopholes are disallowed.

This is code-golf, so shortest answer in bytes wins!

Leaderboard

var QUESTION_ID=86075,OVERRIDE_USER=42570;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
Common Lisp, 29 bytes

```<code>(dotimes(n 10)(print(+ n 1)))
</code>```

Title: Print numbers from 1 to 10

Body:
Common Lisp, 29 bytes

(dotimes(n 10)(print(+ n 1)))


问:
Print integers in any base up to 36

Possible Duplicate:

  Integer to string with given radix

This question is inspired by Pythons builtin int function. int is used to convert other numbers or strings into integers. If you are converting a string you can provide the additional parameter base, that contains the base that your number is represented in within the string:

```<code>>>> int('137')
137
>>> int('137',base=8)
95
>>> int('ff',base=16)
255
>>> int('1AZ',base=36)
1691
</code>```

Unfortunately Python doesn't provide a function for the reverse case, where you want to convert a number into a string in a specific base.

Your task is to write such a function.

the function may return the value or print it

you must provide support for all bases between 2 and 36

digits to use are 0123456789abcdefghijklmnopqrstuvwxyz

all languages are allowed

built in functions for this purpose are boring and thus forbidden

shortest code wins

答:
CoffeeScript (98 92)

```<code>z=(i,b)->a=parseInt(i)%b;return''if 1>i;(z i/b,b)+if a>9then String.fromCharCode(a+87)else a
</code>```

The compiled (and readable) javascript for the interested:

```<code>z = function(i, b) {
  var a;
  a = parseInt(i) % b;
  if (1 > i) {
    return '';
  }
  return (z(i / b, b)) + (a > 9 ? String.fromCharCode(a + 87) : a);
};
</code>```

What can I say? Unnecessary recursion gets me hot.

This could have been far shorter if I knew a shorter way to floor or convert from ASCII in Coffee-/Javascript. Tips would be greatly appreciated.

Edited to include "parseInt" to save a couple of characters on "Math.floor" and with some rearranging to reduce the "if ... then ..."s. Unfortunately, I don't think there even is a shorthand if in CoffeeScript ( "... ? ... : ..." doesn't work).

Title: Print integers in any base up to 36

Body:
CoffeeScript (98 92)

z=(i,b)->a=parseInt(i)%b;return''if 1>i;(z i/b,b)+if a>9then String.fromCharCode(a+87)else a

The compiled (and readable) javascript for the interested:

z = function(i, b) {
  var a;
  a = parseInt(i) % b;
  if (1 > i) {
    return '';
  }
  return (z(i / b, b)) + (a > 9 ? String.fromCharCode(a + 87) : a);
};

What can I say? Unnecessary recursion gets me hot.

This could have been far shorter if I knew a shorter way to floor or convert from ASCII in Coffee-/Javascript. Tips would be greatly appreciated.

Edited to include "parseInt" to save a couple of characters on "Math.floor" and with some rearranging to reduce the "if ... then ..."s. Unfortunately, I don't think there even is a shorthand if in CoffeeScript ( "... ? ... : ..." doesn't work).


答:
QBIC, 9 bytes

```<code>[1|10:?a]
</code>```

Explanation

```<code>[       ]  FOR <x> = ...NEXT; note that <x> becomes the symbol a-z, based on availability
 1|10      <x> goes from 1 to 10, an increment could be specified with ||
     :     End of FOR-loop specification
      ?a   Print the value of a
</code>```

EDIT: A non-competing entry saves me <s>one byte</s> two bytes:

```<code>[q|z:?a
</code>```

QBIC now supports variable params for FOR, and q through z are initialised in QBIC to represent 1-10, so saved a byte on the 10. Woohoo! Also, QBIC now detects any unclosed language constructs (IF/DO/FOR) at the end of a program and auto-closes 'm.

EDIT2: QBIC now has a variable number of parameters for its FOR loops. It by default assumes a loop from 1 to 10. Providing 1 parameter (y) makes it run from 1 to y, Providing 2 parameters (x and y) loops from x to y. Providing 3 parameters changes the interval: FOR a = x TO y STEP z. Using the defaults gives us this 4-byter:

```<code>[|?a
</code>```

Title: Print numbers from 1 to 10

Body:
This might be a very simple challenge, but I am surprised it hasn't been done on code-golf yet:

Print all Integers from 1 to 10 inclusive in ascending order to standard output.

Your output format can be whatever your language supports. This includes arbitrary separators (commas, semicolons, newlines, combinations of those, etc., but no digits), and prefixes and postfixes (like [...]). However, you may not output any other numbers than 1 through 10. Your program may not take any input. Standard loopholes are disallowed.

This is code-golf, so shortest answer in bytes wins!

Leaderboard

var QUESTION_ID=86075,OVERRIDE_USER=42570;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

Body:
QBIC, 9 bytes

[1|10:?a]

Explanation

[       ]  FOR <x> = ...NEXT; note that <x> becomes the symbol a-z, based on availability
 1|10      <x> goes from 1 to 10, an increment could be specified with ||
     :     End of FOR-loop specification
      ?a   Print the value of a

EDIT: A non-competing entry saves me <s>one byte</s> two bytes:

[q|z:?a

QBIC now supports variable params for FOR, and q through z are initialised in QBIC to represent 1-10, so saved a byte on the 10. Woohoo! Also, QBIC now detects any unclosed language constructs (IF/DO/FOR) at the end of a program and auto-closes 'm.

EDIT2: QBIC now has a variable number of parameters for its FOR loops. It by default assumes a loop from 1 to 10. Providing 1 parameter (y) makes it run from 1 to y, Providing 2 parameters (x and y) loops from x to y. Providing 3 parameters changes the interval: FOR a = x TO y STEP z. Using the defaults gives us this 4-byter:

[|?a


答:
Java 7, 47 bytes

int c(double n){return n>1?1+c(Math.log(n)):0;}
```
<p>Try it online.</p>
<p>The recursive Java 7 style method above is 2 bytes shorter than an iterative Java 8 style lambda:</p>
<pre class="lang-java prettyprint-override"><code>n->{int c=0;for(;n>1;c++)n=Math.log(n);return c;}
</code>```

Try it online.

Explanation:

int c(double n){      // Method with double parameter and integer return-type
  return n>1?         //  If the input is larger than 1:
    1+                //   Return 1 +
      c(Math.log(n))  //   A recursive call with log(input)
   :                  //  Else:
    0;                //   Return 0 instead

n->{                  // Method with double parameter and integer return-type
  int c=0;            //  Create a counter, starting at 0
  for(;n>1;           //  Loop as long as the input is still larger than 1:
    c++)              //   Increase the counter by 1
    n=Math.log(n);    //   And update the input to log(input)
  return c;}          //  After the loop: return the counter as result
```

Title: Calculate the Super-Logarithm

Body:
This should be a simple challenge.

Given a number \$n \ge 0\$, output the super-logarithm (or the \$\log^*\$, log-star, or iterated logarithm, which are equivalent since \$n\$ is never negative for this challenge.) of \$n\$.

$$\log^*(n) = \begin{cases}
0  & \text{ if } n \le 1 \\
1 + \log^*(\log(n)) & \text{ if } n > 1
\end{cases}$$

This is one of the two inverse functions to tetration. The other is the super-root, which is in a related question.

Examples

```<code>Input       Output
0           0
1           0
2           1
3           2
4           2
...
15          2
16          3
...
3814279     3
3814280     4
</code>```

Rules

You do not need to support decimals, though you may.

You need to support input of at least \$3814280 =  \left\lceil e^{e^e} \right\rceil\$.

You may not hard-code the values like 3814280. (Your program must theoretically support higher numbers.) I want an algorithm to be implemented.

Shortest code wins.

Related OEIS

Body:
Java 7, 47 bytes

int c(double n){return n>1?1+c(Math.log(n)):0;}

Try it online.

The recursive Java 7 style method above is 2 bytes shorter than an iterative Java 8 style lambda:

n->{int c=0;for(;n>1;c++)n=Math.log(n);return c;}

Try it online.

Explanation:

int c(double n){      // Method with double parameter and integer return-type
  return n>1?         //  If the input is larger than 1:
    1+                //   Return 1 +
      c(Math.log(n))  //   A recursive call with log(input)
   :                  //  Else:
    0;                //   Return 0 instead

n->{                  // Method with double parameter and integer return-type
  int c=0;            //  Create a counter, starting at 0
  for(;n>1;           //  Loop as long as the input is still larger than 1:
    c++)              //   Increase the counter by 1
    n=Math.log(n);    //   And update the input to log(input)
  return c;}          //  After the loop: return the counter as result


问:
Crash IRB (interactive Ruby)
Ruby comes with a built-in REPL, which is quite handy.

Your challenge is to crash it in the least amount of code!

The definition of "crash" is "make it exit in an unintended way." This means exit, quit, abort, irb_exit, irb_quit, et. al. are not valid answers.

Furthermore, you may not cause any side-effect to any other part of the system. For example, `rm -rf /` is not valid either.

Any version 1.9.3 or above is valid. If your code only works on a specific version of Ruby, you may specify that in the answer.

The final restriction is that you may not rely on any gems.

This is code-golf, so the shortest code that crashes IRB will win!

答:
8 characters

Similar to chinese perl goth's answer:

```<code>$>.close
</code>```

$> is an alias for STDOUT.

Title: Crash IRB (interactive Ruby)

Body:
8 characters

Similar to chinese perl goth's answer:

$>.close

$> is an alias for STDOUT.


问:
Output the alphabet, the ALPHABET, or just a character
The challenge is simple:

Write a function or program that takes an input x, and outputs the lower case alphabet if x is part of the lower case alphabet, outputs the upper case alphabet if x is part of the upper case alphabet and outputs just x if it's not part of either.

Rules:

The input can be function argument or from STDIN

The input will be any of the printable ASCII characters from 32 to 126 (space to tilde).

The input may be inside quotation marks,'x' or "x", but remember that ' and " are valid input and should be supported.

The input can be any of the letters in the alphabet, i.e. you can't assume it will be a or A.

The output should be only one of the alphabets or the single symbol, but trailing newlines are OK.

The letters in the alphabet should not be separated by spaces, commas or anything else.

Some examples:

```<code>F
ABCDEFGHIJKLMNOPQRSTUVWXYZ

z
abcdefghijklmnopqrstuvwxyz

"
"

    <- Input:  Space
    <- Output: Space
</code>```

Shortest code in bytes win.

Optional but appreciated: If your language has an online interpreter, please also post a link so that it can be easily tested by others.

Leaderboard

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code>## Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code>## Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

var QUESTION_ID=67357,OVERRIDE_USER=44713;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
s-lang, 40 bytes (non-competing)

Replaces any letter with the alphabet, matching the case.

```<code>t@[[a-z]][abcdefghijklmnopqrstuvwxyz]
</code>```

t Replace with regex function

@ Match case for entire match parameter for t function

[[a-z]] first argument ([a-z]) regex for matching any letter (@ parameter makes it so this function ignores the case when matching, so we don't need A-Z too)

abcdefghijklmnopqrstuvwxyz what to replace it with

Try it here

Body:
s-lang, 40 bytes (non-competing)

Replaces any letter with the alphabet, matching the case.

t@[[a-z]][abcdefghijklmnopqrstuvwxyz]

t Replace with regex function

@ Match case for entire match parameter for t function

[[a-z]] first argument ([a-z]) regex for matching any letter (@ parameter makes it so this function ignores the case when matching, so we don't need A-Z too)

abcdefghijklmnopqrstuvwxyz what to replace it with

Try it here


问:
How to weight loss easily?
In this question, we will only focus on losing weight by doing exercise, although there are still many ways to lose weight.

Different sports burn different amount of calories.

For example, playing billiards for an hour can burn 102 calories[1], while playing basketball for 15 minutes can already burn 119 calories [1], which make weight loss by playing basketball easier, at least from some perspectives.

The exact way to weigh the easiness is by dividing the amount of calories burnt by the time needed, which gives us the easiness index (EI).

For example, fencing for 15 minutes can burn 85 calories, which gets an EI of 85/15.

You will be given a list in this format:

```<code>[["fencing",15,85],["billiards",60,102],["basketball",15,119]]
</code>```

or other format that you want.

Then, you will output the sports which have the highest EI.

TL;DR

Given a list of tuples [name,value1,value2] output the name where value2/value1 is the highest.

Constraints

You may not produce any real number that is not integer in the process.

You may not use any fraction built-in.

Specifications (Specs)

If there is more than one name that satisfy the result, you may output any non-empty subset of them or any element of them.

The name will match the regex /^[a-z]+$/, meaning that it will only consist of lowercase Latin standard alphabet.

The list will not be empty.

Testcase

Input:

```<code>[["fencing",15,85],["billiards",60,102],["basketball",15,119]]
</code>```

Output:

```<code>basketball
</code>```

References

http://calorielab.com/burned/

答:
Haskell <s>72</s> 70 bytes

```<code>import Data.List
(n,(x,y))%(m,(a,b))=compare(x*b)$y*a
fst.minimumBy(%)
</code>```

Usage :

```<code>main=putStr$(fst.minimumBy(%))[("fencing",(15,85)),("billiards",(60,102)),("basketball",(15,119))]
</code>```

Title: How to weight loss easily?

Body:
Haskell <s>72</s> 70 bytes

import Data.List
(n,(x,y))%(m,(a,b))=compare(x*b)$y*a
fst.minimumBy(%)

Usage :

main=putStr$(fst.minimumBy(%))[("fencing",(15,85)),("billiards",(60,102)),("basketball",(15,119))]


答:
Ruby, 72 bytes

```<code>e=0;while gets;n=$_.split;f=eval n[2]+"/"+n[1];m,e=n[0],f if f>e;end;p m
</code>```

I really thought this would be shorter...

Input is taken from STDIN in the format of name time calories

Oh well, any help to shorten it is appreciated.

Title: How to weight loss easily?

Body:
In this question, we will only focus on losing weight by doing exercise, although there are still many ways to lose weight.

Different sports burn different amount of calories.

For example, playing billiards for an hour can burn 102 calories[1], while playing basketball for 15 minutes can already burn 119 calories [1], which make weight loss by playing basketball easier, at least from some perspectives.

The exact way to weigh the easiness is by dividing the amount of calories burnt by the time needed, which gives us the easiness index (EI).

For example, fencing for 15 minutes can burn 85 calories, which gets an EI of 85/15.

You will be given a list in this format:

```<code>[["fencing",15,85],["billiards",60,102],["basketball",15,119]]
</code>```

or other format that you want.

Then, you will output the sports which have the highest EI.

TL;DR

Given a list of tuples [name,value1,value2] output the name where value2/value1 is the highest.

Constraints

You may not produce any real number that is not integer in the process.

You may not use any fraction built-in.

Specifications (Specs)

If there is more than one name that satisfy the result, you may output any non-empty subset of them or any element of them.

The name will match the regex /^[a-z]+$/, meaning that it will only consist of lowercase Latin standard alphabet.

The list will not be empty.

Testcase

Input:

```<code>[["fencing",15,85],["billiards",60,102],["basketball",15,119]]
</code>```

Output:

```<code>basketball
</code>```

References

http://calorielab.com/burned/

Body:
Ruby, 72 bytes

e=0;while gets;n=$_.split;f=eval n[2]+"/"+n[1];m,e=n[0],f if f>e;end;p m

I really thought this would be shorter...

Input is taken from STDIN in the format of name time calories

Oh well, any help to shorten it is appreciated.


问:
"Hello, World!"
So... uh... this is a bit embarrassing. But we don't have a plain "Hello, World!" challenge yet (despite having 35 variants tagged with hello-world, and counting). While this is not the most interesting code golf in the common languages, finding the shortest solution in certain esolangs can be a serious challenge. For instance, to my knowledge it is not known whether the shortest possible Brainfuck solution has been found yet.

Furthermore, while all of <s>Wikipedia</s> (the Wikipedia entry has been deleted but there is a copy at archive.org
), esolangs and Rosetta Code have lists of "Hello, World!" programs, none of these are interested in having the shortest for each language (there is also this GitHub repository). If we want to be a significant site in the code golf community, I think we should try and create the ultimate catalogue of shortest "Hello, World!" programs (similar to how our basic quine challenge contains some of the shortest known quines in various languages). So let's do this!

The Rules

Each submission must be a full program.

The program must take no input, and print Hello, World! to STDOUT (this exact byte stream, including capitalization and punctuation) plus an optional trailing newline, and nothing else.

The program must not write anything to STDERR.

If anyone wants to abuse this by creating a language where the empty program prints Hello, World!, then congrats, they just paved the way for a very boring answer.

Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.

Submissions are scored in bytes, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like Folders, are a bit tricky to score - if in doubt, please ask on Meta.

This is not about finding the language with the shortest "Hello, World!" program. This is about finding the shortest "Hello, World!" program in every language. Therefore, I will not mark any answer as "accepted".

If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck-derivatives like Alphuck), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.

As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf - these are still useful to this question as it tries to compile a catalogue as complete as possible. However, do primarily upvote answers in languages where the authors actually had to put effort into golfing the code.

For inspiration, check the Hello World Collection.

The Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code>## Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code>## Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](https://esolangs.org/wiki/Fish), 121 bytes
</code>```

/* Configuration */

var QUESTION_ID = 55422; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery(''+lang+'').text();

    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  text-align: left !important;
  display: block !important;
}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 500px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}</code>```

<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
s-lang, 18 bytes

Literally replaces "nothing" with "Hello, World!" (s-lang is not really meant to create strings, just modify them).

```<code>t[][Hello, World!]
</code>```

t - replace function

Try it here

Title: "Hello, World!"

Body:
s-lang, 18 bytes

Literally replaces "nothing" with "Hello, World!" (s-lang is not really meant to create strings, just modify them).

t[][Hello, World!]

t - replace function

Try it here


答:
ListSharp, 37 bytes

```<code>[FOREACH NUMB IN 1 TO 10 AS i]
SHOW=i
</code>```

Pretty straight forward

as a sidenote =>
is this cheating?

```<code>SHOW="10,9,8,7,6,5,4,3,2,1"
</code>```

Title: Print numbers from 1 to 10

Body:
ListSharp, 37 bytes

[FOREACH NUMB IN 1 TO 10 AS i]
SHOW=i

Pretty straight forward

as a sidenote =>
is this cheating?

SHOW="10,9,8,7,6,5,4,3,2,1"


问:
Divisibility test

Task

Given two strictly positive integers n and d as input, determine whether n is evenly divisible by d, i.e., if there exists an integer q such that n = qd.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

The output should be a truthy or a falsy value; truthy if n is divisible by d, and falsy otherwise.

Your code only has to handle integers it can represent natively, as long as it works for all signed 8-bit integers. However, your algorithm has to work for arbitrarily large integers.

You may use any programming language, but note that these loopholes are forbidden by default.

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test cases

```<code> n,  d    output

 1,  1    truthy
 2,  1    truthy
 6,  3    truthy
17, 17    truthy
22,  2    truthy
 1,  2    falsy
 2,  3    falsy
 2,  4    falsy
 3,  9    falsy
15, 16    falsy
</code>```

Leaderboard

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code>## Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code>## Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 3 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
Pyth, 3 bytes

```<code>!%F
</code>```

Test suite.

Title: Divisibility test

Body:
Pyth, 3 bytes

!%F

Test suite.


答:
Pyke, 2 bytes

```<code>%!
</code>```

Try it here!

```<code>not (a mod b)
</code>```

Title: Divisibility test

Body:
Task

Given two strictly positive integers n and d as input, determine whether n is evenly divisible by d, i.e., if there exists an integer q such that n = qd.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

The output should be a truthy or a falsy value; truthy if n is divisible by d, and falsy otherwise.

Your code only has to handle integers it can represent natively, as long as it works for all signed 8-bit integers. However, your algorithm has to work for arbitrarily large integers.

You may use any programming language, but note that these loopholes are forbidden by default.

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test cases

```<code> n,  d    output

 1,  1    truthy
 2,  1    truthy
 6,  3    truthy
17, 17    truthy
22,  2    truthy
 1,  2    falsy
 2,  3    falsy
 2,  4    falsy
 3,  9    falsy
15, 16    falsy
</code>```

Leaderboard

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code>## Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code>## Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 3 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

Body:
Pyke, 2 bytes

%!

Try it here!

not (a mod b)


答:
Jelly, 1 byte

```<code>ḍ
</code>```

This took me hours to golf.

Try it online!

Title: Divisibility test

Body:
Jelly, 1 byte

ḍ

This took me hours to golf.

Try it online!


答:
APL (Dyalog Unicode), 3 bytes

0=|
```

Try it online!

Is zero equal to the division remainder?

Title: Divisibility test

Body:
APL (Dyalog Unicode), 3 bytes

0=|

Try it online!

Is zero equal to the division remainder?


答:
Python, 16 bytes

lambda D,d:D%d<1
```

Title: Divisibility test

Body:
Python, 16 bytes

lambda D,d:D%d<1


答:
Tcl , 34 bytes

```<code>ge stdin a
ge stdin b
exp $a%$b<1
</code>```

My first /*successful*/ attempt in codegolf !
This code must be executed in Tcl shell , otherwise it will not work.

One byte thanks to @Lynn .

Four bytes thanks to @Lynn and @LeakyNun (now I understand what he meant)!

Title: Divisibility test

Body:
Tcl , 34 bytes

ge stdin a
ge stdin b
exp $a%$b<1

My first /*successful*/ attempt in codegolf !
This code must be executed in Tcl shell , otherwise it will not work.

One byte thanks to @Lynn .

Four bytes thanks to @Lynn and @LeakyNun (now I understand what he meant)!


答:
CJam, <s>6</s> 4 bytes

Saved 2 bytes thanks to Dennis

```<code>q~%!
</code>```

Try it online

```<code>q    e# Take in the input
 ~   e# Dump the individual values to the stack
  %  e# Modulus
   ! e# Boolean NOT
</code>```

Title: Divisibility test

Body:
CJam, <s>6</s> 4 bytes

Saved 2 bytes thanks to Dennis

q~%!

Try it online

q    e# Take in the input
 ~   e# Dump the individual values to the stack
  %  e# Modulus
   ! e# Boolean NOT


答:
Brain-flak <s>102, 98,</s> 96 bytes

```<code>(({}<>))<>{({}[()])<>(({}[()])){{}(<({}[({})])>)}{}({}({}))<>}{}<>([{}]{}){<>(([()])())}({}{}())
</code>```

Eww. Gross. I might post an explanation, but I barely understand it myself. This language hurts my brain.

Try it online!

Thanks to github user @Wheatwizard for coming up with a modulus example. I probably could not have figured that out myself!

Also, the shorter answer is here.

Possibly incorrect explanation:

```<code>(({}<>))                    #Push this element onto the other stack
<>                          #Move back to stack one.
{                           #While the top element is non-zero:
 ({}[()])                   #  Decrement the number on top
 <>                         #  Move to the other stack
 (({}[()]))                 #  Push the top element minus one twice
 {                          #  While the top element is non-zero:
  {}                        #    Pop the top element
  (<          >)            #    Push a zero
        ({})                #    Push the second from top element
       [    ]               #    Evalue this second from top element as negative
    ({}      )              #    And push that negative plus the top element
 }
 {}                         #  Pop the top element
 ({}({}))                   #  Push the top element plus the second from the top, AND push the second from top
 <>                         #  Switch stacks
}

{}                          #Pop the stack
<>                          #Switch to the other stack
([{}]{})                    #And push the top element minus the second element.
</code>```

The rest is pretty straightforward.

```<code>{              }            #While the top element is non-zero:
 <>                         #Move to the other stack
   (([()])  )               #Push a negative one
          ()                #AND push the previously pushed value + 1 (e.g. 0)

                 (      )   #Push:
                  {}{}      #The top two elements added together
                      ()    #Plus one
</code>```

Title: Divisibility test

Body:
Brain-flak <s>102, 98,</s> 96 bytes

(({}<>))<>{({}[()])<>(({}[()])){{}(<({}[({})])>)}{}({}({}))<>}{}<>([{}]{}){<>(([()])())}({}{}())

Eww. Gross. I might post an explanation, but I barely understand it myself. This language hurts my brain.

Try it online!

Thanks to github user @Wheatwizard for coming up with a modulus example. I probably could not have figured that out myself!

Also, the shorter answer is here.

Possibly incorrect explanation:

(({}<>))                    #Push this element onto the other stack
<>                          #Move back to stack one.
{                           #While the top element is non-zero:
 ({}[()])                   #  Decrement the number on top
 <>                         #  Move to the other stack
 (({}[()]))                 #  Push the top element minus one twice
 {                          #  While the top element is non-zero:
  {}                        #    Pop the top element
  (<          >)            #    Push a zero
        ({})                #    Push the second from top element
       [    ]               #    Evalue this second from top element as negative
    ({}      )              #    And push that negative plus the top element
 }
 {}                         #  Pop the top element
 ({}({}))                   #  Push the top element plus the second from the top, AND push the second from top
 <>                         #  Switch stacks
}

{}                          #Pop the stack
<>                          #Switch to the other stack
([{}]{})                    #And push the top element minus the second element.

The rest is pretty straightforward.

{              }            #While the top element is non-zero:
 <>                         #Move to the other stack
   (([()])  )               #Push a negative one
          ()                #AND push the previously pushed value + 1 (e.g. 0)

                 (      )   #Push:
                  {}{}      #The top two elements added together
                      ()    #Plus one


答:
GolfScript, 3 bytes

```<code>~%!
</code>```

Explanation:

```<code>~    # Evaluate the input
 %   # Take the first modulus the second
  !  # Boolean not
</code>```

Try it online!

Title: Divisibility test

Body:
GolfScript, 3 bytes

~%!

Explanation:

~    # Evaluate the input
 %   # Take the first modulus the second
  !  # Boolean not

Try it online!


答:
Javascript (ES6) 17 12 11 bytes

```<code>a=>b=>a%b<1
</code>```

EDIT: Removed 5 bytes because 'a>0' is expected.

EDIT2: Removed 1 byte thanks to Downgoat.

Title: Divisibility test

Body:
Javascript (ES6) 17 12 11 bytes

a=>b=>a%b<1

EDIT: Removed 5 bytes because 'a>0' is expected.

EDIT2: Removed 1 byte thanks to Downgoat.


答:
Fortran 95, 78 bytes

```<code>function f(i,j)result(k)
integer::i,j,k
k=merge(1,0,MOD(i,j)<1)
end function f
</code>```

Title: Divisibility test

Body:
Fortran 95, 78 bytes

function f(i,j)result(k)
integer::i,j,k
k=merge(1,0,MOD(i,j)<1)
end function f


答:
05AB1E, 6 bytes

```<code>II%0Q,
</code>```

Uses CP-1252 encoding. Try it online!

You can also use the built in

```<code>Ö
</code>```

which does exactly what the challenge asks. Just that the 2 inputs are swapped. Try it online!

Title: Divisibility test

Body:
05AB1E, 6 bytes

II%0Q,

Uses CP-1252 encoding. Try it online!

You can also use the built in

Ö

which does exactly what the challenge asks. Just that the 2 inputs are swapped. Try it online!


答:
Retina, 12 bytes

```<code>^(1+)\1* \1$
</code>```

Takes space-separated input in unary, like 111111111111 1111 to check if 12 if divisible by 4. Prints 1 (true) or 0 (false).

Try it online!

<s>FryAmTheEggman saved two bytes.</s> Oops, rewrote my answer to take the arguments in the right order. (Then Fry beat me to it in the comments. I’m slow at regex!)

Title: Divisibility test

Body:
Retina, 12 bytes

^(1+)\1* \1$

Takes space-separated input in unary, like 111111111111 1111 to check if 12 if divisible by 4. Prints 1 (true) or 0 (false).

Try it online!

<s>FryAmTheEggman saved two bytes.</s> Oops, rewrote my answer to take the arguments in the right order. (Then Fry beat me to it in the comments. I’m slow at regex!)


答:
Brachylog, 2 bytes

```<code>%0
</code>```

Try it online!

Title: Divisibility test

Body:
Brachylog, 2 bytes

%0

Try it online!


答:
Batch, 20 bytes

```<code>@cmd/cset/a!(%1%%%2)
</code>```

Outputs 1 on success, 0 on failure.

Title: Divisibility test

Body:
Batch, 20 bytes

@cmd/cset/a!(%1%%%2)

Outputs 1 on success, 0 on failure.


答:
Actually, <s>3</s> 2 bytes

```<code>%Y
</code>```

Saved one byte thanks to @Mego.

Try it online!

Title: Divisibility test

Body:
Actually, <s>3</s> 2 bytes

%Y

Saved one byte thanks to @Mego.

Try it online!


答:
Convex, 3 bytes

```<code>A´`
</code>```

Try it online!

Title: Print numbers from 1 to 10

Body:
This might be a very simple challenge, but I am surprised it hasn't been done on code-golf yet:

Print all Integers from 1 to 10 inclusive in ascending order to standard output.

Your output format can be whatever your language supports. This includes arbitrary separators (commas, semicolons, newlines, combinations of those, etc., but no digits), and prefixes and postfixes (like [...]). However, you may not output any other numbers than 1 through 10. Your program may not take any input. Standard loopholes are disallowed.

This is code-golf, so shortest answer in bytes wins!

Leaderboard

var QUESTION_ID=86075,OVERRIDE_USER=42570;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

Body:
Convex, 3 bytes

A´`

Try it online!


答:
Julia, 9 bytes

D\d=D%d<1
```

Try it online!

Title: Divisibility test

Body:
Julia, 9 bytes

D\d=D%d<1

Try it online!


问:
Draw a ladder and slide
Your task is to create a program or function that takes, as input, a natural number (n) between 1 and 25 (inclusive) and prints an isometric representation of a slide and ladder with n number of rungs.

Ladder and slide specifications

The ladder is always oriented on the left and the slide on the right. We're viewing it from the ladder side, so part of the slide is obscured at the top three levels. The rungs are represented by four dashes (----) and the sides of the ladder and slide by slashes (/ and \). The following is a diagram to represent the patterns of spaces needed for a slide with five rungs.

```<code>Slide              Blank space count
    /----/\        1234/----/\
   /----/  \       123/----/12\
  /----/    \      12/----/1234\
 /----/ \    \     1/----/1\1234\
/----/   \    \    /----/123\1234\
</code>```

Examples

```<code>>>1
/----/\

>>3
  /----/\
 /----/  \
/----/    \

>>4
   /----/\
  /----/  \
 /----/    \
/----/ \    \

>>10
         /----/\
        /----/  \
       /----/    \
      /----/ \    \
     /----/   \    \
    /----/     \    \
   /----/       \    \
  /----/         \    \
 /----/           \    \
/----/             \    \
</code>```

This is code-golf, so the answer with the lowest byte count wins.

Note: trailing white space is acceptable in the output, as long as it doesn't exceed the length of the line.

答:
Vim, 71 keystrokes

This is such a stupid way of doing it, but it's a bit of fun. Input is given as a text file with a single line containing an integer. This is likely quite golfable, but it'll do for now (edit: switched style of control characters upon request):

```<code>A@qyyPgg<c-v><c-v>GkI <c-v><esc>G$i  <c-v><esc><esc>
Tq"qDI/----/\^[lD@"ddh<c-v>god:%s/     \\/\\    \\<cr>
</code>```

<c-v>, <esc> and <cr> are all individual keystrokes; ctrl+v, escape, and carriage return (enter) respectively. For a simple to digest version with the correct literals, here is the file ladder.keys run though xxd:

```<code>00000000: 4140 7179 7950 6767 1616 476b 4920 161b  A@qyyPgg..GkI ..
00000010: 4724 6920 2016 1b1b 5471 2271 4449 2f2d  G$i  ...Tq"qDI/-
00000020: 2d2d 2d2f 5c1b 6c44 4022 6464 6816 676f  ---/\.lD@"ddh.go
00000030: 643a 2573 2f20 2020 2020 5c5c 2f5c 5c20  d:%s/     \\/\\
00000040: 2020 205c 5c0d 0d0a                         \\...
</code>```

To try it out (assuming a nix with the appropriate tools) take the above, run it through xxd -r and put in the file ladder.keys. Create a file ladder.txt with an integer in it. Then do:

```<code>vim -s ladder.keys -u NONE ladder.txt
</code>```

Title: Draw a ladder and slide

Body:
Vim, 71 keystrokes

This is such a stupid way of doing it, but it's a bit of fun. Input is given as a text file with a single line containing an integer. This is likely quite golfable, but it'll do for now (edit: switched style of control characters upon request):

A@qyyPgg<c-v><c-v>GkI <c-v><esc>G$i  <c-v><esc><esc>
Tq"qDI/----/\^[lD@"ddh<c-v>god:%s/     \\/\\    \\<cr>

<c-v>, <esc> and <cr> are all individual keystrokes; ctrl+v, escape, and carriage return (enter) respectively. For a simple to digest version with the correct literals, here is the file ladder.keys run though xxd:

00000000: 4140 7179 7950 6767 1616 476b 4920 161b  A@qyyPgg..GkI ..
00000010: 4724 6920 2016 1b1b 5471 2271 4449 2f2d  G$i  ...Tq"qDI/-
00000020: 2d2d 2d2f 5c1b 6c44 4022 6464 6816 676f  ---/\.lD@"ddh.go
00000030: 643a 2573 2f20 2020 2020 5c5c 2f5c 5c20  d:%s/     \\/\\
00000040: 2020 205c 5c0d 0d0a                         \\...

To try it out (assuming a nix with the appropriate tools) take the above, run it through xxd -r and put in the file ladder.keys. Create a file ladder.txt with an integer in it. Then do:

vim -s ladder.keys -u NONE ladder.txt