Задача на собесеовании №1
От: Аноним  
Дата: 29.06.08 09:03
Оценка:
Оцените, пожалуйста, мое решение следующей задачи.

Implement a circular queue of integers of user-specified size using a simple array. Provide routines to initialize(), enqueue() and dequeue() the queue. Make it thread safe.

Please do not to use existing class libraries for this question.



Мое решение

/**
 * Thread safe Circular queue implementation
 */
public class CircularQueue {
    private int[] internalContainer;
    private int lastElementIndex;

    /**
     * Public constructor
     * @param size initial capacity
     */
    public CircularQueue(int size) {
        if(size < 1) {
            throw new IllegalArgumentException("size cannot be negative or zero");
        }
        internalContainer = new int[ size ];
        lastElementIndex = 0;
    }
    
    /**
     * Initialize queue with elements
     * @throws IllegalStateException if input elements more than queue capacity
     */
    public synchronized void initialize(int... elements) {
        if(elements == null) {
            throw new NullPointerException("elements parameter cannot be null");
        }
        else if(elements.length > internalContainer.length) {
            throw new IllegalStateException("elements amount is more than queue capacity");
        }
        
        lastElementIndex = elements.length - 1;        
        
        arrayCopy(elements, 0, internalContainer, 0, elements.length);
    }
    
    /**
     * Adds element to the end of the queue
     * Throws:
     *    IllegalStateException if the element cannot be added at this time due to capacity restrictions
     */
    public synchronized void enqueue(int element) {
        if(lastElementIndex + 1 == internalContainer.length) { 
            throw new IllegalStateException("queue is full");
        }            
            
        internalContainer [ lastElementIndex + 1 ] = element;
        
        ++lastElementIndex;
    }
    
    /**
     * Removes and returns the integer at the beginning of the queue
     * Throws:
     *    IllegalStateException if the queue is empty 
     */
    public synchronized int dequeue() {
        if(lastElementIndex == -1) {
            throw new IllegalStateException("no elements in queue");
        }
        --lastElementIndex;
        
        int result = internalContainer[0];
        
        arrayCopy(internalContainer, 1, internalContainer, 0, internalContainer.length);        
        
        return result;
    }
    
    private void arrayCopy(int[] src, int srcPos, int[] dest, int destPos, int length) {
        for (int i = 0; (i < length) && ((destPos + i) < dest.length) && ((srcPos + i) < src.length); i++) {
            dest [ destPos + i ] = src[ srcPos + i ];
        }
    }
    
}



30.06.08 13:36: Перенесено модератором из 'Java' — Blazkowicz
08.07.08 20:42: Перенесено модератором из 'Архитектура программного обеспечения' — Кодт
08.07.08 20:43: Перенесено модератором из 'Алгоритмы' — пардон, не на то нажал — Кодт
Re: Задача на собесеовании №1
От: Dronzo  
Дата: 29.06.08 09:12
Оценка:
Здравствуйте, <Аноним>, Вы писали:

А> Make it thread safe

А>Мое решение ....
?
... << RSDN@Home 1.2.0 alpha rev. 783>>
Re[2]: Задача на собесеовании №1
От: Dronzo  
Дата: 29.06.08 09:15
Оценка:
Здравствуйте, Dronzo, Вы писали:

D>Здравствуйте, <Аноним>, Вы писали:


А>> Make it thread safe

А>>Мое решение ....
D> ?

Прошу прощения. Не заметил
... << RSDN@Home 1.2.0 alpha rev. 783>>
Re: Задача на собесеовании №1
От: elmal  
Дата: 29.06.08 10:23
Оценка:
Здравствуйте, Аноним, Вы писали:

А>Оцените, пожалуйста, мое решение следующей задачи.


А>[b]Implement a circular queue of integers of user-specified size using a simple array. Provide routines to initialize(), enqueue() and dequeue() the queue. Make it thread safe.

А>Please do not to use existing class libraries for this question.
По стилю почти неплохо, достаточно понятно. По реализации — arrayCopy при добавлении и удалении явно лишее. Performance в результате 0 будет, называется такое алгоритм маляра Френеля кажется. Надо было без него, держать 2 индекса, первый элемент и последний элемент
Re: Задача на собесеовании №1
От: dotidot Россия  
Дата: 29.06.08 10:28
Оценка:
Здравствуйте, Аноним, Вы писали:

А>Please do not to use existing class libraries for this question.


А>
А>    private void arrayCopy(int[] src, int srcPos, int[] dest, int destPos, int length) {
А>        for (int i = 0; (i < length) && ((destPos + i) < dest.length) && ((srcPos + i) < src.length); i++) {
А>            dest [ destPos + i ] = src[ srcPos + i ];
А>        }
А>    }
А>

жестоко мне кажется, что задание было воспринято слишком буквально.
PS остальной код не смотрел
Re[2]: Задача на собесеовании №1
От: Аноним  
Дата: 29.06.08 10:31
Оценка:
Здравствуйте, elmal, Вы писали:

E>Здравствуйте, Аноним, Вы писали:


А>>Оцените, пожалуйста, мое решение следующей задачи.


А>>[b]Implement a circular queue of integers of user-specified size using a simple array. Provide routines to initialize(), enqueue() and dequeue() the queue. Make it thread safe.

А>>Please do not to use existing class libraries for this question.
E>По стилю почти неплохо, достаточно понятно. По реализации — arrayCopy при добавлении и удалении явно лишее. Performance в результате 0 будет, называется такое алгоритм маляра Френеля кажется. Надо было без него, держать 2 индекса, первый элемент и последний элемент

Да, с двумя индексами согласен. Кажется, здесь я прогадал.
http://en.wikipedia.org/w/index.php?title=Circular_buffer&amp;printable=yes
Re: Задача на собесеовании №1
От: insighter ОАЭ  
Дата: 30.06.08 09:59
Оценка:
в методе initialize я бы использовал java.lang.IllegalArgumentException вместо illegal state-а
в scjp(1.5) кстати этому уделяется внимание тоже
... << RSDN@Home 1.1.4 stable SR1 rev. 568>>
java шараги -> enterprise галеры, банки -> highload microservices + bigdata/ml
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.