Even Catfish Can Code

13.04.2010

My Top Ten Must Read Books for Programmers

Filed under: 1 — botique @ 18:24

1. The Art of Programming (D. Knuth)
2. Introduction to Algorithms (T. Cormen, C. Leiserson, R. Rivest, C. Stein)
3. Data Structures and Algorithms (Aho, Ullman, Hopcroft)
4. Data Structures and Problem Solving using C++ (Mark Weiss)
5. Discrete Math (James Anderson)
6. Structured Computer Organization (Andrew Tanenbaum)
7. Applied Cryptography (Bruce Schneier)
8. Operating Systems: Internals and Design Principles (William Stalling)
9. Computer Networks (Andrew Tanenbaum)
10. Applying UML and Patterns. An introduction to Object-Oriented analysis and Design and Iterative Development (Craig Larman)

12.01.2010

10 lessons for entry-level programmers

Filed under: 1 — botique @ 21:57
Tags: , ,

I’ve been programming for about 10 years and have learned some general rules that I’m ready to share with you, my students. I’m offering these “recipes” to those of you who are interested in learning more about success in programming.

1. Be in love with programming. Think about programming as a hobby, labor of love and entertainment. Try to program every day, enjoy developing your own game or making things that are useful to other people. Programming is very interesting pass time and pleasure of making others’ lives easier.
2. Always plan your time. Try to develop your own time management system that is suitable for your lifestyle. Do not spend eight hours in a front of the monitor trying to solve very small, boring and routine task. Use documentation and Internet resources for help. Be wise.
3. Practice thinking. Learn mathematics to be creative and very smart man (or woman)
4. Meet and communicate with other programmers, engineers and top industry experts in the software field. Collaborate with developers on projects and enjoy of working with them in a team. Learn with them, learn from their experience, teach them!
5. Learn to learn more. Be curious. Every single day try to read books, magazines and blogs about programming, computer technologies, and new techniques.
6. Simplify your algorithms. Do not forget, that programming is an art. As a programmer you MUST produce working, valid, reliable, stable, scalable, convenient, and interoperable software. Improve and optimize your code. Your code is your symphony.
7. Support juniors. Train entry-level developers on good programming guidelines and techniques. Nothing can compare with the delight of working in enthusiastic medium.
8. Always document your code. Whether it is an enterprise-level software or very simple laboratory work at your university, try to provide meaningful and complete documentation. It only takes a second to add an additional comment line for each 3 lines of code. This extra second will save your time and prevent you from enormous number of problems in the future.
9. Go in for sports. Take a part in programming olympiads, contests and competitions.
10. You are not the best at programming. Live with it, but try to become a supercoder or some kind of nerdy superhero. Do not forget that sense of humor is a requirement in this industry.

26.12.2009

Ruby: Кодирование во время выполнения

Ruby — динамический язык, который позволяет конструировать и интерпретировать фрагменты кода в ходе выполнения статически написанной программы. С помощью API отражения программа получает информацию о себе самой. Благодаря этому на этом языке сравнительно легко создавать отладчики, профилировщики и т.д.
Например, мне очень нравится такая возможность:

puts "Enter method's name you wish to create"
method_name = gets
puts "Enter body of the method"
method_body = gets

