Modified Coupon Collector's Problem in Java

The deviation you see from the expected results is probably in large part due to the poor use of Random. When I time your code, I get:

Average value of draws required is 23.832188
Complete in 23473.917s

If I use Random the way it should be (re)used, and convert this code:

        mCouponList.add(new Random()
                .nextInt((mMaxCouponNumber - mMinCouponNumber) + 1)
                + mMinCouponNumber);

to be:

private static final Random RANDOM = new Random();

....

            mCouponList.add(RANDOM
                    .nextInt((mMaxCouponNumber - mMinCouponNumber) + 1)
                    + mMinCouponNumber);

it completes in half the time:

Average value of draws required is 23.827381
Complete in 11552.228s

Hmm.. I was expecting this to correct the errors in the 'randomness' too, but, now I see the problem there.... you are using float, and not double. Float has relatively low accuracy. If I change this line here:

float mSumOfDraws = 0;

to be:

double mSumOfDraws = 0;

My results become:

Average value of draws required is 24.1312123

That's much closer to the mathematical expectation.

Now, about performance... your code is really slow. There's four prime reasons:

there's no need to record every draw you make in an ArrayList - it will grow large, and require garbage collection. You only need to count how many times you 'pull' each coupon.
there is no need to number the coupons from minimum to maximum - you just need to know how many there are.
You use Integer values instead of int primitives.
You have too much code in your main method - the main method is hard for the compiler to optimize - it is only ever called once.

Additionally, apart from the performance, the code style is... unconventional. You should parameterize a lot of the static values so that you can reuse the code better too.

Here is the results of my simplified code:

Average for 2 sets of 6 coupons is 24.131
Complete in 3.983s

(compared to your results with the improved Random, and double):

Average value of draws required is 24.1291875
Complete in 11.109s

The code I use is:

import java.util.Arrays;
import java.util.Random;

public class CouponClipper {

    private final int[] counts;
    private int remaining;

    public CouponClipper(int couponCount, int sets) {
        this.counts = new int[couponCount];
        Arrays.fill(counts, sets);
        this.remaining = couponCount;
    }

    public boolean pull(int coupon) {
        if (--counts[coupon] == 0) {
            remaining--;
        }
        return remaining == 0;
    }

    private static final Random RANDOM = new Random();

    public static int countRequired(int coupons, int sets) {
        CouponClipper clipper = new CouponClipper(coupons, sets);
        int count = 0;
        do {
            count++;
        } while (!clipper.pull(RANDOM.nextInt(coupons)));
        return count;
    }

    public static double averageCounts(int coupons, int sets, int iterations) {
        long sum = 0;
        for (int i = 0; i < iterations; i++) {
            sum += countRequired(coupons, sets);
        }
        return sum / (double)iterations;
    }

    public static void main(String[] args) {
        long nanos = System.nanoTime();
        System.out.printf("Average for 2 sets of 6 coupons is %.3f\n", averageCounts(6, 2, 10000000));
        nanos = System.nanoTime() - nanos;
        System.out.printf("Complete in %.3fs\n", nanos / 1000000000.0);

    }

}


Check if all leaves are at same level in a binary tree

Okay lets start with the name of your function: leavesIn1Level(...). It does explain what this method does, but apparently it is not very clear - even to yourself - therefore you felt the need to add a comment. How a bout the name areAllLeavesInSameLevel(..). This explais what it does and makes your comment useless.

Next point (a compliment): You used a Queue, which is the data-structure that fits your needs perfectly. Good job.

One thing I noticed: The line node.left == null && node.right == null is used twice in your short piece of code and therefore - code duplication. How do we get rid of it? Well... What does that line of code do? It checks whether a Node is a Leaf. So why don't we just name it that way?

private static boolean isLeaf(Node node)
{
    return node.left == null && node.right == null;
}

Boom. Code duplication gone. And the code explains exactly what it does.

Now what I realized, is that you have a very deep level of abstraction in this function, where you mix what is done with how its done. Lets try to get rid of this:

if(current.left != null){
    q.add(current.left);
}
if(current.right != null){
    q.add(current.right);
}

This piece of code explains how something is done. But what is done? Children of a node are added to a queue. Why don't we just name it that?

private static void addChildrenToQueue(Node node, Queue<Node> queue)
{
    if(node.left != null){
        queue.add(node.left);
    }
    if(node.right != null){
        queue.add(node.right);
    }
}

Lets take a look at what we have now:

public static boolean areAllLeavesInSameLevel(Node root){

    if(root == null){
        return false;
    }
    if(isLeaf(root)){
        return true;
    }
    Queue<Node> q = new LinkedList<Node>();
    q.add(root);

    int levelNumber = 0;
    int height = height(root);

    while(true){

        int nodeCount = q.size();
        if(nodeCount == 0){
            break;
        }
        while(nodeCount > 0){

            Node current = q.remove();
            nodeCount--;

            if(isLeaf(current)){
                if(height != levelNumber){
                    return false;
                }else{
                    return true;
                }
            }
            addChildrenToQueue(current,q);
        }
        levelNumber++;
    }
    return false;
}

Now I'm not particularly happy with the name q. What is inside that queue? It's nodes that need to be checked - in other words: remainingNodes. Lets just call it that.

Take a look at this:

while(true){
    int nodeCount = remainingNodes.size();
    if(nodeCount == 0){
        break;
    }
    ...
}
return false;

What does it do? If the queue is empty it jumps out of the loop and then returns false. How about we move it around a bit to get rid of that while(true):

while(!remainingNodes.isEmpty()){
    int nodeCount = remainingNodes.size();
    ...
}
return false;

Aaaand the while(true) is gone and replaced with a much better phrased condition. While the Collection of remaining nodes is not empty do something. At this point we can argue that the queue could have the even better name queueOfRemainingNodes. Some would say it's too long. I like it, but that's up to you to decide.

Let's take a look at the second while:

int nodeCount = queueOfRemainingNodes.size();
while(nodeCount > 0){
    nodeCount--;
    ...
}

To me this looks like the classic case for a for-loop instead:

for(int nodeCount = queueOfRemainingNodes.size(); nodeCount > 0; nodeCount--)
{
    ...
}

Okay. Now what does this inner for-loop actually do? It checks whether any node, that is currently in the queue is a leaf and if it is not, it adds its children to the queue. If however one is a leaf, it does the following check:

