Showing posts with label Game. Show all posts
Showing posts with label Game. Show all posts

Friday, March 6, 2020

R(eg?)*x Challenge

Regular Expressions

Regular expressions are a very powerful tool. However, they have their downsides, mainly in maintainability. Regexes are often really hard to read or modify, as they are often just a long string of characters with special meaning.

For that reason, we should use them with care in our applications. But that is not the only place where they have their use. Modern editors come with support for searching and replacing using regexes. This is a perfect use case, because, as a one-time action we need not maintain them. We can also see the exact context that it will be applied to, so there are no bug issues.

The Challenge

Keeping our regex toolbox sharp is important, and I recently got a fun regex challenge to practice. In Visual Studio Code paste the following and create a regular expression that matches each of the good lines (it should show 6 matches), and none of the bad lines:

GOOD:
"xxx";yyyy;"zzz"
"xxx;xxx";yyyy
xxxx;yyyy;zzzz
"xxx";"yyyy";"zzzz"
xxxx;;yyyy;zzz
xxx;"yy""yy";"zzzzz"

BAD:
xxx";"yyyy
xx"xx";yyyy
xxxx;"yy";
xx";yyyyy";zzzz"
xxxxx;";yyyyy
"xxxx";";"yyyy"

Cheat Sheet

To save you some time here is a cheat sheet of VSCode regex:

Regex Meaning
.
Any character
[a-zA-Z_]
A character in the range a-z or A-Z or _
[^a-zA-Z_]
A character _not_ in the range a-z nor A-Z nor _
X*
Zero or more X (longest match)
X*?
Zero or more X (shortest match)
X+
One or more X (longest match)
X+?
One or more X (shortest match)
X|Y
Either X or Y
^
Start of line
\r?$
End of line

Wednesday, October 23, 2019

A New Take On FizzBuzz

I have been hosting a lot of technical interview by now, to determine whether applicants meet our programming and data understanding requirements. A lot of thoughts have gone into the structure and design of the questions to ensure that they tested all relevant aspects and where not 'gameable'.

Before I did my first I went online to find out what other people had done, and immediately came across "FizzBuzz". Then I realized that if I used something I had found online, my applicants might very well have studied for a technical interview and came across the same thing. Analyzing FizzBuzz I determined that it requires an applicant be familiar with at least loops and conditionals.

As it turns out we can use the same exercise to reach higher levels of programming skill. Here are a few variations I came up with to determine an applicants skill level. They are intended to be solved in C# or Java, but any Object Oriented language should present the same solution.

Level 0: Standard

Write a program that takes as input a number, N, and outputs all numbers from 0 to N. But if a number is divisible by 3 it instead outputs "Fizz", if it is divisible by 5 it instead outputs "Buzz". It it is divisible by both it outputs "FizzBuzz".

Level 1: Without iteration

Write the same program but without using while, for, streams, nor foreach.

Level 2: Without conditional

Write the same program but without using if, the ternary operator, nor switch.

Level 3: Without either (almost)

Write the same program but using only one if, no else, ternary operator, switch, while, for, streams, nor foreach.

Level 4: Without either

Write the same program but without using if, ternary operator, switch, while, for, streams, nor foreach.

Conclusion

Although the fact that level 4 is possible is a fun challenge, and shows creativity in an applicant. However, level 3 is much prettier, so I would seldom be disappointed if they stop here, unless creativity is very highly valued in the position they're applying for.

Thursday, January 31, 2019

Debugging Challenge #6

Previously on Dr. Lambda's blog:

I have deviced a series of debugging challenges, some are easy, some are really hard, all come from real live systems. Good luck!

The Challenge

  • 1 point if you can spot where the error is.
  • +1 point if you can explain why.
  • +2 points if you can explain how to fix it.
@Echo off

set direct=1
echo %cmdcmdline% | find /i "%~n0" >nul
if not %errorlevel% == 1 set direct=0

REM powershell.exe -file .\AdHocScripts\FlushBlobCache.ps1
Set e=%errorlevel%
if not %e% == 0 goto error

powershell.exe -Version 2 -file .\AdHocScripts\FarmIISReset.ps1
Set e=%errorlevel%
if not %e% == 0 goto error

goto success

:error
    Echo ERROR, errorlevel %e%
    if %direct% == 0 pause else exit %e%
    goto end
:success
    Echo done
    if %direct% == 0 pause
:end

Thursday, January 24, 2019

Debugging Challenge #5

Previously on Dr. Lambda's blog:

I have deviced a series of debugging challenges, some are easy, some are really hard, all come from real live systems. Good luck!

The Challenge

  • 1 point if you can spot where the error is.
  • +1 point if you can explain why.
  • +2 points if you can explain how to fix it.