method_definition=%[def #{method_name}\n #{method_body}\n end] # compose method
eval(method_definition) # define method
eval(method_name) # invoke your new method

Структуры данных: Стек

Filed under: 1 — botique @ 00:40
Tags: , , , , ,

В данной статье рассмотрим такую элементарную структуру данных, как стек. Стек представляет собой динамическое множество, элементы которого добавляются и удаляются в соответствии со стратегией LIFO (last-in, first-out): первым из стека удаляется элемент, который был помещен туда последним. В программах, например, стек используется для работы с автоматическими переменными. По мере появления автоматические переменные добавляются в вершину стека. Когда их действие прекращается, они удаляются из стека.

Опишем основные свойства и операции стека в общем виде. Стек содержит определенное количество элементов, что делает его контейнером. Значит, его можно реализовать с помощью массива elements с количеством элементов STACK_SIZE. Дополнительно задаются атрибуты topIndex и topElement, представляющие индекс последнего помещенного в стек элемента и сам этот элемент соответственно. Если значение topIndex равно 0, то стек не содержит ни одного элемента и является пустым. Проверить стек на наличие в нем элементов можно с помощью операции isEmpty. Если производится попытка снять элемент с пустого стека, то это приводит к ошибке underflow (опустошение). Если значение topIndex равно STACK_SIZE, то стек переполняется, что приводит к ошибке overflow. Эта проверка осуществляется с помощью операции isFull.

Операция вставки элемента производится функцией PUSH (запись в стек), а операция удаления — функцией POP (снятие верхнего элемента со стека).

Существует множество эффективных способов реализации стеков. В данной статье рассмотрим объектно-ориентированный подход.

В разделе private класса Stack инкапсулируется способ представления данных (обычный массив, динамический, связный список, …). В данный момент ограничимся обычным массивом из STACK_SIZE элементов (константа, специфичная для класса, объявлена в 24 строке, см. листинг 1). В дальнейшем можно легко заменить его на динамический без внесения изменений в общедоступный (public) интерфейс класса.

Функции pop() и push() возвращают информацию о состоянии стека (пуст или заполнен), поэтому объявлены как bool, a не void. Таким образом, программист имеет возможность обработки ситуаций переполнения и очистки стека. Фактически, проверку переполнения и опустошения стека выполняют функции isFull и isEmpty, которые объявлены в разделе private.

Вместо того чтобы давать определение стека на основе конкретного типа данных (int, double, …), мы его опишем на базе обобщенного типа StackElement с использованием спецификатора typedef. Конечно, более правильным вариантом было бы использование шаблонов класса, но в данной статье мы пока их рассматривать не будем.

Далее представлен код на C++

Листинг 1. Файл Stack.h

#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED
typedef int StackElement;

class Stack
{
    public:
        Stack(); //default constructor
        ~Stack(); // destructor

        /*inserts a new element to stack,
          returns true if it is possible */
        bool push(const StackElement & element);

        /* deletes a top element from the stack,
           returns true if it is possible*/
        bool pop();

        /* returns top element of stack*/
        StackElement getTopElement() const;

    private:
        /* size of stack, constant */
        enum {STACK_SIZE = 5};

        StackElement elements[STACK_SIZE];

        /* index of top element*/
        int topIndex;

        /* value of the top element*/
        StackElement topElement;

        /* checks if stack is empty */
        bool isEmpty() const;

        /* checks if stack is full */
        bool isFull() const;
};
#endif

Листинг 2. Файл Stack.cpp

#include "stack.h"

Stack::Stack()
{
    topIndex = 0;
}

Stack::~Stack(){}

bool Stack::isEmpty() const
{
    return topIndex == 0;
}

bool Stack::isFull() const
{
    return topIndex == STACK_SIZE;
}

bool Stack::push(const StackElement & element)
{
    if (!isFull())
    {
        elements[topIndex++] = element;
        topElement = elements[topIndex];
        return true;
    }
    return false;
}

bool Stack::pop()
{
    if (!isEmpty())
    {
        topElement = elements[--topIndex];
        return true;
    }
    return false;
}

StackElement Stack::getTopElement() const
{
    return topElement;
}

Листинг 3. Файл main.cpp

#include <iostream>
#include <cctype>
using namespace std;
#include "stack.h"

int main()
{
    char ch;
    int elem;
	Stack stack;

    cout<<"Enter 'I' to insert element to stack, \n"
        <<"'D' to delete element from stack, \n"
        <<"'Q' to quit\n";

    while(cin>>ch && toupper(ch) != 'Q')
    {
        switch(ch)
        {
            case 'I' :
            case 'i' : cout<< "Enter element to insert:\n";
            cin>>elem;
            if (stack.push(elem))
            {
                cout<<"Element "<<elem<<" is inserted to stack.\n";
            }
            else
            {
                cout<<"Stack overflow!\n";
            }
            break;

            case 'D' :
            case 'd' :
            if (stack.pop())
            {
                cout<<"Element "<<stack.getTopElement()<<" is deleted from stack.\n";
            }
            else
            {
                cout<<"Stack underflow!\n";
            }
            break;
        }
    }
    return 0;
}

Литература:
1) Т. Кормен, Ч. Лейзерсон, Р. Ривест, К. Штайн. Алгоритмы. Построение и анализ.
2) С. Прата. Язык программирования С++. Лекции и упражнения.

Тема: Rubric. Блог на WordPress.com.

Follow

Get every new post delivered to your Inbox.