if(height != levelNumber){

What? Is height equal to levelNumber? What is levelNumber? And which height? By looking up we find out that height is the height of the tree and levelNumber is the number of the level we are currently looking at. Let's give these two some more expressive names:

int currentLevelNumber = 0;
int treeHeight = height(root);

So where are we now? Let's take a look at the full code:

public static boolean areAllLeavesInSameLevel(Node root){

    if(root == null){
        return false;
    }
    if(isLeaf(root)){
        return true;
    }
    Queue<Node> queueOfRemainingNodes = new LinkedList<Node>();
    queueOfRemainingNodes.add(root);

    int currentLevelNumber = 0;
    int treeHeight = height(root);

    while(!queueOfRemainingNodes.isEmpty()){

        for(int nodesOnCurrentLevel = queueOfRemainingNodes.size(); nodesOnCurrentLevel > 0; nodesOnCurrentLevel--){

            Node current = q.remove();

            if(isLeaf(current)){
                if(treeHeight != currentLevelNumber){
                    return false;
                }else{
                    return true;
                }
            }
            addChildrenToQueue(current,queueOfRemainingNodes);
        }
        currentLevelNumber++;
    }
    return false;
}

Wow. Just realized how long this post got. Sorry, I could go on for hours and remove this second (and third) level of intendation and find more expressive names for everything, but I think this gives you an impression on what you can do.


Simple exercice representing a slidepuzzle

System.out.println("Enter height (>0)");

        int height = sc.nextInt();

This pattern repeats itself several times in your code. Turn it into a method, e.g. (assuming the Scanner is turned into a static field):

private static int promptForInt(String message) {
    System.out.println(message);
    return sc.nextInt();
}

-

    public static int getRandomInteger(){

        Random randomGenerator = new Random();

        return randomGenerator.nextInt(99) + 1;
    }

Creating a new Random for each call makes no sense from a performance perspective. The object should be created exactly once.

    public static void populatePuzzle( int[][] puzzle ){

    public static void displayPuzzle( int[][] puzzle ){

    public static void placeMissingPiece( int elementNumber, int[][] puzzle ){

You're not thinking object-oriented here. The above pattern is a really obvious indication that each method should belong to a Puzzle class. That way your main method can concern itself with the core logic of your program instead of the implementation details of the puzzle. E.g.:

Puzzle puzzle = new Puzzle(); // .populate() should probably be called from the constructor
// ...
puzzle.placeMissingPiece(position);
// ...
puzzle.display();
// ...
puzzle.swapElementValues(0, number); // findNumber() called as a private method
// etc...


Naming

Templates depend on a consistent naming scheme for static polymorphism.

We can observe such consistent naming throughout the type traits offered by the standard library (from std::aligned_storage to std::add_pointer); the two most common names being:

A type alias member when the type trait produces a type result.
A value static data member to represent constexpr values.

This means that naming your extracted type alias as result is non-standard and breaks with any templates that assume the same naming convention from the standard library.

What is a type list?

There doesn't seem to be a specific purpose for having a type list that is defined in terms of a head and tail when variadic templates can easily represent what a type list is. Thus, we can simply define a type list as:

template <class... Types>
class type_list {};

What is extracting from a type list?

We can define a more general extraction template to extract from a variadic template.

template <std::size_t idx, class... Types>
class extract
{
    static_assert( idx < sizeof...( Types ), "index out of bounds" );

    template <std::size_t i, std::size_t n, class... Rest>
    struct extract_impl;

    template <std::size_t i, std::size_t n, class T, class... Rest>
    struct extract_impl<i, n, T, Rest...>
    {
        using type = typename extract_impl<i + 1, n, Rest...>::type;
    };

    template <std::size_t n, class T, class... Rest>
    struct extract_impl<n, n, T, Rest...>
    {
        using type = T;
    };

public:
    using type = typename extract_impl<0, idx, Types...>::type;
};

Now that we have that, extracting from our type list is a simple subset operation based on the generalized template for extraction:

template <std::size_t idx, class TypeList>
struct type_list_extract;

template <std::size_t idx, template <class...> class TypeList, class... Types>
struct type_list_extract<idx, TypeList<Types...>>
{
    using type = typename extract<idx, Types...>::type;
};

For which we can provide a convenience alias:

template <std::size_t idx, class TypeList>
using type_list_extract_t = typename type_list_extract<idx, TypeList>::type;

That we can now use as follows:

int main()
{
    using list_t = type_list<char, bool, void>;

    static_assert( std::is_same<char, type_list_extract_t<0, list_t>>::value, "!" );
    static_assert( std::is_same<bool, type_list_extract_t<1, list_t>>::value, "!" );
    static_assert( std::is_same<void, type_list_extract_t<2, list_t>>::value, "!" );
    //type_list_extract_t<3, list_t>; // static_assert fails: index out of bounds
}

Final words

There are non-recursive ways to implement extraction (among other operations); they will most likely (possibly definitely!) require integer/index sequences. You can have a look at my answer for this question to see a non-recursive integer sequence implementation.

There are many more cool tricks to do with templates. Look on this very site or Stack Overflow!


All combinations of two pairs of elements of an array

Unused variables
We never use targetVector, so we can omit its definition.
Reduce scope
We can move pair1 and pair2 inside of the do loop.
Don't cast to signed
This looks like a misguided attempt to appease a compiler warning:
    for (int i = 0; i < (int)index_pair.size(); i++) {

Whilst it's good that you have enabled a good set of warnings, the better response would be to change the type of i to match (especially as we intend to use it as an indexer):
    for (std::size_t i = 0u;  i < index_pair.size();  ++i) {

We can also simplify the if chain if we use a small array for pair:
    std::size_t pair[3] = {};

    for (std::size_t i = 0u;  i < index_pair.size();  ++i)
        pair[index_pair[i]] += 1u << (i+1);

    if (pair[1] > pair[2]) {

We could use range-based for instead:
    std::size_t n = 0;
    for (auto i: index_pair)
        pair[i] += 1u << ++n;

It's not obvious whether this is better than the index loop, but you might prefer it.
A typo
You appear to have misspelt std::prev_permutation in the while condition.

Modified code
Without changing the algorithm, I have simplified to just
#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> index_pair = { 2, 2, 1, 1, 0 };

    do {
        std::size_t pair[3] = {};

        for (std::size_t i = 0u;  i < index_pair.size();  ++i)
            pair[index_pair[i]] += 1u << (i+1);

        if (pair[1] > pair[2]) {
            for (auto index: index_pair) {
                std::cout << index;
            }
            std::cout << "\n";
        }
    } while (std::prev_permutation(index_pair.begin(), index_pair.end()));
}


Here are a few things you can do to improve the performance of the data loading:

convert the JSON file to CSV and use LOAD DATA to load from a file (sample). It is probably the fastest way to do what you are trying to do.
use .executemany() instead of .execute():

datajson = json.load(testFile)

insert_query = """
    INSERT INTO
        cstore (AccountNo)
    VALUES (%(AccountNo)s)
"""
cursor.executemany(insert_query, datajson)

look into disabling/removing existing indexes during the insertion and then re-creating them after the insertion is done
make sure you are not doing the data-load "over the internet" and there is no network-latency and bandwidth impact, be "closer" to the database server
loading the JSON file is probably not a bottleneck, but you may also look into faster JSON parsers like ujson
I remember we also had some data-loading-performance-related success with the ultra-fast umysql Python database driver, but it looks like the package has not been maintained for quite a while


This SQL of yours has three issues I want to address before looking at the performance...
Formatting:
SELECT c.id,
       c.fromUserId,
       c.toUserId,
       m.userId,
       m.message,
       m.timestamp,
       pm.filename AS thumbnail,
       u.username
FROM conversations c,
     messages m,
     productmedia pm,
     users u
WHERE (c.fromUserId = '9' OR c.toUserId = '9')
  AND c.id = m.conversationId
  AND m.timestamp = (
           SELECT MAX(m.timestamp)
           FROM messages m
           WHERE m.conversationId = c.id)
  AND c.productId = pm.productId
  AND pm.sortOrder = '0'
  AND m.userId = u.id
GROUP BY c.id
ORDER BY m.timestamp DESC

I am not advocating the above as the right way to indent SQL, but, it is consistent, and it allows you to more easily see what is what in the query. What's nice is that you have consistently capitalized the keywords, etc. so that's good.
I am familiar with the above indenting/layout, so, I can now more easily see the next two issues....
Aliases:
You have the table messages twice in your query, once in the sub-select, and again in the main query. Both of these instances of the table have the alias m.... <sarcasm>this is not at all confusing... </sarcasm>
Group By:
Your group by clause is one of those things that will never be resolved to my satisfaction. MySQL has what I consider to be a bug.....(they call it a feature) ..... a massive, oh-my-god, how-could-they-do-that, what-were-they-thinking bug.
What does this mean practically? It means that your query makes no sense to anyone other than a MySQL expert. Your query makes no sense to me.... I can't help. I don't know what the expected behaviour is in your code. Your query does not even contain any aggregated values? Huh!
Next steps:

Figure out what you are grouping by (or even if the group-by is needed).
pull an explain-plan from the database when it runs the query.


Function to get current value or default from a string of two values

Potential Issues

a naive string replacement could change more than just the placeholders; for instance, when another part of the script uses the same string as a literal
the replacement can introduce a value with the same format {%}; your sql has no way of knowing that this is a replacement value, and since the format matches that of a place holder, it will be ignored and the default value will be taken
make sure the sql user of your unit test project has limited rights, because you don't know the exact sql that is going to run at runtime

If you insist on using a string replacement, try to manage escape characters and try to avoid false positives/negatives, both from sql and C# injection.


Calculating holes on a Tetris grid quickly

You can do this faster by doing the whole row at once instead of one bit at a time.  All you need to do is to keep a mask of bits that correspond to your firstFound booleans.  To match the OP's counting scheme (which can triply count a hole), I keep three masks: an underMask, an lNeighborMask, and an rNeighborMask.  underMask is used to count holes underneath the topmost filled square in a column.  lNeighborMask is used to count holes to the left of the column.  rNeighborMask is used to count holes to the right of the column.  (I edited my original answer to account for the triple counting).

The Code

public int calcHolesConverted(int[] grid)
{
    int gridMask      = (1 << xsize) - 1;
    int underMask     = 0;
    int lNeighborMask = 0;
    int rNeighborMask = 0;
    int foundHoles    = 0;

    for (int y = 0; y < ysize; y++) {
        int line   = grid[y];
        int filled = ~line & gridMask;

        underMask     |= filled;
        lNeighborMask |= (filled << 1);
        rNeighborMask |= (filled >> 1);

        foundHoles += setOnes1024[underMask & line] +
                      setOnes1024[lNeighborMask & line] +
                      setOnes1024[rNeighborMask & line];
    }
    return foundHoles;
}

In this code, setOnes1024 is an array of size 1024 which contains the number of 1 bits in the corresponding index.  It is analagous to your setOnes array.  Also, this code assumes that the bits to the left of the leftmost column will all be 0.  If they are not, then you will need to adjust lneighborMask to not contain bits outside the valid columns.

The Timing Test

I ran this timing test by converting both functions to C and running them on the same randomized grid (20000000 iterations each function).

OP's function    : 8.2 seconds
Modified function: 1.4 seconds


[Char] is usually written as String.

You have a redundant base case: nameMatch [] [].

The parameter names are a bit off.  A common convention for naming the head and tail is x:xs.

nameMatch :: String -> String -> Bool
nameMatch [] _      = True
nameMatch abbrev [] = False
nameMatch abbrev@(a:as) word@(w:ws)
   | a == w    = nameMatch as ws
   | otherwise = nameMatch abbrev ws

For printing the output, if you want each result to be on a separate line rather than as a list (which would produce output like ["Trollh\228ttan"]), then write

mapM putStrLn $ filter (nameMatch search) cities


As you are doing calculations on all values where the result depends on both loops, there isn't much that can be done about the complexity, at least not without knowing what you do with the result (which seems to be just discarded in the code shown).

There are some things that you can do in the innermost loop:

Instead of first using Contains and then get the value, you can use TryGetValue directly.

You know that term exists in the other collection, so you don't need TryGetValue for that one.

Squaring is done a lot faster by just multiplying instead of using Math.Pow.

if (word_i.Value.TryGetValue(term,out a)) {
  b = word_j.Value[term];
  sim += a * b;
  sqrta += a * a;
  sqrtb += b * b;
}


What to do with the Exception when you fail to close() a resource?

At least in code that I've seen, it is very common to ignore exceptions when closing a resource. In fact Apache Commons IO has a number of closeQuietly functions just for this purpose.

Also, the work being done with raFile should be wrapped in a try, with the close/closeQuietly being called in the finally. This ensures that close/closeQuietly is called even if an exception occurs while working with the file.

RandomAccessFile raFile = new RandomAccessFile(articleFile, "r");
try {
  if (this.isToInclude(raFile, conditionMap)) {
    return true;
  }
}
finally {
  IOUtils.closeQuietly(raFile);
}

Also, if you are using Java 7, you might want to check out the new try-with-resources statement.


A variadic C function for concatenating multiple strings

Always return allocated string or never do it

This code here:

if (count < 1)
{
    return "";
}

is bad because you return a static string whereas the normal case returns a string allocated by malloc.  If the caller then tries to free this static string, it will cause some kind of error.  You can fix this by either returning an allocated empty string:

if (count < 1)
{
    return calloc(1, 1);
}

or by just returning NULL:

if (count < 1)
{
    return NULL;
}

Memory leaks

Your function never frees p or len_array.  Actually, I would probably not even use temporary arrays like these.  If I were to write this function, I would measure the total length on one pass, and then copy the strings on a second pass.

Rewrite

After fixing the above issues, my rewrite of your function would look like this:

char *mystrcat(int count, ...)
{
    va_list ap;
    size_t  len = 0;

    if (count < 1)
        return NULL;

    // First, measure the total length required.
    va_start(ap, count);
    for (int i=0; i < count; i++) {
        const char *s = va_arg(ap, char *);
        len += strlen(s);
    }
    va_end(ap);

    // Allocate return buffer.
    char *ret = malloc(len + 1);
    if (ret == NULL)
        return NULL;

    // Concatenate all the strings into the return buffer.
    char *dst = ret;
    va_start(ap, count);
    for (int i=0; i < count; i++) {
        const char *src = va_arg(ap, char *);

        // This loop is a strcpy.
        while (*dst++ = *src++);
        dst--;
    }
    va_end(ap);
    return ret;
}


Java is an Object Oriented language... and I recognize that objects are not always the right solution to a problem.... The generally accepted "opposites" of object-orientation, though, are "procedural", and "functional". It is common (for example, in C) to write code as a collection of procedures, or (in haskell) to write it as functions.

In almost no languages, though, is it common to have no procedures, no objects, and no functions... well, except shell scripts, I guess. Your program has no methods, no objects, no functions, except the main method.

You need to break your code down in to parts that do logically isolated things, and then call those reusable chunks when needed.

Function 1

The first function I would extract, is a start-of-game match-count:

private static int getStartCount(Scanner sc) {
    while(true) {
        System.out.println("How many matches do you want to play with? "
                + "(from 6 to 60)") ;
        int totalMatches = sc.nextInt() ;
        if (totalMatches >= 6 && totalMatches <= 60) {
            return totalMatches;
        }
    }
}

Note, in that function I converted it from a do-while loop, to an infinite while-loop, with an early-return if the input is valid. I have nothing against do-while loops, but I find this early-return system simpler in terms of variable management. Note that the int totalMatches has a smaller scope than your code. You can call the code with:

int totalMatches = getStartCount(sc);

Function 2 (and 3)

Right, here's your input issue.... you have a big while loop, that plays each round, and inside that it has a user-input loop. The conditions on that loop are... confusing. What you have, is a prompt, some validation, and if everything is OK, you break. If there's a problem, you loop again. Again, extracting a function with an early return value, would be useful.

As an aside, when it comes to user input, it is almost always better to inform the user what input would be valid before requesting the input. Telling them they made a mistake afterwards is great, but telling them what their options are before, is better. Consider these two functions, the first function computes what would be a valid input, the second function uses that information to prompt the user:

private static int[] computeAllow(int totalMatches, int previous) {
    if (totalMatches == 1) {
        return new int[]{1};
    }
    if (totalMatches == 2 && previous < 3 && previous > 0) {
        return previous == 1 ? new int[]{2} : new int[]{1};
    }
    switch (previous) {
        case 0:
            return new int[]{1,2,3};
        case 1:
            return new int[]{2,3};
        case 2:
            return new int[]{1,3};
        case 3:
            return new int[]{1,2};

    }
    throw new IllegalStateException("Unexpected previous count " + previous);
}

Then, use this function like:

private static int getPlayerPick(Scanner sc, int totalMatches, int player, int previous) {
    if (totalMatches == 1) {
        System.out.println("There is only one match left on "
                + "the table") ;
    } else {
        System.out.println("There are " + totalMatches
                + " matches on the table") ;
    }

    final int[] allow = computeAllow(totalMatches, previous);

    while (true) {

        System.out.printf("Player %d: How many matches do you want to pick? %s",
                player, Arrays.toString(allow));

        final int matchesThisTurn = sc.nextInt();
        for (int a : allow) {
            if (a == matchesThisTurn) {
                // Valid input.
                return matchesThisTurn;
            }
        }

        System.out.printf("Wrong entry: there are %d matches, "
            + "the last player selected %d, "
            + "which means you can only select one of %s\n",
                totalMatches, previous, Arrays.toString(allow));
    }
}

Main

Puting this all together, the main method becomes much simpler:

public static void main(String[] args) {

    try (Scanner sc = new Scanner(System.in) ;) {

        int totalMatches = getStartCount(sc);

        int matchesPreviousTurn = 0 ;
        int round = 0 ;
        int player = 0 ;

        do {

            //previousPlayer = player ;
            player = 1 + (round % 2);
            round++ ;

            int matchesThisTurn = getPlayerPick(sc, totalMatches, player, matchesPreviousTurn);

            totalMatches -= matchesThisTurn ;
            matchesPreviousTurn = matchesThisTurn ;

        } while (totalMatches > 1 || totalMatches == 1 && matchesPreviousTurn != 1);

        System.out.println("*** The game is over! Player " + player
                + " Wins! ***") ;
    }
}

It is still probably too busy, but you can at least see what's going on now.

Note how the user is prompted with valid values before they are entered now:

How many matches do you want to play with? (from 6 to 60)
10
There are 10 matches on the table
Player 1: How many matches do you want to pick? [1, 2, 3]
4
Wrong entry: there are 10 matches, the last player selected 0, which means you can only select one of [1, 2, 3]
Player 1: How many matches do you want to pick? [1, 2, 3]
2
There are 8 matches on the table
Player 2: How many matches do you want to pick? [1, 3]
2
Wrong entry: there are 8 matches, the last player selected 2, which means you can only select one of [1, 3]
Player 2: How many matches do you want to pick? [1, 3]
3
There are 5 matches on the table
Player 1: How many matches do you want to pick? [1, 2]
3
Wrong entry: there are 5 matches, the last player selected 3, which means you can only select one of [1, 2]
Player 1: How many matches do you want to pick? [1, 2]
2
There are 3 matches on the table
Player 2: How many matches do you want to pick? [1, 3]
1
There are 2 matches on the table
Player 1: How many matches do you want to pick? [2]
2
*** The game is over! Player 1 Wins! ***


I'm not sure I'd compare the .width properties of a control and a range - hear me out.

Let's start with a table of relevant measurements

Inch       .5
cm         1.27
Pixel      48
Point      36
Characters 5.38

With a Range

In the excel UI you see two numbers - characters and pixels when manually adjusting width.

Characters being the number of characters with the font (I'm using default here- calibri 11) that can fit in the width of the range (yes, that's a ridiculous measurement unit).

In the Format menu for a range, the Column Width is also characters.

In VBA

Range.Width = points (Variant Double)
Range.ColumnWidth = characters (Variant Double)

.width here is giving us points which then must be divided by .75 to get to pixels to match the UI.

With a Form

The properties of an active x combobox on a form are

ComboBox1.ColumnWidths = points (String)
ComboBox1.Width = pixels (Single)
ComboBox1.ListWidth = points (String)

In the code

.ColumnWidths = GetColumnWidths(source.Range)
.ListWidth = IIf(ComboBox1.Width > source.Range.Width, ComboBox1.Width, source.Range.Width)

Essentially you set .ColumnWidths (String in points) with a String representing points. Nice.

Then you compare pixels to points and set ListWidth (String in points) with either pixels (as Single) or points (Variant Double).

There's no avoiding this mess, so I would break out another function that returns a String of points.

Yes, it's needlessly complicated to do so, unless someone is trying to debug some more complex version of this or you're like me and you hate that excel has done this.

    Dim myControlBox As Control
    Set myControlBox = Me.ComboBox1
    With myControlBox
        .ColumnCount = source.Columns.Count
        .ColumnWidths = GetColumnWidths(source)
        .ListWidth = GetListWidth(source, myControlBox)
    End With

Private Function GetListWidth(ByVal source As Range, ByVal myControlBox As Control) As String
    If myControl.Width > source.Width Then
        GetListWidth = myControl.Width * 0.75
        Exit Function
    Else: GetListWidth = source.Width
End Function

This answer took me longer to write that I'm willing to admit.


I took it to 6 to make it a little more readable:

def _animate_display(self, display):
    self._timer += 1 / bge.logic.getAverageFrameRate()
    symbolic_level = self.battery.get_symbolic_level()
    if self._timer >= 5.0:
        self._timer = symbolic_level / 25
    else:
        utils.change_texture(display, 'DisplayMat', 'icons/battery_{}.png'.format(next((x,y) for x,y in zip(xrange(100, -1, -25), xrange(4, -1, -1)) if symbolic_level <= x and self._timer >= y)))


Thumbnails for bootstrap carousel jQuery plugin

The only thing worse than missing alt text is bad alt text. 1_tn.jpg is meaningless. Instead, use empty alt text.
Your CSS looks okay. I'll note you can use padding: 5px 0 0;, with padding-left being automatically filled in.
You never use window in your plugin, so you don't need to pass it.
conf is shared across all instances of the plugin. Normally this is fine... but you're mutating conf, instead of using a separate variable to hold the defaults. This means that code like the below won't work as expected:

$(".thumbnails-carousel.not-centered").thumbnailsCarousel({ center: false });

// no need to specify because it's centered by default
$(".thumbnails-carousel.centered").thumbnailsCarousel();

Similarly, you are using a global shared "cache" which apparently holds a jQuery object created from a hard-coded string. In doing so, I am no longer able to:

dynamically generate the carousel
give the carousel my own class name
use more than one carousel in a non-buggy way

Instead, use instance variables. After all, you're providing $.fn.thumbnailsCarousel. When you call $(".thumbnails-carousel").thumbnailsCarousel(), $(".thumbnails-carousel") is passed in as this!
refreshOpacities() is oddly named. After going through it twice I now understand that it's just synchronising the active thumbnail with the active carousel image. Can you rename this function?
bindUiActions() is okay but the lowercase i is bugging me... although some may argue that this is perfectly fine (à la getElementById()...).
There's no point in explicitly specifying the empty object when calling .thumbnailsCarousel(), since $.extend(x, undefined) === x.

The following point becomes less relevant as you address the above points, mostly because I believe you should refactor the referenced code out anyway.

In init(), you use cache.$carouselContainer.find(".carousel-control"), which is plain silly because you already have cache.$controls.


Map markers on a canvas that pop up boxes when clicked

My comments are more just on style as opposed to performance:

Instead of using :

if(box.el.css('visibility') == 'hidden'){

it's more readable to use :

if(box.el.is(":hidden")){

And similarly, instead of using :

box.el.css('visibility', 'visible');

you can use :

box.el.hide();

A note on this one though, these are not exactly equivalent because hide actually sets display: none.  In this case though I believe that's fine.

And one final comment, it's a good practice to name variables which contain jQuery objects with a $ at the beginning.  This allows you to know that the variable is already a jQuery object without going back in the code to check and avoids accidentally creating jQuery objects out of objects that were already jQuery objects.

So something like this:

var t = $(this),
    name = t.text()

would become this:

var $t = $(this),
    name = $t.text()


A Sine Template Function For Boost.MultiArray in C++

It looks very simple and clean. I would change the name of with_std_sin though. There are some guidelines for naming concepts that suggest that it should be named sinable. That looks a bit weird, but everything I can think of to describe "something that std::sin supports" looks weird in some way, so it is as good as any name.
However, consider that you might want to apply many other functions to the contents of a boost::multi_array as well, not just std::sin. In that case, a recursive_transform() that handles multi_arrays is the way to go, so you could "just" write:
auto test_result = recursive_transform(A, [](auto &x){return std::sin(x);});

Or at least use that to define sin(), cos() and so on in therms of recursive_transform() without having to duplicate code.


You could define a sorted list of the types and use that to sort the input. Here's what a function that does that would look like.

let sortArticles : seq<obj> -> seq<obj> =
    let sorted =
        [
            typeof<ArticleSubmission>
            typeof<seq<Photos>>
            typeof<ArticleReviewRating>
            typeof<BusinessReviewRating>
            typeof<seq<ArticleTags>>
        ]
    Seq.sortBy (fun o -> sorted |> List.findIndex ((=) (o.GetType())))


Polymorphic animals speak their name and make a noise

Item 1
Instead of Animal new: n use Animal named: aString implemented on the class side of Animal as:

named: aString
    ^self new name: aString

Then in the instance side of the class define

name: aString
    name := aString

Item 2
Yes, new is inherited by the subclass. The same happens with all class methods; they are inherited by subclasses.

Item 3
You don't have to implement new, unless you want to do something special in your class. In most dialects (I haven't checked GNU Smalltalk) new will call the instance method initialize, which by default does nothing. If you need to initialize you instances, then implement initialize as

initialize
     super initialize.
     "your specific code"

Item 4
Can't help on this one but yes, the usual message for creating a subclass includes a keyword for declaring named instance variables.

Item 5
You have two options here. (1) You can implement sound in Animal as self subclassResponsibility. (2) You can implement it with a default value ^oops. The first alternative will indicate the programmer extending the hierarchy what method they must to provide in the new subclass. The second will just provide a default sound for the programmer to find out and refine.

---EDIT---

A more realistic implementation (meaning, one not intended to test OOP concepts in Smalltalk) would get rid of the name instance variable of Animal. This is possible because the class name already provides the animal's name. In other words, the instance doesn't need to "remember" its name because its class already knows it. Here is the instance side code

name
    ^self class name asLowercase

Note that instances of the abstract class Animal will now answer the string 'animal' as their name.

With this simplification the instance creation method (class side) named: would no longer be required. However, we could tweak its implementation so it answers an instance of the appropriate subclass:

named: aString
    | subclass |
    subclass := Animal withAllSubclasses
        detect: [:class | class name asLowercase = aString] ifNone: [self].
    ^subclass new

With these changes we no longer need the name instance variable and also will be able to create, say an instance of Horse evaluating: Animal named: 'horse', etc.


I can't imagine why do you do this via Reflection, I believe the same can be done by walking through Controls tree. Your method will not work if context menu has property Generate member set to false in designer.

var contextMenus = fields.Where(f => f.GetValue(this).GetType() == typeof(ContextMenuStrip));
var menus = contextMenus.Select(f=> f.GetValue(this));
return menus.Cast<ContextMenuStrip>();

Can be replaced with:

return fields.Select(f => f.GetValue(this)).OfType<ContextMenuStrip>();


Rust, compute gcd: modularity, references

You do not need to take the numbers by reference.
Do not put an underscore at the beginning of the variable name. A variable name beginning with _ is used to say to the compiler that the variable is unused.

Otherwise, I see no issues in your code. Here is the solution taking account of my comments:

pub fn gcd(mut a: i64, mut b: i64) -> i64 {
    while b != 0 {
        let tmp = a;
        a = b;
        b = tmp % b;
    }
    a
}

#[cfg(test)]
mod tests {
    use ::gcd;

    #[test]
    fn test_gcd() {
        assert_eq!(gcd(60, 168), 12);
        assert_eq!(gcd(1071, 1029), 21);
    }
}

Further explanations:

  Why do I need to use let a = instead of let mut a = when calling it?

Not sure if my explanation is legit, but when you give a thing to another function, this function can do whatever it wants to this thing: it can take it as mutable or not. That is not anymore the problem of the previous owner.

  Which type of variables should and should not be passed by reference?

This is a very broad question. I advice you to think things differently. In Rust, you can give a thing, or only lend it (the thing is borrowed). The general answer is: if you do not need anymore the thing, or if the receiver needs a full control on it, give it away.

In this specific case, the thing is copyable and small (as small as a reference, in fact). So, borrow it does not give any advantage: just take it (or take a copy) and do not bother with references.


A traits class for (compound) pointers - beyond what std::pointer_traits offers

First, size_t should be std::size_t everywhere.

Why don't the raw pointer/array cases have release()? Granted, it won't really change any ownership in reality, but it could conceptually.

static ptr_type make(size_t count) { return new T[count]; }
static ptr_type make()             { return new T;        }

I'm not sure this interface is a good idea as is. This only supports Ts with default constructors. What about constructor arguments:

template <typename... Args>
static ptr_type make(Args&&... args)
{
    return new T{std::forward<Args>(args)...};
}

But of course, if you do that, it conflicts with the make(std::size_t) overload. So you'd need a different name for that, like make_n() or something, maybe with an interface like:

template <typename... Args>
static ptr_type make_n(std::size_t count, Args&&... args)
{
    return new T[count]{std::forward<Args>(args)...};
}

However, what about the difference between T{...} and T(...)? Now you need overloads for those cases, too.

Now, as for the overall idea, I'm not a committee member, but I can tell you with absolute certainty that this will never be accepted.

First, what actual problem in use is this supposed to solve? What is an actual use case where this is necessary and offers a significant improvement? I can't think of any situation where this will be useful. Certainly not one that's generalizable, which is mandatory for a standard library addition.

Generally speaking, memory management should be handled by containers, and containers use allocators, and this has no allocator support whatsoever.

Even worse, it hides the allocation method from client code... which is disastrous because you need to know how something was allocated to know how to DEallocate it. As it is, your interface offers a "handy" way to allocate memory, but no way to free it, and in fact goes out of its way to make code less safe by stripping ownership from smart pointers with the release() function.

In summary, I see no general gain from this, and plenty of dangerous drawbacks.


Architecture and error handling in simple java program

General architecture

A useful architecture guideline is:

By introducing classes and methods, I create the high-level language that I want
to use for expressing my solution.

So, It's a good idea to start from the most abstract top-level, and later implement the methods needed at that top-level code. So I'd like to rephrase your program (top-level) as follows:

Read the output filename: String outputFile = readWithPrompt(reader, "Enter a filename for the output:");
Read the first input filename: String sourceToCopy = readWithPrompt(reader, "Enter the path of the file to be copied");
Read the second input filename: String sourceToAppend = readWithPrompt(reader, "Enter the path of the file to be appended");
Combine the files: combineFiles(sourceToCopy, sourceToAppend, outputFile);

This keeps user interface and business logic apart, which I highly recommend!

Reading the three file names is three times the same, so I used a common phrase (= calling the same method, just with different prompting strings).

The main business of your program is to combine two input files into one output file, so I made that explicit at the top-level.

I like your distinct append() method. It's useful on its own, not only in your combine-two-files setting. You could even implement the whole thing by first creating an empty file, and then twice append some source file to it.

Where to read user input

Always separate user interface from doing things. Imagine that tomorrow you want to combine all files from one directory with a common footer (e.g. your company's legal stuff). Then you no longer want to ask the user for every single file, but you'll still be combining pairs of input files into an output. You can then easily re-use a clean business method, but not one mixing user I/O and business.

Error handling

I like your exception handling in the main method.

The single most important guideline is: A method should throw an exception if it couldn't do its job.

So, if during the files copying something went wrong, you ended up with a missing or corrupt result. The caller of combineFiles() can normally assume that after that call, the output file has the correct content. If not, he needs to know about that, and that's done by throwing an exception (or not catching an exception that came from some inner calls).

Exception handling is a big topic with diverging opinions between the professionals, too much to go into more details here. As long as you follow the guideline, you can't be going wrong.

Javadoc

Your Jacadocs are mostly fine. I wish most real-world programs were documented like that. Sigh!

  Reads inputs, copies second file to first and calls method to append file

Here's one quirk: you say "calls method", and that's breaking encapsulation. Javadocs should describe a method as a black box, how it behaves to the outside world. For the Javadoc, it doesn't matter if the method does its job all by itself or by calling hundreds of other methods. Only describe things that have an effect visible to your caller.

When describing the append() method, you thoughts were probably withing your overall task, so the text shows parts of what the append() method is meant for ("final result file") in the whole program instead of just describing what it does (append one file to the existing contents of another file).

Class names, packages

Nothing to complain about your class names.

"Solution" is not the most inventive, but a valid name for such a compact program.

"FileProcessor" is a perfect name for a class like yours.

But when you start to do serious stuff, you should get into the habit of organizing your classes into packages with unique names, with low risk of colliding with packages from external libraries, typically by using something like a reversed domain name or identity e.g. com.facebook.username, something that's unlikely to be used by someone else.

Finally, I'd like to warn about wildcard import statements like your import java.io.*;. This makes all class names from the java.io package visible in your code. At a first glance, that's fine, you can abbreviate java.io.FileOutputStream to just FileOutputStream in your code.

But maybe, in some future Java version, a class named FileProcessor gets included into the java.io package. Then the confusion starts: does FileProcessor mean your class or the one from java.io?

While exactly that is well-defined (it will be your class as long as you're in the same package), wildcard imports can cause real trouble in related, similar situations. Every decent, modern IDE has the ability to manage individual imports for you, so replacing the wildcard import with the necessary individual imports should be "one click" and then avoids the risk I described here.

Indentation

The indentation of your code looks mostly fine, but a few lines are out of sync. So probably, you did at least some of it manually. In your IDE, look for automated code indentation or formatting. No need to waste time hitting the space key multiple times, and as a result of the automated feature, your code always looks tidy.


Printing all the permutations of a string in alphabetical order

A boolean tested each time, and firing just once on the first iteration is unaesthetic (and a waste of time). Consider instead

    std::cout << record;
    while (std::next_permutation(record.begin(), record.end())) {
        std::cout << ',' << record;
    }
    std::cout << '\n';

Otherwise looks good. Congratulations for not using namespace std.


Generating random number from a binomial distribution

The RDRAND instruction generated from the _rdrand64_step intrinsic is actually very slow, though high quality (modulo some concerns about back doors). Depending on the processor it may take hundreds (Ivy Bridge through Skylake) or even thousands (Intel Atom, AMD) of cycles per RDRAND. So just replacing the random number generator will help a lot.

For example, xoroshiro128+ is a relatively fast PRNG, it has some weaknesses but they don't seem too bad for this purpose. An interesting aspect is that it contains no operation that must go to execution port 1 on Intel processors, so its operations do not "fight" the popcnt much, in contrast to PRNGs that contain multiplication.

So overall, something like this:

static inline uint64_t rotl(const uint64_t x, int k) {
    return (x << k) | (x >> (64 - k));
}

static uint64_t s[2];

uint64_t next(void) {
    const uint64_t s0 = s[0];
    uint64_t s1 = s[1];
    const uint64_t result = s0 + s1;

    s1 ^= s0;
    s[0] = rotl(s0, 24) ^ s1 ^ (s1 << 16); // a, b
    s[1] = rotl(s1, 37); // c

    return result;
}

int64_t rbinom(int64_t size) {
    if (!size) {
        return 0;
    }

    int64_t result = 0;
    while (size >= 64) {
        result += _popcnt64(next());
        size -= 64;
    }

    result += _popcnt64(next() & ~(UINT64_MAX << size));

    return result;
}

Elsewhere in the application, the state s must be seeded with a non-zero random-enough number. For example, you could use _rdrand64_step to seed it once, at the start of the application.

But different strategies are possible. With a size in the thousands or even millions (as indicated in the comments), SIMD could be used both to generate pseudo-random bits and to accumulate the pop-counts. Using some techniques from Faster Population Counts Using AVX2 Instructions (mainly, reducing the amount of actual pop-counting by using carry-save addition) and Xorshift+ as PRNG (I avoid rotate because AVX2 does not have them built in, and multiplication because AVX2 also has no 64bit integer multiply built in), it could look like this:

__m256i bigstate0, bigstate1;

__m256i xorshift128plus_avx2(__m256i *state0, __m256i *state1)
{
    __m256i s1 = *state0;
    const __m256i s0 = *state1;
    *state0 = s0;
    s1 = _mm256_xor_si256(s1, _mm256_slli_epi64(s1, 23));
    *state1 = _mm256_xor_si256(_mm256_xor_si256(_mm256_xor_si256(s1, s0),
        _mm256_srli_epi64(s1, 18)),
        _mm256_srli_epi64(s0, 5));
    return _mm256_add_epi64(*state1, s0);
}

__m256i popcnt_AVX2(__m256i x) {
    const __m256i popcntLUT = _mm256_setr_epi8(
        0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
        0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4
    );
    const __m256i nibmask = _mm256_set1_epi8(15);
    const __m256i zero = _mm256_setzero_si256();

    __m256i L = _mm256_shuffle_epi8(popcntLUT, _mm256_and_si256(x, nibmask));
    x = _mm256_srli_epi16(x, 4);
    __m256i H = _mm256_shuffle_epi8(popcntLUT, _mm256_and_si256(x, nibmask));
    return _mm256_sad_epu8(_mm256_add_epi8(L, H), zero);
}

__m256i CSA(__m256i a, __m256i b, __m256i c, __m256i *carry) {
    __m256i t0 = _mm256_xor_si256(a, b);
    __m256i t1 = _mm256_xor_si256(t0, c);
    *carry = _mm256_or_si256(_mm256_and_si256(a, b), _mm256_and_si256(t0, c));
    return t1;
}

int64_t rbinom_AVX2(int64_t size) {
    if (!size) {
        return 0;
    }

    int64_t result = 0;

    __m256i sum1 = _mm256_setzero_si256();
    __m256i sum2 = sum1;
    __m256i sum4 = sum1;
    __m256i sum = sum1;
    while (size >= 2048) {
        __m256i sample0 = xorshift128plus_avx2(&bigstate0, &bigstate1);
        __m256i sample1 = xorshift128plus_avx2(&bigstate0, &bigstate1);
        __m256i sample2 = xorshift128plus_avx2(&bigstate0, &bigstate1);
        __m256i sample3 = xorshift128plus_avx2(&bigstate0, &bigstate1);
        __m256i sample4 = xorshift128plus_avx2(&bigstate0, &bigstate1);
        __m256i sample5 = xorshift128plus_avx2(&bigstate0, &bigstate1);
        __m256i sample6 = xorshift128plus_avx2(&bigstate0, &bigstate1);
        __m256i sample7 = xorshift128plus_avx2(&bigstate0, &bigstate1);
        // reduce weight 1
        __m256i c0, c1, c2, c3;
        __m256i t0 = CSA(sample0, sample1, sample2, &c0);
        __m256i t1 = CSA(sample3, sample4, sample5, &c1);
        __m256i t2 = CSA(sample6, sample7, sum1, &c2);
        sum1 = CSA(t0, t1, t2, &c3);
        // reduce weight 2
        __m256i c4, c5;
        __m256i t3 = CSA(c0, c1, c2, &c4);
        sum2 = CSA(c3, t3, sum2, &c5);
        // reduce weight 4
        __m256i c6;
        sum4 = CSA(sum4, c4, c5, &c6);
        sum = _mm256_add_epi64(sum, _mm256_slli_epi64(popcnt_AVX2(c6), 3));
        size -= 2048;
    }
    sum1 = popcnt_AVX2(sum1);
    sum2 = popcnt_AVX2(sum2);
    sum4 = popcnt_AVX2(sum4);
    sum = _mm256_add_epi64(sum, sum1);
    sum = _mm256_add_epi64(sum, _mm256_slli_epi64(sum2, 1));
    sum = _mm256_add_epi64(sum, _mm256_slli_epi64(sum4, 2));
    result += _mm256_extract_epi64(sum, 0);
    result += _mm256_extract_epi64(sum, 1);
    result += _mm256_extract_epi64(sum, 2);
    result += _mm256_extract_epi64(sum, 3);

    while (size >= 64) {
        result += _mm_popcnt_u64(next());
        size -= 64;
    }

    result += _mm_popcnt_u64(next() & ~(UINT64_MAX << size));

    return result;
}

Algorithmic tricks such as the alias method may be appropriate. I have no experience with this so I cannot explain it or even really recommend it, but it's something to look into.


Flux: async communication with websockets

ActionCreator.js

Why write a class for when you just export a single instance? When one makes a class, one expects to be able to make multiple instances. This doesn't. You can just roll with object literals. You could even just write functions and just export them.
service is undefined. Where is it?

todo-service.js

Same as above, why write a class?

WebSocketWrapper.js

Same as above, why write a class? Even more interesting is that you have "tracking variables" (reqId and responseDeffers) outside the class.
Not sure how you'd benefit with let in you code. You're declaring them at the very top of a function scope. var would have sufficed.

Just because JS has ES6 doesn't mean you have to use classes, let and all the new stuff.


It sounds like Earth cannot exist without an ID and the UpdateUniverse boolean flag. As such, you need a constructor that enforces this:

public Earth(int id, bool updateUniverse)
{
    // the rest of the code that went in Earth(Earth m)
}

If you still need a parameterless constructor because WCF needs it, that's fine. You can extract that constructor into its own method:

public Earth(int id, bool updateUniverse)
{
    SetId(id, updateUniverse);
}

public void SetId(int id, bool updateUniverse)
{
    // the rest of the code that went in Earth(Earth m)
}

I'm also questioning why this class needs a reference to the data access layer at all. It actually looks like you need planetX for an Earth to even exist.

What is planetX, another Earth? I'm getting lost here. Which Earth are we talking about, and how many are there? The real problem is that this class is doing too much. It is doing data access, which needs to happen in the code using the Earth objects, not inside the Earth class.

Judging by your first code block, this seems more appropriate:

Earth earth = new EarthDataAccess().GetById(11);

// now just use a fully populated Earth object

Pulling an Earth object from the database should not involve more lines of code than that.


High execution time of LCS length program in Python2

That looks like a classic LCS solution to me.

If all you want is to read the bottom-right element of the tableau, you don't actually have to store the entire matrix: all you need to keep is the most recent row.  That could save you a few megabytes of memory — I don't know how much processing time that would save, though.

To initialize the arrays, you can use the * operator instead of a list comprehension.  The indexing would be a bit less awkward, in my opinion, if you enumerated starting from 1.  I suggest c1 and c2 for characters out of s1 and s2, respectively, but that's a matter of personal taste.

def lcs_len(s1, s2):
    prev_lcs = [0] * (len(s2) + 1)
    curr_lcs = [0] * (len(s2) + 1)
    for c1 in s1:
        curr_lcs, prev_lcs = prev_lcs, curr_lcs
        for j, c2 in enumerate(s2, 1):
            curr_lcs[j] = (
                1 + prev_lcs[j - 1] if c1 == c2 else
                max(prev_lcs[j], curr_lcs[j - 1])
            )
    return curr_lcs[-1]


Follow-up: Randomizing Civilization 5 team choice

Your indentation is generally fine, except the Draw procedure isn't indented as it should; everything in a Sub block should be indented 1 level, so that this:

Next noOfPlayers
End Sub

Becomes that:

    Next noOfPlayers
End Sub

I like that you have lots of small functions - that's very good!

However Draw could be further broken down; I'm removing the fluff to illustrate:

Public Sub Draw()
    For
        For
            While
                For
                    '...
                Next
            Wend
        Next
    Next
End Sub

That's 4 layers of nested loops! I've seen worse arrow code, but I'd extract a method out of the body of the 2nd For loop, to make it look like this:

Public Sub Draw()
    For
        For
            ExtractedMethodCall
        Next
    Next
End Sub

Other than that, looks great!


I think one thing that you could do is to call result.reserve(items.size()) (as long as you expect that items can be queried for size()) just after you declare it. That would prevent the vector from allocating new space each time new element is added and/or being copied from time to time as the elements are being added to it, which may result in increased performance, especially when items contains a lot of elements and/or of large size.

It's possible that compiler optimizations would do the same to you, but it won't hurt if you put it anyway just in case. Besides, optimizations might be turned off in debug mode.

Also, since you don't modify items, it's better to make it const auto& for the sake of const correctness and pass it by reference to avoid unnecessary copying as @Deduplicator has pointed out. The same goes for item in the range loop if fun is not to modify it.


Making as many unique strings as possible by removing two characters

Instead of using string.Remove (and creating a 2 string for each index combination), you could create an array of chars / ints and work on that array.
You dont have to iterate from i = 0 to i = str.Length and j = 0 to j.str.Length because that results in duplicated indexes (e.g. 1,2 and 2,1).
The idea with the hashes is good, but as mentioned in comment, you have to check for all "uncertain duplicates" if they are actually duplicates.

The following code shows a simple implementaion that considers the points above:

public class Variation
{
    public Variation(int hash, int index1, int index2)
    {
        Hash = hash;
        Index1 = index1;
        Index2 = index2;
    }
    public int Index1 { get; }
    public int Index2 { get; }
    public int Hash { get; }
}

public int CountVariantions(string input)
{
    int[] inputArray = input.ToCharArray().Select(c => (int)c).ToArray();
    var variations = new List<Variation>();
    for (int i = 0; i < input.Length; i++)
        for (int j = i + 1; j < input.Length; j++)
            variations.Add(GetVariation(inputArray, i, j));

    var groups = variations.GroupBy(v => v.Hash).ToArray();

    var uncertainDublicates = groups.Where(g => g.Skip(1).Any()).ToArray();

    var dublicatesRealCount = GetRealCount(inputArray, uncertainDublicates);

    return groups.Length - uncertainDublicates.Length + dublicatesRealCount;
}

private int GetRealCount(int[] inputArray, IEnumerable<IGrouping<int, Variation>> duplicates)
{
    // todo: check if the duplicates are actually identically
    return duplicates.Count();
}

private static Variation GetVariation(int[] inputArray, int index1, int index2)
{
    var hashValue = Enumerable
        .Range(0, inputArray.Length)
        .Where(i => i != index1 && i != index2)
        .Select(i => inputArray[i])
        .Aggregate((hash, val) => hash ^ val);

    return new Variation(hashValue, index1, index2);
}


Non-recursive implementation of MergeSort

The approach may lose the stability. If list a contains a1, a2, and list b contains b1, b2 and all of them are compared equal, the resulting list will have a a1, b1, a2, b2, whereas the stable result should be a1, a2, b1, b2. The fix is to not special case a[count1] == b[count2]:

if b[count2] < a[count1]:
    merge from b
else:
    merge from a

Your big-O worries are unfounded. At the \$k\$'th iteration there remain \$O(\frac{n}{2^k})\$ sublists, but the length of each sublist is \$O(2^k)$\$, so the entire body of the inner loop executes in \$O(n)\$ time regardless of the iteration; and as you noticed there are \$O(\log{n})\$ of them.


Epilogue to a binary search to find the range of matching indexes

There are three alternatives you should consider. Depending on circumstances, I have used all three.

The most simple, is to comment the block.

while (lastSucceedingIndex < tailIndex && (array[++lastSucceedingIndex] == key)) {
    //loop condition terminates when key is not found, or data runs out.
}
lastSucceedingIndex--;

The comment should shut down the error.

The second approach is to simplify the loop condition to match your code and to make the dependent code part of the loop. The pre-increment is essentially your "work" which should be in the block... but, because it is a pre-increment, it is messy... Still, your code would become...

while (lastSucceedingIndex < tailIndex) {
    lastSucceedingIndex++;
    if (array[lastSucceedingIndex] != key) {
        break;
    }
}
lastSucceedingIndex--;

That's still not as neat as I would like, but it reduces the complexity of the while condition and makes the break-out process more apparent.

This last alternative is simpler in other ways:

while (lastSucceedingIndex < tailIndex && array[lastSucceedingIndex + 1] == key) {
    lastSucceedingIndex++;
}

Now there is no need for the corrective decrement.


The code seems good to me. You have one bug and some unnecessary code.

First of all, it's not clear what types of values can be stored in the heap. It looks like it's supposed to be positive numbers, but the only place you check for this is in the decrease-key function. But there's actually not anything stopping callers from attempting to store strings, negative numbers, classes, etc. This will lead to bizarre behavior. I think you need to validate the input and make sure only the right type of data is going in.
It's not necessary to end your functions with return
The line

(this.heap[index]<this.heap[parent])? this.heapifyUp(index) : this.heapifyDown(index);

should be written as a normal if, not a ternary.
This line

this.heap.slice((this.heap.length-1), 1);

is repeated several times; perhaps it should be brought into its own helper method with an explanatory name (suggest deleteLastElement()).
In extractMin(), this line:

swap(this.heap, 0, (this.heap.length-1));

performs unnecessary work. The last element is about to be deleted, so you don't need to put anything there. Just say

this.heap[0]=this.heap[this.heap.length-1]`

A conceptual problem is that you only allow accessing nodes by index. How is someone using your code supposed to know what the index is? An item could move around the heap a lot due to inserts and removals and heapify calls. This applies to decrease() and delete()
heapifyDown() has a bug. Consider the heap represented by [4,6,5,7] and what happens if you extractMin().
decreaseKey() has a bug, but I'm not going to find this one for you.


Recursion: Count from x until n and backwards

If you print a sequence of numbers from \$x\$ through \$n\$ in increasing order, and then the same sequence in decreasing order, you'll get a row of numbers which starts and ends with \$x\$ and contains an analogous double sequence of numbers \$x+1\ldots n\$ between, right?

For example a sequence from 2 to 5 and back is: 2, sequence from 3 to 5 and back, and 2 again:

2 [3 4 5 5 4 3] 2

So the simplest solution would be a recursion like this:

void printNumberSequence(int x, int n)
{
    cout << x << endl;
    if(x < n) printNumberSequence(x + 1, n);
    cout << x << endl;
}

If you want to avoid doubling the greatest number, e.g. for numbers 2 through 5 you want the output like:

2 3 4 5 4 3 2

just execute the second cout << ... under the if(), that is when you're not at the maximum number:

void printNumberSequence(int x, int n)
{
    cout << x << endl;
    if(x < n)
    {
        printNumberSequence(x + 1, n);
        cout << x << endl;
    }
}


Group-wise deviations from means / centering with dplyr vs. data.table

This answer only goes to how to speed up processing and doesn't get at the intricacies of data.table vs dplyr under the hood.

Below is a slightly faster version (at least for larger datasets).

Rather than create additional columns in the main DT, I created a new DT that had the mean values for each. As that had a 6-fold smaller size, the second DT has to be keyed and then joined back to the original.

This produces a bunch of extra columns (with values from x), so that's why we only selection columns of [,1:length...].  Note that subtraction of two DTs ignores column labels and assumes the same order of all the columns - i.e without the setcolorder, mean_x has "cell" being the first column, which results in the wrong columns being subtracted.

center_dt_3 <- function(x) {
  setDT(x,key="cell")
  x_fullnames <- names(x)
  mean_x <- x[,lapply(.SD,mean, na.rm=TRUE),by=cell]
  setcolorder(mean_x,x_fullnames)
  setkey(mean_x,cell)
  res<-x-mean_x[x,][,1:length(names(mean_x))]
  res[,cell:=NULL]
  setDF(res)
  return(res)
}

Perhaps your package version of microbenchmark is different than mine

bench_all <- rbind(bench_small %>% summary %>% mutate(expr = paste0(expr,"_small")),
                   bench_large %>% summary %>% mutate(expr = paste0(expr,"_large")))

bench_all

             expr        min        lq       mean     median         uq        max neval
1 ans_dplyr_small  14.016470  14.63970  16.057286  14.919529  15.477332  26.772788    10
2   ans_dt1_small   2.033062   2.13456   2.349156   2.189441   2.638336   2.754370    10
3   ans_dt2_small   2.217810   2.27483   2.438935   2.407972   2.628640   2.661144    10
4   ans_dt3_small   2.925432   3.00355   3.896746   3.093642   3.514454  10.440436    10
5 ans_dplyr_large 660.563300 677.73756 709.718870 695.432125 707.791010 848.521906    10
6   ans_dt1_large  54.344144  55.17835  59.058532  56.304646  62.696206  69.227890    10
7   ans_dt2_large  21.906666  22.25135  23.184892  22.716924  23.423408  28.072566    10
8   ans_dt3_large   8.380004   8.94536   9.065873   9.136237   9.218774   9.665814    10

Doing this a bit more natively in data.table (unfortunately I couldn't figure out how to dereference in x and i, as with=FALSE assumes the name of each list is e.g. x.x_names)

center_dt_4 <- function(t) {
  setDT(t,key="cell")
  x_fullnames <- names(t)
  x_names <- x_fullnames[which(x_fullnames != "cell")]
  mean_x <- t[,lapply(.SD,mean,na.rm=TRUE),by=cell]
  res<-t[mean_x,.(A=x.A-i.A,B1=x.B1-i.B1,B2=x.B2-i.B2),on="cell"]
  setDF(res)
  return(res)
}

> bench_all
                        expr        min         lq       mean     median         uq        max neval
1            ans_dplyr_small  14.366576  14.494300  15.392998  14.925517  15.385244  20.094272    10
2              ans_dt1_small   2.029644   2.216670   2.384766   2.381316   2.554228   2.729282    10
3  ans_dt1_precompiled_small   3.341396   3.495352   3.804031   3.781878   4.003972   4.439324    10
4              ans_dt2_small   2.155372   2.321018   2.463510   2.405263   2.584166   2.936550    10
5              ans_dt3_small   2.638620   2.760072   2.859517   2.873259   2.965346   3.063422    10
6              ans_dt4_small   1.925294   1.930712   2.961612   2.119307   2.510894  10.003090    10
7            ans_dplyr_large 672.502800 677.593296 692.047965 685.753199 706.827080 716.847560    10
8              ans_dt1_large  55.923322  56.490104  59.640225  60.677824  62.484374  63.247306    10
9  ans_dt1_precompiled_large 135.373544 139.275732 141.147599 141.397891 142.505084 150.496206    10
10             ans_dt2_large  21.825126  22.328332  23.785973  22.710226  23.469594  29.990162    10
11             ans_dt3_large   8.644578   8.912002   9.775805   9.052987   9.578002  15.339058    10
12             ans_dt4_large   7.787560   8.263110   8.517451   8.644150   8.788840   8.970734    10


Finding a very quick/reliable solution was actually significantly harder than I was expecting but this is the best I can come up with. It lists about ~130 applications in about 22ms on my computer.

    Function Get-InstalledSoftware {
    Param (
        [Array]$Properties = @('DisplayName','DisplayVersion')
    )
    $Keys = "Software\Microsoft\Windows\CurrentVersion\Uninstall","SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
    $Result = New-Object -TypeName 'System.Collections.ArrayList'
    $BaseKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine,$ENV:ComputerName)
    ForEach($Key in $Keys) {
        $RegKey = $BaseKey.OpenSubkey($key)
        If($RegKey -ne $null) {
            ForEach($subName in $RegKey.getsubkeynames()) {
                foreach($sub in $RegKey.opensubkey($subName)) {
                    [string]$Name = $sub.getvalue("displayname")
                    If ($Name.trim().Length -gt 0) {
                        $HashProperty = @{}
                        ForEach ($CurrentProperty in $Properties) {
                            $HashProperty.$CurrentProperty = $sub.GetValue($CurrentProperty)
                        }#End-ForEach
                        $Result.add([psCustomObject]$HashProperty)
                    }#End-IF
                }#End-ForEach
            }#End-Foreach
        }#End-IF
    }#End-ForEach
    $Result
}

The new script is not only significantly more flexible, but also significantly faster than previous solutions.

Measure-Command {
    for($i = 0; $i -lt 100; $i++) {
        Get-InstalledSoftware99 -Properties DisplayName,UninstallString,DisplayVersion
    }
}

Measure-Command {
    for($i = 0; $i -lt 100; $i++) {
        Get-SoftwareList
    }
}

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 925
Ticks             : 9259570
TotalDays         : 1.07170949074074E-05
TotalHours        : 0.000257210277777778
TotalMinutes      : 0.0154326166666667
TotalSeconds      : 0.925957
TotalMilliseconds : 925.957

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 14
Milliseconds      : 695
Ticks             : 146959970
TotalDays         : 0.00017009255787037
TotalHours        : 0.00408222138888889
TotalMinutes      : 0.244933283333333
TotalSeconds      : 14.695997
TotalMilliseconds : 14695.997


'''create a simple setup folder for a new project

The recommendation is to always use """ not ''' for docstrings

Follows the guide posted at:
http://guide.python-distribute.org/quickstart.html#lay-out-your-project

The structure built will match the following:

| ProjectName/
|---> LICENSE.txt
    | README.txt
    | setup.py
    | projectname/
    | ---> __init__.py

For the sake of best practices, __init__.py is left empty.

'''

#! usr/bin/env python

import sys, os, errno

class NewProject(object):
    '''interface for building a directory with a new project in it'''

    def __init__(self, projectname, directory):

The python style guide recommends underscores to separate words
            self.project = projectname

I'd call it self.name not self.project. The name project doesn't convey much useful information.

        self.base = check_path(directory)
        #project defaults: I don't want them here as class attributes!
        self.SETUP = {

'README.txt' :
'''This is an unmodified README text file.
It contains a list of changes to the program.
It also contains help for dealing with the application.
''',

'LISCENSE.txt' :
'''Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
'''
}

I wouldn't mix large docstrings into my python files. I think that makes it rather hard to read.

    def newproject(self):
        '''creates a file structure for a new project at `directory`
        '''
        self.name = self.project.replace(' ', '')

I dislike adding object attirbutes not present in the constructor. It makes it harder to know what attributes an object will have

        self.path = os.sep.join([self.base, self.name])

Use os.path.join for joining paths together. It'll handle a few corner cases that os.sep.join won't.

        sub = self.name.lower()
        subpath = os.sep.join([self.path, sub])

        check_build_path(subpath)
        for filename, content in self.SETUP.items():
            self.buildfile(filename, content, directory=self.path)
        #setup takes arguments, it has its own method
        setup = self.buildsetup()
        self.buildfile('setup.py', setup)
        self.buildfile('__init__.py', directory=subpath)

I'd probably pass a blank content for __init__.py rather then  having it be the default. I figure its rate that you want to have a file like that, so making it default doesn't make sense.

    def buildfile(self, name, content="", directory = ""):
        '''opens and creates a new file at `directory` with `contents`'''
        #assumes bad directories have been purified
        if directory == "":
            loc = os.sep.join([self.path, name])
            w = open(loc, 'w')
        else:
            directory = os.sep.join([directory, name])

That's not a directory if you've saved the file name over it.
                w = open(directory, 'w')

If you use os.path.join, you won't need to handle these two cases separately.
            w.write(content)
            w.close()

I recommend you use with statement to make sure the file closes correctly

    def buildsetup(self):
        return '''from distutils.core import setup

setup(
    name='{0}',
    version='0.1dev',
    packages=['{1}',],
    license=open('LISCENSE.txt).read(),
    long_description=open('README.txt').read(),
)
'''.format(self.project, self.name.lower())

Again, I don't like putting huge docstrings in the middle of the code. I recommend having a template folder that you copy over to the target. Just do search/replace on filenames and contents for a few keywords like NAME or MODULE.

def check_path(loc):
    '''recursively check if last character in `loc` is like os.sep character.
    If so, remove.'''
    if loc[-1] == os.sep:
        return check_path(loc[:-1])
    return loc

This is the sorta thing that os.path.join will do for you. I'd also avoid recursion,  because its pretty easy to make this a while loop. Also what happens when loc is "/"

def check_build_path(loc):
    d = os.path.normpath(loc)

I discourage single letter variable names whenever I can

    if not os.path.exists(d):
        os.makedirs(d)
    else:
        try:
            os.rmdir(d)
        except OSError as ex:
            if ex.errno == errno.ENOTEMPTY:
                print "Directory specified must be new or empty"
                sys.exit(1)

You should reraise the exception if it was something else.

        #if delete was successful, build the directory
        check_build_path(loc)

This function would be simpler if done like this:

try:
    os.rmdir(d)
except OSError as error:
    if error == ERROR_CODE_FOR_NOT_EXIT:
        pass # OK
    else:
        print "Failed to delete because: ", error
        sys.exit(1)
os.makedirs(d)

I think that conveys the logic better

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print "Usage: string 'Project Name', string '/abs/path'"
        sys.exit(1)
    project = NewProject(sys.argv[1], sys.argv[2])
    project.newproject()


Try using this instead.

// `isPrime` adopted from http://www.javascripter.net/faq/numberisprime.htm
var isPrime = function (n) {
    if (isNaN(n) || !isFinite(n) || n % 1 || n < 2) {
        return false;
    }
    if (n % 2 === 0){
        return (n === 2);
    }
    if (n % 3 === 0){
        return (n === 3);
    }
    for (var i = 5, m = Math.sqrt(n); i <= m; i += 6) {
        if ((n % i === 0) || (n % (i + 2) === 0)){
            return false;
        }
    }
    return true;
}
var getPrimesUntilN = function (n) {
    n = Math.abs(n);
    var primes = (1 < n) ? [2] : [];
    if (isNaN(n) || !isFinite(n)) {
        return primes;
    }
    for (var i = 3; i <= n; i+=2) {
        if (isPrime(i)) {
            primes.push(i);
        }
    }
    return primes;
};

Input:

getPrimesUntilN(50);

Output:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]


Compare a given version number in the form major.minor.build.patch and see if one is less than the other

Yes, there is a cleaner way:

if (a.major != b.major) {
    *result = a.major < b.major;
} else if (a.minor != b.minor) {
    *result = a.minor < b.minor;
} else if (a.patch != b.patch) {
    *result = a.patch < b.patch;
} else {
    *result = a.build < b.build;
}
return OKAY;

I reordered patch to come before build since that's how it is usually done. If your version scheme is different from this, good luck.

Instead of unsigned char I would choose uint32_t so that your code can handle versions like 1.0.20190415. If you need to handle version numbers with millisecond timestamps, each version component would need to be uint64_t.


CSES standard solution for range query problem giving TLE

You are already using the optimal solution algorithm for the problem. A few things, which might speed-up the computations (.split should not be the limiting factor in most likeliness)
Variable naming
Use names which match the problem description, so that it becomes easier to follow your code. So, instead of x, y it'd be a, b. Also, in python, it is a good practice to name your variables in lower_snake_case.
sum is an builtin function. Do not override this.
Computing len
You do not need to iterate over indices as the index is not really being used anyway. Lists can be iterated over their values itself.
Lazy iterators
Instead of generating list inline, you can use generators so that the values are yielded when iterating, and not consuming memory.
.split
Not passing a parameter to .split is same as providing whitespace as parameter.

Rewrite:
def solve():
    n, q = map(int, input().split())
    arr = map(int, input().split())

    cumulative_summation = [0]
    running_sum = 0
    # Not calculating `len` of `arr`, also, you don't need to calculate it.
    # the length is known to be `n`.
    for value in arr:
        running_sum += value
        cumulative_summation.append(running_sum)

    for i in range(q):
        a, b = map(int, input().split())
        print(cumulative_summation[b] - cumulative_summation[a - 1])


Projecteuler.net Problem 2 using collection pipeline Pattern

updated my code to use a deferent approach and apply collection pipeline
update my code

I use collection pipeline refactoring for more information about the
topics look
https://martinfowler.com/articles/refactoring-pipelines.html
I use stride function instead of filter to generate even Integer array

Sidenote: I don't know if I will save a couple of computing cycles—all I want to make my code more Swifty.
func isPerfectSquare(_ x:Int ) -> Bool {
    let i = Int(sqrt(Double(x)))
    return  (i * i == x)
}

var result  =  (Array(stride(from: 0`enter code here`, to: 100, by: 2)).filter{(isPerfectSquare(5 * $0 * $0  + 4) || isPerfectSquare(5 * $0 * $0  - 4))}).reduce(into: 0){$0 += $1}
print(result)


Checking that all occurrences of 'g' have another 'g' as a neighbor

Other answers have good input on a number of factors I agree with, especially about the early-return logic, the bugs that were pointed out, and the bracing strategies.

My suggestion though, is to use a different (the right?) tool for the job.

Regular expressions are a tool that are designed for text processing, and a well-crafted expression is typically faster and more concise than the hand-coded alternative. Regular expressions are not always the solution, but in this case, the result would be simpler to read (for someone familiar with them).

In this case, the logic requires checking that all 'g' chars are happy for the check to return true. Alternatively, to make sure there are no unhappy 'g' chars.

The expression to check for unhappy 'g' chars will be:

 private static final Pattern UNHAPPYG = Pattern.compile("(?<!g)g(?!g)");

That expression says "Match any 'g' that has no 'g' before it, and no 'g' after it.

Then, you can use it as:

private static final boolean gHappy(String str) {
    return !UNHAPPYG.matcher(str).find();
}

I have put together an Ideone example here.


Separation of Logic and Rendering

The Square object is essentially a button that also contains some information for display, such as the number of surrounding bombs.

The problem you are having is that this GUI element is communicating directly with the game board of your minesweeper game model.  When Square gets clicked, it tells the board to check the amount of bombs.

I'm not very familiar with Swing, but typically I would expect there to be a Scene or Window at the top level of the hierarchy.  Once clicked, the button would tell the controller to tell the game model to perform the necessary action, and then the controller would update the view based on changes to the model.

In this approach you could possibly have a Game object, Board object, and Square object in the game model. On a button click, the coordinates of the Square button object in the view would be passed into the Game, and the appropriate changes would be made to the Board and to the game state.  For example, the coordinates have a bomb, and so the state of the Game is set to GameState.LOSS.

In this approach, you could make the Board object available to the view.
After each move, the view could update based on the new state of the board, marking the squares that have flags, have been uncovered, etc.

You could also do something such as compute the positions of the nearby Square objects at the start of the game, and then you could check for bombs like this:

int bombCount = 0;
for (Position position : square.neighbors) {
    Square neighbor = board.get(position);
    if (neighbor.hasBomb) {
        bombCount++;
    }
}

Or alternatively store a reference to the actual Square objects, if you want.

The advantage of all of this is that if you some day want to use a different graphical representation other than Swing, you could easily take the code for the game model and use a different controller and view. You would still use the model in the same way, passing in the coordinates of the location on the board that is clicked.


I think in this case the answer is to count rather than sort and search. I would create a struct that simply keeps count of how many cards of each type. Something like this:

struct cardCounts {
    unsigned long numOneCircles;
    unsigned long numTwoCircles;
    unsigned long numThreeCircles;
    unsigned long numOneSquares;
    unsigned long numTwoSquares;
    unsigned long numThreeSquares;
    unsigned long numOneTriangles;
    unsigned long numTwoTriangles;
    unsigned long numThreeTriangles;
};

You can initialize them all to 0, then increment each one as you read a card of that type from the input.

Once you've read all the cards, you can make combinations from them. For example, you can figure out how many sets containing 3 cards of 1 circle are possible by simply dividing numOneCircles by 3. Then the same for each other member of the struct.

Next, you can find combinations where 1 property is the same and the other are all different. So either the shape is the same but the counts are different, or the counts are the same and the shapes are different. You can take the minimum of numOneCircles, numTwoCircles, and numThreeCircles, and that's how many sets you can make with 1 card from each stack. Do the same for squares then triangles. Then switch it so the number stays the same but the shapes are different - so across numOneCircles, numOneSquares, and numOneTriangles.

Finally, find all combinations where both the shape and the number are different. This one is a little trickier, but not too bad. Check for one circle, two squares, three triangles. (Again, taking the min of those 3 as the result.) Then one circle, two triangles, three squares. There are 9 combinations you have to cover (I think?).

This should be O(n) in time and O(1) in space, as you'll only read through the data once when counting up the amounts, and you'll only ever use the 9 elements to store the sums.


Expression evaluators, with possible short circuit evaluation

If your code will always behave as the parts shown, you can refactor it to early-out returns. I show your Evaluate<T1, T2, T3, TResult>(...) as an example:

public static Response<TResult> Evaluate<T1, T2, T3, TResult>(Func<Response<T1>> func1, Func<T1, Response<T2>> func2, Func<T2, Response<T3>> func3, Func<T3, Response<TResult>> funcResult)
{
    var response = new Response<TResult>();

    if (!func1()) return response;
    if (!func2(true)) return response;
    if (!func3(true)) return response;
    return response.WithValue(funcResult(result3));
}

So you get rid of the nesting if statements. And you don't need the local flag variables since you know that the value is true.


Your solution is fine, subject to the caveat that the use of recursion imposes a limit on the length of your lists, due to the possibility of stack overflow.

Your comments betray a sense of insecurity about how it works, though.  Just consider what happens locally, and trust that recursion will take care of the rest.

I also suggest un-nesting the else block.

/**
 * Recursively merge two sorted lists by manipulating node pointers.
 * Returns the head of the merged list.
 */
Node* MergeLists(Node *headA, Node* headB)
{
    if (headA == NULL) {
        return headB;
    } else if (headB == NULL) {
        return headA;
    } else if (headA->data <= headB->data) {
        headA->next = MergeLists(headA->next, headB);
        return headA;
    } else {
        headB->next = MergeLists(headA, headB->next);
        return headB;
    }
}


Your methods take int parameters but it seems like you only have really thought about positive numbers. This yields some inconsistencies. For example:

(-28).FloorTo(6) == -28
(-28).FloorTo(-6) == -28
(28).FloorTo(-6) == 24

For CeilingTo the results are:

(-28).CeilingTo(6) == -28
(-28).CeilingTo(-6) == -28
(28).CeilingTo(-6) == 18

If you don't want to think about or deal with negative numbers you should either change the signature to accept only uint parameters (which would require the caller to think about what to do in case he's got an int) or you check and throw an ArgumentOutOfRange exception
Just considering positive numbers FloorTo could be changed to

public static int FloorTo(this int value, int interval)
{
   var remainder = value % interval;
   return value - remainder;
}

Less logic to read and verify in your head.


Is there better way to shorten this Lambda expression's result selector?

Naming
Your entities / POCO classes have badly named members (assuming the entity names themselves aren't really named the way you've posted them), that break the C# naming conventions for public members - they should be PascalCase, ...and what's with the Hungarian notation? Also disemvoweling is never a great idea - call a table Table instead of Tbl, and we'll know you didn't mean Team-Based-Learning... whatever.
public class Table2
{
       [Key]
       public int Id { get; set; }
       public long AccountNumber{ get; set; }
}

Entities are NOT database tables; they MAP to database tables, and they're classes - so they should follow the naming conventions for C# classes. If they're mapped to tables/columns on SQL Server with different names, you should use the appropriate [Column("columnName")] attributes (or fluent API configurations) to specify the mapping.
Convention over Configuration
Entity Framework is able to infer a lot of things from the way you name things. Having a property called Id in an entity type, is automagically inferred to be that type's [Key] - hence, the explicit attribute is redundant / noise, and should be removed.
Tbl1 is breaking this convention. The [Key] field bintAccountNo should be called Id, and the table should be called Account - so when other related entities have a property named AccountId, Entity Framework knows that's a FK property.
Navigation Properties
One of the greatest things about EF is its ability to simplify the querying of complex relationships between entities, using navigation properties.
public class Account
{
    public long Id{ get; set; }
}

public class Table2
{
    public int Id { get; set; }
    public long AccountId { get; set; }

    public virtual Account Account { get; set; }
}

You mention in a comment that you find the generated T-SQL inefficient when you're using navigation properties; how exactly is it "inefficient"? It's verbose, yes, but that doesn't make it inefficient. Have you performance-profiled it? What's the bottleneck? Could you be missing indexes?

Your Query
I like that you're using the method syntax, but it's not clear what's being queries exactly, because the code you posted looks like it's querying the type itself:
var b = (Tbl1.GroupJoin(...));

One would expect something like this:
using (var context = new MyDbContext())
{
    var result = context.Tbl1s.GroupJoin(...));
}

GroupJoin
This is where the query syntax gets handy, see what exactly is a group join? on Stack Overflow:
Join syntax:
from p in Parent
join c in Child on p.Id equals c.Id
select new { p.Value, c.ChildValue }

GroupJoin syntax:
from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }

And that calls GroupJoin() for you under the hood, and it's easier to mentally picture what your data looks like, I find.
I'm not quite clear on GroupJoin followed by SelectMany - why not just do a regular Join then?


A few observations about your code.

incomplete - As you've noted, it doesn't handle Int overflow. It also doesn't handle the optional leading + character.

digit characters - The variables charMap and keyMap are unnecessary. The .isDigit and .asDigit methods in the standard library provide the same functionality.

Boolean logic - Consider this Boolean test: !charMap.contains(c) || c == '-' || c == ' ' It translates to "if c is not a digit OR if c is a dash OR if c is a space." But if c is a dash or space then it is already not a digit. The dash and space tests serve no purpose because no dash or space character would get beyond the digit test.

unneeded vars - There's no reason to make cleanStr or summand a var. Their initial values are never changed. In fact, you could just drop summand altogether and increment num directly.

num += (c match { ...//rest of code block

excess braces - In a match{...} every case statement ends the previous code block and starts a new one. Therefore wrapping the code block in { braces } is redundant and just adds visual clutter. In other words, this...

case x =>
  //code
  //here

...is cleaner than this...

case x => {
  //code
  //here
}

style - The use of so much mutation (i.e. vars instead of vals) makes it pretty clear that you are using the Scala language to write C code. This will change as you become more familiar with the Scala standard library, the tenants of Functional Programming, and the study of other Scala code.

Here, for example, is a Scala solution for the atoi challenge.

val numRE = "\\s*([+-]?)0*(\\d+).*".r

def myAtoi(str :String) :Int = str match {
  case numRE(signStr, numStr) =>
    val sign    = if (Option(signStr).contains("-")) -1 else 1
    val bailOut = if (sign < 0) Int.MinValue else Int.MaxValue
    if (numStr.length > 10) bailOut                      //too many digits
    else if (numStr.length < 10 || numStr < "2147483648")
      sign * numStr.foldLeft(0)(_*10 + _.asDigit)        //calculate return Int
    else bailOut
  case _ => 0  //input doesn't match the pattern
}