Code Kata 2

CodeKata One: Supermarket Pricing

This kata arose from some discussionswe’ve been having at the DFWPractionersmeetings. The problem domain issomething seemingly simple: pricing goods at supermarkets.

Some things in supermarkets have simple prices: this can ofbeans costs $0.65. Other things have more complex prices. For example:

·threefor a dollar (so what’s the price if I buy 4, or 5?)

·$1.99/pound(so what does 4 ounces cost?)

·buytwo, get one free (so does the third item have a price?)

This kata involves no coding. The exercise is to experiment withvarious models for representing money and prices that are flexible enough todeal with these (and other) pricing schemes, and at the same time are generallyusable (at the checkout, for stock management, order entry, and so on). Spendtime considering issues such as:

·doesfractional money exist?

·when(if ever) does rounding take place?

·howdo you keep an audit trail of pricing decisions (and do you need to)?

·arecosts and prices the same class of thing?

·ifa shelf of 100 cans is priced using “buy two, get one free”, how do you valuethe stock?

This is an ideal shower-time kata, but be careful. Some of theproblems are more subtle than they first appear. I suggest that it might take acouple of weeks worth of showers to exhaust the main alternatives.

Goal

The goal of this kata is to practice a looser style ofexperimental modelling. Look for as many different ways of handling the issuesas possible. Consider the various tradeoffs of each. What techniques use bestfor exploring these models? For recording them? How can you validate a model isreasonable?

What’s a Code Kata?

As a group, software developers don’t practice enough. Most ofour learning takes place on the job, which means that most of our mistakes getmade there as well. Other creative professions practice: artists carry asketchpad, musicians play technical pieces, poets constantly rewrite works. Inkarate, where the aim is to learn to spar or fight, most of a student’s time isspent learning and refining basic moves. The more formal of these exercises arecalled kata.

To help developers get the same benefits from practicing, we’reputting together a series of code kata: simple, artificial exercises which letus experiment and learn without the pressure of a production environment. Oursuggestions for doing the kata are:

·finda place and time where you won’t be interrupted

·focuson the essential elements of the kata

·rememberto look for feedback for every major decision

·ifit helps, keep a journal of your progress

·havediscussion groups with other developers, but try to have completed the katafirst

There are no right or wrong answers in these kata: the benefitcomes from the process, not from the result.

KataTwo: Karate Chop

A binary chop (sometimes called the more prosaic binary search)finds the position of value in a sorted array of values. It achieves someefficiency by halving the number of items under consideration each time itprobes the values: in the first pass it determines whether the required valueis in the top or the bottom half of the list of values. In the second pass inconsiders only this half, again dividing it in to two. It stops when it findsthe value it is looking for, or when it runs out of array to search. Binarysearches are a favorite of CS lecturers.

This Kata is straightforward. Implement a binary search routine(using the specification below) in the language and technique of your choice.Tomorrow, implement it again, using a totally different technique. Do the samethe next day, until you have five totally unique implementations of a binarychop. (For example, one solution might be the traditional iterative approach, onemight be recursive, one might use a functional style passing array slicesaround, and so on).

Goals

This Kata has three separate goals:

1.As you’re coding each algorithm, keep a note of thekinds of error you encounter. A binary search is a ripe breeding ground for“off by one” and fencepost errors. As you progress through the week, see if thefrequency of these errors decreases (that is, do you learn from experience inone technique when it comes to coding with a different technique?).

2.What can you say about the relative merits of thevarious techniques you’ve chosen? Which is the most likely to make it in toproduction code? Which was the most fun to write? Which was the hardest to getworking? And for all these questions, ask yourself “why?”.

3.It’s fairly hard to come up with five uniqueapproaches to a binary chop. How did you go about coming up with approachesfour and five? What techniques did you use to fire those “off the wall”neurons?

Specification

Write a binary chop method that takes an integer search targetand a sorted array of integers. It should return the integer index of thetarget in the array, or -1 if the target is not in the array. The signaturewill logically be:

   chop(int, array_of_int)  -> int

You can assume that the array has less than 100,000 elements.For the purposes of this Kata, time and memory performance are not issues(assuming the chop terminates before you get bored and kill it, and that youhave enough RAM to run it).

Test Data

Here is the Test::Unit code I used when developing my methods.Feel free to add to it. The tests assume that array indices start at zero.You’ll probably have to do a couple of global search-and-replaces to make thiscompile in your language of choice (unless your enlightened choice happens tobe Ruby).

  def test_chop
    assert_equal(-1, chop(3, []))
    assert_equal(-1, chop(3, [1]))
    assert_equal(0,  chop(1, [1]))
    #
    assert_equal(0,  chop(1, [1, 3, 5]))
    assert_equal(1,  chop(3, [1, 3, 5]))
    assert_equal(2,  chop(5, [1, 3, 5]))
    assert_equal(-1, chop(0, [1, 3, 5]))
    assert_equal(-1, chop(2, [1, 3, 5]))
    assert_equal(-1, chop(4, [1, 3, 5]))
    assert_equal(-1, chop(6, [1, 3, 5]))
    #
    assert_equal(0,  chop(1, [1, 3, 5, 7]))
    assert_equal(1,  chop(3, [1, 3, 5, 7]))
    assert_equal(2,  chop(5, [1, 3, 5, 7]))
    assert_equal(3,  chop(7, [1, 3, 5, 7]))
    assert_equal(-1, chop(0, [1, 3, 5, 7]))
    assert_equal(-1, chop(2, [1, 3, 5, 7]))
    assert_equal(-1, chop(4, [1, 3, 5, 7]))
    assert_equal(-1, chop(6, [1, 3, 5, 7]))
    assert_equal(-1, chop(8, [1, 3, 5, 7]))
  end

KataThree: How Big, How Fast?

Rough estimation is a useful talent to possess. As you’re codingaway, you may suddenly need to work out approximately how big a data structurewill be, or how fast some loop will run. The faster you can do this, the lessthe coding flow will be disturbed.

So this is a simple kata: a series of questions, each asking fora rough answer. Try to work each out in your head. I’ll post my answers (andhow I got them) in a week or so.

How Big?

·roughlyhow many binary digits (bit) are required for the unsigned representation of:

o1,000

o1,000,000

o1,000,000,000

o1,000,000,000,000

o8,000,000,000,000

·Mytown has approximately 20,000 residences. How much space is required to storethe names, addresses, and a phone number for all of these (if we store them ascharacters)?

·I’mstoring 1,000,000 integers in a binary tree. Roughly how many nodes and levelscan I expect the tree to have? Roughly how much space will it occupy on a32-bit architecture?

How Fast?

·Mycopy of Meyer’s Object Oriented Software Construction has about 1,200 bodypages. Assuming no flow control or protocol overhead, about how long would ittake to send it over an async 56k baud modem line?

·Mybinary search algorithm takes about 4.5mS to search a 10,000 entry array, andabout 6mS to search 100,000 elements. How long would I expect it to take tosearch 10,000,000 elements (assuming I have sufficient memory to preventpaging).

·Unixpasswords are stored using a one-way hash function: the original string isconverted to the ‘encrypted’ password string, which cannot be converted back tothe original string. One way to attack the password file is to generate allpossible cleartext passwords, applying the password hash to each in turn andchecking to see if the result matches the password you’re trying to crack. Ifthe hashes match, then the string you used to generate the hash is the originalpassword (or at least, it’s as good as the original password as far as loggingin is concerned). In our particular system, passwords can be up to 16characters long, and there are 96 possible characters at each position. If ittakes 1mS to generate the password hash, is this a viable approach to attackinga password?

点赞