// @param date  string in the format YYYY-MM-DD
function isBeforeToday(date: string) {
  return new Date(date).getTime() 
      < Math.floor(Date.now() / 86400000) * 86400000;
}

Saturday, January 12, 2019

Debugging Challenge #4

Previously on Dr. Lambda's blog:

I have deviced a series of debugging challenges, some are easy, some are really hard, all come from real live systems. Good luck!

The Challenge

  • 1 point if you can spot where the error is.
  • +1 point if you can explain why.
  • +2 points if you can explain how to fix it.
let csv_split seperator str =
  let csvSplit = new Regex(
    "((?:\")[^\"]*(?:\"(?=,|$)+)|(?<=,|^)[^,\"]*(?=,|$))", 
    RegexOptions.Compiled) in
  csvSplit.Matches(str)
    .OfType<Match>()
    .Select(fun m -> m.Value.TrimStart(','))
    .ToArray()

Saturday, January 5, 2019

Debugging Challenge #3

Previously on Dr. Lambda's blog:

I have deviced a series of debugging challenges, some are easy, some are really hard, all come from real live systems. Good luck!

The Challenge

  • 1 point if you can spot where the error is.
  • +1 point if you can explain why.
  • +2 points if you can explain how to fix it.
int index = addressLine.Length;
for (int i = 0; i < 10; i++)
{
    int position = addressLine.IndexOf(i.ToString());
    if (position != -1 && position < index)
        index = position;
}
string street = addressLine.Substring(0, index).Trim();
string nr = addressLine
            .Substring(index, addressLine.Length - index)
            .Trim();

Saturday, December 29, 2018

Debugging Challenge #2

Previously on Dr. Lambda's blog:

I have deviced a series of debugging challenges, some are easy, some are really hard, all come from real live systems. Good luck!

The Challenge

  • 1 point if you can spot where the error is.
  • +1 point if you can explain why.
  • +2 points if you can explain how to fix it.
export class ActivityService {
    activities : Activity[] = [];
    constructor(){
        this.activities = [
            {
                title: "Arrange meeting",
                type: "task"
            }
        ];
        setTimeout(function () {
            this.activities.push({ 
                title: "Meeting",
                type: "appointment"
            });
        }, 3000); 
    };
}

Saturday, December 22, 2018

Debugging Challenge #1

Previously on Dr. Lambda's blog:

I have deviced a series of debugging challenges, some are easy, some are really hard, all come from real live systems. Good luck!

The Challenge

  • 1 point if you can spot where the error is.
  • +1 point if you can explain why.
  • +2 points if you can explain how to fix it.
private static long IncrementRowVersion(long rowversion)
{
    return rowversion++;
}

Saturday, December 15, 2018

Bug Hunt: Debugging Challenge #0

So, I really like puzzles, and challenges. Just like the Javascript Drinking Game. I also used to post programming challenges online, most were extremely challenging, and very time consuming. Therefore I have long been thinking how to make exercises that are both challenging, relevant, and light.

My idea was some sort of debugging challenge. As a developer I spend most of my time doing this anyway, so I figured my colleagues must too, and it would be great practice. Because we are living in a culture were attention span is getting shorter and shorter I knew that the entire thing has to fit on a page, the description should be bulleted, and the code cannot be more than a handful of lines. If any of these fail most people wont give it a second glance.

I decided on a simple point system, starting with a pretty trivial task – to hook the reader. Just identify what looks wrong. Then draw them in by asking why they said that, and finally the real challenge: How to fix it. The Bug Hunt has a start date and an end date, and everybody collects points all season. At the end the victor can have his pick of which project to work on.

After spending a year keeping an eye out, I finally feel like I have collected enough material for the first "season". All the code comes from actual live systems that I have come in contact with as a consultant. They are obviously annonymized, but the structure of the code, and more importantly the bugs were real. As such, the challenges have very different flavor, some are included because they are very difficult, others are deceptively easy. They span different programming languages and technologies, however, in most cases this context must be inferred.

I highly recommend that you share challenges that you like (I print and hang them on the walls in the office), you might even use them to set up a Bug Hunt at your own office. If so, I would be happy to provide the answers.

Let the 0th Bug Hunt begin, and a good hunt to all participants!

The Challenge

  • 1 point if you can spot where the error is.
  • +1 point if you can explain why.
  • +2 points if you can explain how to fix it.
