0

I'm trying to convert c++ funtion to c#, but I'm failing for the second straight hour. Need help:/ The function is taken from this question

bool haswon(unsigned __int64 newboard)
{
    unsigned __int64 y = newboard & (newboard >> 6);
    if (y & (y >> 2 * 6)) // check \ diagonal
        return true;
    y = newboard & (newboard >> 7);
    if (y & (y >> 2 * 7)) // check horizontal -
        return true;
    y = newboard & (newboard >> 8);
    if (y & (y >> 2 * 8)) // check / diagonal
        return true;
    y = newboard & (newboard >> 1);
    if (y & (y >> 2))     // check vertical |
        return true;
    return false;
}

Here's my c# one:

    bool HasWon(ulong newboard)
    {
        ulong y = newboard & (newboard >> 6);
        if ((y & (y >> 2 * 6)) > 0) // check \ diagonal
            return true;
        y = newboard & (newboard >> 7);
        if ((y & (y >> 2 * 7)) > 0) // check horizontal -
            return true;
        y = newboard & (newboard >> 8);
        if ((y & (y >> 2 * 7)) > 0) // check / diagonal
            return true;
        y = newboard & (newboard >> 1);
        if ((y & (y >> 2 * 7)) > 0)    // check vertical |
            return true;
        return false;
    }

But It doesn't work! Looks like a trivial thing, but I'm totally lost. Thanks for help

Community
  • 1
  • 1
Louisa Bickley
  • 297
  • 5
  • 17
  • 2
    Compare your code with the C code, you should see your copy'n'paste error(s). (Hint: The number of the deadly sins...) –  Apr 29 '17 at 01:47
  • How is it not working? (what was your input, what was your expected output, which line is not returning what you expect)? – Rufus L Apr 29 '17 at 01:53
  • @RufusL this is an algorithm to check if "Connect 4" game's board is connected (if there are 4 bits in the row). [Here](http://stackoverflow.com/questions/4261332/optimization-chance-for-following-bit-operations) it is explained in details. Basically if you pass "15" you should get true. Because last 4 bits of "15" are "1111". But I can't get it :/ I don't see any "deadly sins" :( – Louisa Bickley Apr 29 '17 at 01:56
  • Yep, I understand. When you step through the code, are all the lines not working? or just some of them? (in your last two lines, you are not shifting `y` by twice the amount that you're shifting `newboard `) – Rufus L Apr 29 '17 at 01:57

1 Answers1

1

It looks like a simple copy/paste error. Your last two lines were not shifting y by twice the amount of newboard:

private static bool isWon(ulong board)
{
    // Check / diagonal
    ulong y = board & (board >> 8);
    if ((y & (y >> 2 * 8)) > 0) return true;

    // Check - horizontal
    y = board & (board >> 7);
    if ((y & (y >> 2 * 7)) > 0) return true;

    // Check \ diagonal
    y = board & (board >> 6);
    if ((y & (y >> 2 * 6)) > 0) return true;

    // Check | vertical
    y = board & (board >> 1);
    if ((y & (y >> 2)) > 0) return true;

    return false;
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43