SELECT a.* FROM Notification a
LEFT OUTER JOIN (
    SELECT CONVERT(uniqueidentifier, 
                MIN(CONVERT(char(36), b.[ID]))) AS ID
            , CAST(b.[Message] AS varchar(255)) AS Message_varchar
            , b.[To]
    FROM Notification b
    GROUP BY Message_varchar, b.[To]
) AS KeepRows ON
a.[ID] = KeepRows.[ID]
WHERE a.[Sent] = 0
AND KeepRows.[ID] IS NULL

Wednesday, October 4, 2017

Javascript Drinking Game and the Scientific Method

Spoiler warning: this post contains a minor spoiler of the Goal.

Introduction

I am a big fan of Java Puzzlers. I love quizzes and games like that. At university I would regularly host a Java quiz. In the quiz I would present a few lines of Java-code, and then the audience would have to choose from 5 options what the output would be.

Following Atwoods law: "Everything that can be written in Javascript, will eventually be". For this reason I think it is important to learn about some of the pitfalls and corner cases in Javascript. Therefore I have invented a game for learning some of them in Javascript.

The Scientific Method

The game consists of a lot of tiny code snippets, grouped into small sections. Many of these sections are structured to encourage the player to discover an underlying rule. The way you play this game is much like the Scientific Method:

  • Make an observation
  • Form/refine a hypothesis
  • Test the hypothesis
  • Repeat

Learning to work like this is very useful, in many different areas. It gives us the ability to uncover the underlying structure of something, without being able to observe it directly. This is also a point in the Goal.

This is exactly the same with these games, you have a language like Javascript, with some fixed rules (the interpreter), of course in this case we could lookup the source code of the interpreter, however we don't want to do that. Even if we did the behavior might stem from a complex interaction in the code. Thus we cannot observe the rules directly.

The way we play the game is:

  • You see a code snippet (make an observation)
  • Try to guess what it does (form a hypothesis)
  • Run the code (test the hypothesis)

If your prediction was inaccurate you refine your hypothesis to include the new data, and at this point move onto the next snippet. As mentioned the snippets are grouped into sections which encourages the formation of good hypotheses.

The Game

The rules are simple:

  • Open the developer console (f12).
  • Type in the expression
  • Try to predict what the result will be
  • Evaluate it
  • If you were wrong you drink (an appropriate amount)

So without further ado here are the snippets.

  • > "1" + 1
  • > "1" - 1
  • > "1" + - 1

  • > let x = 3
    > "5" + x - x
  • > "5" - x + x

  • > parseInt("")
  • > isNaN("")
  • > typeof NaN

  • > throw "ball"

  • > []+{}
  • > {}+[]
  • > []+{} === {}+[]

  • > null > 0
  • > null < 0
  • > null == 0
  • > null >= 0
  • > null <= 0
  • > NaN < NaN
  • > NaN >= NaN

  • > function dis() { return this }
    > five = dis.call(5)
  • > five.wtf = "potato"
  • > five.wtf
  • > five * 5
  • > five.wtf
  • > five++
  • > five.wtf
  • > five.wtf = "potato?"
  • > five.wtf
  • > five

  • > "1000" == "1e3"

  • > new Date("12/08/2016")
  • > new Date("2016-12-08")

  • > 0.1 + 0.2

  • > +[]
  • > {} + []
  • > {}{}{}{}{} + []
  • > [] + []
  • > {}{}{}{}[] + []
  • > [] + {}
  • > {}{}{}{}[] + {}
  • > +{}
  • > {} + {}
  • > {}{}{}{}{} + {}

  • > []?true:false
  • > {}?true:false
  • > ({}?true:false)

  • > [1001, 101, 1, 2].sort()
  • > [1, 2, 101, 1001].sort()
  • > [6, -2, 2, -7].sort()

  • > [1,2,3] == [1,2,3]

  • > let t = [0]
    > t == t
  • > t == !t

  • > Math.max() > Math.min()
  • > Math.max() < Math.min()

  • > true + true === 2
  • > true - true === 0
  • > true === 1

  • > [] == false
  • > [] ? true : false

  • > let numbers = [1, 2, 3]
    > numbers.map(n => { value: n })

  • > Ninja = function (name) {
      this.name = name;
    }
    > Ninja.prototype.jump = function () {
      console.log(this.name + " jumped");
    }
    > let john = new Ninja("John");
  • > john.jump()
  • > setTimeout(john.jump, 1000)
  • > setTimeout(() => john.jump(), 1000)
  • > let callback = john.jump
  • > setTimeout(() => callback(), 1000)
  • > callback()

  • > "" == false
  • > false == "0"
  • > "" == "0"

  • > [[][[]]+[]][+[]][++[+[]][+[]]]

  • > ('b' + 'a' + + 'a' + 'a').toLowerCase()

  • > console.log(b)
  • > console.log(b); var b;

Have fun with Javascript, and always drink responsibly.