воскресенье, 19 февраля 2017 г.

Магазин для своего сервера Minecraft.

Установка магазина на Apache

Установка mod_wsgi

В первую очередь необходимо установить модуль wsgi. Либо воспользовавшись исходным кодом (что я и сделал, когда впервые потребовалось прикрутить python к apache) следуя по инструкции. Либо взять готовый модуль из репозитория:
~$ sudo apt-get install libapache2-mod-wsgi

Настройка виртуального хоста

Для этого перейдем в директорию:
~$ cd /etc/apache2/sites-enabled/
и отредактируем наш конфигурационный файл:
~$ sudo vi kalinchyk-ssl.conf
должно получиться что-то в этом роде:

<VirtualHost *>
    ServerName www.kalinchyk.com
    ServerAdmin viacheslav@kalinchyk.com
    DocumentRoot /var/www/minecraft

    WSGIDaemonProcess wsgi user=www-data group=www-data processes=1 threads=5
    WSGIScriptAlias /api /var/www/wsgi/app.wsgi
    <Directory /var/www/wsgi>
            WSGIProcessGroup wsgi
            WSGIApplicationGroup %{GLOBAL}
            Require all granted
    </Directory>
</VirtualHost>

Здесь мы сообщили Apache, что необходимо при обращении клиента к директории /api выполнять python wsgi-скрипт (который физически размещен в директории /var/www/wsgi/app.wsgi) от имени пользователя www-data.
Обязательно проверьте, что вашему пользователю доступны импортируемые библиотеки и все файлы он может читать, а при необходимости и вносить изменения.

Также в настройках виртуального хоста указана основная директория с которой будет клиент работать (/var/www/minecraft).

В этом кусочке конфигурации я убрал строки для настройки ssl-сертификата, логирования и т.д., чтобы не перегружать пример.

После изменений конфигурационных файлов Apache требуется перезапустить:
~$ sudo service apache2 restart

BackEnd

Сначала устанавливаем backend (API магазина). Для этого забираем исходные коды с git-репозитория. Распаковываем архив и содержимое wsgi копируем в нашу wsgi директорию (в моем случае это /var/www/wsgi/).
Т.к. мы для повышения безопасности указали, что python скрипты должны выполняться от имени www-data, то необходимо проверить чтобы директория и содержимое принадлежат этому пользователю.
~$ sudo chmod -R 644 /var/www/wsgi
~$ sudo chown -R www-data:www-data /var/www/wsgi
Первым делом необходимо создать базу данных, выполнив db_update.py от имени нашего пользователя.
~$ python db_update.py
А также при последующих обновлениях необходимо не забывать про эту операцию. Этот скрипт выполняет важные изменения в структуре базы данных. Хоть скрипт самостоятельно сделает резервную копию базы, но необходимо об этом также не забывать и периодически самостоятельно архивировать критически важные данные.

Устанавливаем зависимости

Для корректной работы python приложения необходимо установить несколько зависимостей, а именно bottle, bottle_sqlite, bottle_errorrest. Их можно установить из пакетного менеджера pip:
~$ sudo apt-get install python-pip
~$ sudo -u www-data -H pip install pip
~$ sudo -u www-data -H pip install bottle
~$ sudo -u www-data -H pip install bottle_sqlite
~$ sudo -u www-data -H pip install bottle_errorsrest
И обязательно устанавливаем их для нашего пользователя (параметр -u ww-data), под которым будет выполняться скрипт (параметр -H).

Проверяем работу приложения

В браузере указав адрес своего сервера и директорию, которая обслуживает wsgi, а также суффикс /whoami мы должны получить положительный отклик от сервера.
~$ curl https://test.kalinchyk.com/api/whoami
{"object": "CUSTOMER"}


Настраиваем приложение

Для настройки приложения необходимо создать файл с именем minecraft.json:

{
    "minecraft": {
        "acquiring": {
            "form_method": "post",
            "form_url": "https://sci.interkassa.com/",
            "id": "[идентификатор_кассы_в_interkassa]",
            "sign": "[секретный_ключ_для_формирования_подписи]",
            "sign_test": "[секретный_ключ_для_проверки_подписи_(тест)]",
            "type": "interkassa"
        },
        "admin_username": "[логин_администратора]",
        "admin_password": "[пароль_администратора]",
        "cookie_name": "minecraft_cookie",
        "cookie_sign": "minecraft_secret",
        "server_host": "[адрес_к_серверу_minecraft]",
        "server_query_port": 25565,
        "server_rcon_password": "[пароль_к_rcon]",
        "server_rcon_port": 25575,
        "server_url": "https://test.kalinchyk.com/",
        "server_api": "https://test.kalinchyk.com/"
    }
}

Жирным выделены параметры, которые необходимо заполнить в первую очередь.


FrontEnd

Теперь можно приступить к установке веб-интерфейса магазина. Из ранее извлеченного архива, который был получен на сайте, содержимое minecraft копируем в нашу minecraft директорию (в моем случае это /var/www/minecraft/).


Настраиваем frontend

В директории /var/www/minecraft/ создаем файл .htaccess

Options -Indexes +FollowSymLinks
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* /var/www/minecraft/index.html [L]
DirectoryIndex index.html



Здесь мы включаем модуль rewrite и перенаправляем все запросы на несуществующие файлы/директории будут перенаправлены на index.html


понедельник, 5 октября 2015 г.

WebLogic Server. Encrypt & Decrypt password.

На днях возникла задача хранения некоторой части данных в базе данных. Из темы ясно, что данные должны быть зашифрованы. Чтобы не изобретать велосипед, первым делом отправился в www.google.com с вопросом как же шифруются пароли weblogic'а.

В результате получился маленький класс для шифровки и расшифровки паролей по аналогии как это делает weblogic server.

package com.kalinchyk.util;

import weblogic.security.internal.SerializedSystemIni;
import weblogic.security.internal.encryption.*;

public final class WebLogicSecure {
    
    private static EncryptionService es = null;
    private static ClearOrEncryptedService ces = null;

    public static String decrypt(String pwd) throws Exception {
        es = SerializedSystemIni.getExistingEncryptionService();
        if (es == null)
            throw new Exception("Unable to initialize decryption service");
        ces = new ClearOrEncryptedService(es);
        return ces.decrypt(pwd);
    }    

    public static String encrypt(String pwd) throws Exception {
        es = SerializedSystemIni.getExistingEncryptionService();
        if (es == null)
            throw new Exception("Unable to initialize encryption service");
        ces = new ClearOrEncryptedService(es);
        return ces.encrypt(pwd);
    }
}

Но необходимо учесть, что данные зашифрованные на одном сервере не могут быть расшифрованы на другом, т.к. мы используем ключ самого wls, который формируется (генерируется) в момент установки и будет уникальным для всех серверов.

Для тестирования на локальной машине можно использовать файл SerializedSystemIni.dat из IntegratedWebLogicServer, который необходимо сохранить в директорию с вашим проектом.

понедельник, 27 апреля 2015 г.

JavaScript Frameworks Day 2015

На прошедших выходных (26 апреля 2015 года) прошел очередной ивент от frameworksdays по тематике JavaScript. Как обычно было очень много интересных докладов, конкурсов, подарков!

Спасибо организаторам за яркое воскресенье. 

Есть желание посетить следующие ивенты? Регистрируйтесь и приходите.


пятница, 20 марта 2015 г.

Отчеты BI Publisher и шрифт Times New Roman (кириллица)

Столкнулся с необходимостью формировать отчеты в старой версии Oracle BI Publisher Enterprise (10.1.3.4.1) и сразу возникла сложность со шрифтам. Причем проблема возникала только при формировании отчета в формате pdf. Вместо правильных шрифтов статически указывался Alban WT J и вся кириллица смотрелась ужасно, стили не соответствовали шаблону - небыло выделения жирным и остальные странные артефакты.

Решение:

Первым делом скопировать необходимые шрифты из windows (c:\windows\fonts\), например, Times New Roman, Arial и т.д. в директорию jre/lib/fonts (тут необходимо четко понимать, какой из jre использует ваш BIP, так например на нашей тестовой среде используется не родной).

Следующим шагом прописать группу шрифтов в конфигурационный файл (xdo.cfg). В зависимости от задачи - это может быть глобальный файл (расположен %BIP%/xmlp/XMLP/Admin/Configuration) или локальный для определенного отчета. Мой конфиг выглядит теперь так:
<config version="1.0.0" xmlns="http://xmlns.oracle.com/oxp/config/">

   <properties>
      <property name="pdf-compression">true</property>
   </properties>
   <fonts>
        <font family="Arial" style="normal" weight="normal"> 
            <truetype path="/arial.ttf" /> 
        </font> 
        <font family="Arial" style="italic" weight="normal"> 
            <truetype path="/ariali.ttf" /> 
        </font> 
        <font family="Arial" style="normal" weight="bold"> 
            <truetype path="/arialbd.ttf" /> 
        </font> 
        <font family="Arial" style="italic" weight="bold"> 
            <truetype path="/arialbi.ttf" /> 
        </font>    

        <font family="Times New Roman" style="normal" weight="normal"> 
            <truetype path="/times.ttf" /> 
        </font> 
        <font family="Times New Roman" style="italic" weight="normal"> 
            <truetype path="/timesi.ttf" /> 
        </font> 
        <font family="Times New Roman" style="normal" weight="bold"> 
            <truetype path="/timesbd.ttf" /> 
        </font> 
        <font family="Times New Roman" style="italic" weight="bold"> 
            <truetype path="/timesbi.ttf" /> 
        </font>    

      <font family="Default" style="normal" weight="normal">
         <truetype path="/times.ttf" />
      </font>

      <!--Font substitute setting (for PDFForm filling etc...) -->
      <font-substitute name="MSGothic"> 
         <truetype path="/msgothic.ttc" ttcno="0" />
      </font-substitute>  
   </fonts>
</config>

среда, 11 марта 2015 г.

CodenJoy. 2048


В предыдущем посте я написал о посещении frameworksdays, на котором нас познакомили с проектом codenjoy. Очередные головоломки для разработчиков. В перечне задачек была предложена игра 2048 - суть задания написать алгоритм (бота), позволяющий набрать максимальное количество баллов из всех зарегистрированных участников.

Взаимодействие с сервером осуществляется посредством websoсket'ов. Значит нет привязки к языку программирования - что не может не радовать. 

Установил себе модуль https://pypi.python.org/pypi/websocket-client для работы с вебсокетами через python и начеркал примитивный алгоритм, который может прийти в голову - постоянно жмем кнопку вниз, когда строка (двумерный массив разложенный в строку) не изменилась от предыдущего действия, то нажимаем влево. В результате имеем следующий код:


import websocket

def on_message(ws, message):
    ws.send("LEFT" if message == ws.last_message else "DOWN")
    ws.last_message = message

if __name__ == "__main__":
    ws = websocket.WebSocketApp( "ws://tetrisj.jvmhost.net:12270/codenjoy-contest/ws?user=[user]"
                               , on_message = on_message)
    ws.last_message = ""
    ws.run_forever()


Такой бот смог набрать 7938 и занять 3е место в рейтинге, к заметке - второе место имеет такое же количество баллов.

Для сброса текущего счета (перерегистрация) клиента:
curl http://codenjoy.com/codenjoy-contest/register -d "name=[user]&password=[pass]&gameName=a2048"

Если будет возможность написать обновленного бота, который выйдет на первую строчку рейтинга, то обязательно выложу исходный код. И напоследок - советую всем попробовать свои силы в написании алгоритмов для подобных задачек.

вторник, 10 марта 2015 г.

Java Frameworks Day 2015

7 марта посетил великолепный ивент frameworksdays с тематиками для java разработчиков, хоть java не моя стихия, но было очень захватывающе. Спасибо большое организаторам за проведенное мероприятие и докладчикам за интересные презентации.

вторник, 14 января 2014 г.

Codility. Train. Brackets ★

A string S consisting of N characters is considered to be properly nested if any of the following conditions is true:
  • S is empty;
  • S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string;
  • S has the form "VW" where V and W are properly nested strings.
For example, the string "{[()()]}" is properly nested but "([)()]" is not.
Write a function:
int solution(char *S);
that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise.
For example, given S = "{[()()]}", the function should return 1 and given S = "([)()]", the function should return 0, as explained above.
Assume that:
  • N is an integer within the range [0..200,000];
  • string S consists only of the following characters: "(", "{", "[", "]", "}" and/or ")".
Complexity:
  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(N) (not counting the storage required for input arguments).

понедельник, 13 января 2014 г.

Codility. Train. Number-of-disc-intersections ★★★

Given an array A of N integers, we draw N discs in a 2D plane such that the I-th disc is centered on (0,I) and has a radius of A[I]. We say that the J-th disc and K-th disc intersect if J ≠ K and J-th and K-th discs have at least one common point.
Write a function:
def solution(A)
that, given an array A describing N discs as explained above, returns the number of pairs of intersecting discs. For example, given N=6 and:
A[0] = 1  A[1] = 5  A[2] = 2 
A[3] = 1  A[4] = 4  A[5] = 0  
intersecting discs appear in eleven pairs of elements:
  • 0 and 1,
  • 0 and 2,
  • 0 and 4,
  • 1 and 2,
  • 1 and 3,
  • 1 and 4,
  • 1 and 5,
  • 2 and 3,
  • 2 and 4,
  • 3 and 4,
  • 4 and 5.
so the function should return 11.
The function should return −1 if the number of intersecting pairs exceeds 10,000,000.
Assume that:
  • N is an integer within the range [0..100,000];
  • each element of array A is an integer within the range [0..2147483647].
Complexity:
  • expected worst-case time complexity is O(N*log(N));
  • expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.

Codility. Train. Max-product-of-three ★★

A non-empty zero-indexed array A consisting of N integers is given. The product of triplet (P, Q, R) equates to A[P] * A[Q] * A[R] (0 ≤ P < Q < R < N).
For example, array A such that:
  A[0] = -3
  A[1] = 1
  A[2] = 2
  A[3] = -2
  A[4] = 5
  A[5] = 6
contains the following example triplets:
  • (0, 1, 2), product is −3 * 1 * 2 = −6
  • (1, 2, 4), product is 1 * 2 * 5 = 10
  • (2, 4, 5), product is 2 * 5 * 6 = 60
Your goal is to find the maximal product of any triplet.
Write a function:
def solution(A)
that, given a non-empty zero-indexed array A, returns the value of the maximal product of any triplet.
For example, given array A such that:
  A[0] = -3
  A[1] = 1
  A[2] = 2
  A[3] = -2
  A[4] = 5
  A[5] = 6
the function should return 60, as the product of triplet (2, 4, 5) is maximal.
Assume that:
  • N is an integer within the range [3..100,000];
  • each element of array A is an integer within the range [−1,000..1,000].
Complexity:
  • expected worst-case time complexity is O(N*log(N));
  • expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.

Codility. Train. Triangle ★

A zero-indexed array A consisting of N integers is given. A triplet (P, Q, R) is triangular if 0 ≤ P < Q < R < N and:
  • A[P] + A[Q] > A[R],
  • A[Q] + A[R] > A[P],
  • A[R] + A[P] > A[Q].
For example, consider array A such that:
  A[0] = 10    A[1] = 2    A[2] = 5
  A[3] = 1     A[4] = 8    A[5] = 20
Triplet (0, 2, 4) is triangular.
Write a function:
def solution(A)
that, given a zero-indexed array A consisting of N integers, returns 1 if there exists a triangular triplet for this array and returns 0 otherwise. For example, given array A such that:
  A[0] = 10    A[1] = 2    A[2] = 5
  A[3] = 1     A[4] = 8    A[5] = 20
the function should return 1, as explained above. Given array A such that:
  A[0] = 10    A[1] = 50    A[2] = 5
  A[3] = 1
the function should return 0.
Assume that:
  • N is an integer within the range [0..1,000,000];
  • each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].
Complexity:
  • expected worst-case time complexity is O(N*log(N));
  • expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.

пятница, 10 января 2014 г.

Codility. Train. Genomic-range-query ★★★

A non-empty zero-indexed string S is given. String S consists of N characters from the set of upper-case English letters A, C, G, T.
This string actually represents a DNA sequence, and the upper-case letters represent single nucleotides.
You are also given non-empty zero-indexed arrays P and Q consisting of M integers. These arrays represent queries about minimal nucleotides. We represent the letters of string S as integers 1, 2, 3, 4 in arrays P and Q, where A = 1, C = 2, G = 3, T = 4, and we assume that A < C < G < T.
Query K requires you to find the minimal nucleotide from the range (P[K], Q[K]), 0 ≤ P[i] ≤ Q[i] < N.
For example, consider string S = GACACCATA and arrays P, Q such that:
    P[0] = 0    Q[0] = 8
    P[1] = 0    Q[1] = 2
    P[2] = 4    Q[2] = 5
    P[3] = 7    Q[3] = 7
The minimal nucleotides from these ranges are as follows:
  • (0, 8) is A identified by 1,
  • (0, 2) is A identified by 1,
  • (4, 5) is C identified by 2,
  • (7, 7) is T identified by 4.
Write a function:
def solution(S, P, Q)
that, given a non-empty zero-indexed string S consisting of N characters and two non-empty zero-indexed arrays P and Q consisting of M integers, returns an array consisting of M characters specifying the consecutive answers to all queries.
The sequence should be returned as:
  • a Results structure (in C), or
  • a vector of integers (in C++), or
  • a Results record (in Pascal), or
  • an array of integers (in any other programming language).
For example, given the string S = GACACCATA and arrays P, Q such that:
    P[0] = 0    Q[0] = 8
    P[1] = 0    Q[1] = 2
    P[2] = 4    Q[2] = 5
    P[3] = 7    Q[3] = 7
the function should return the values [1, 1, 2, 4], as explained above.
Assume that:
  • N is an integer within the range [1..100,000];
  • M is an integer within the range [1..50,000];
  • each element of array P, Q is an integer within the range [0..N − 1];
  • P[i] ≤ Q[i];
  • string S consists only of upper-case English letters A, C, G, T.
Complexity:
  • expected worst-case time complexity is O(N+M);
  • expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.

среда, 25 декабря 2013 г.

Codility. Train. Passing-cars ★★

A non-empty zero-indexed array A consisting of N integers is given. The consecutive elements of array A represent consecutive cars on a road.
Array A contains only 0s and/or 1s:
  • 0 represents a car traveling east,
  • 1 represents a car traveling west.
The goal is to count passing cars. We say that a pair of cars (P, Q), where 0 ≤ P < Q < N, is passing when P is traveling to the east and Q is traveling to the west.
For example, consider array A such that:
  A[0] = 0
  A[1] = 1
  A[2] = 0
  A[3] = 1
  A[4] = 1
We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4).
Write a function:
def solution(A)
that, given a non-empty zero-indexed array A of N integers, returns the number of passing cars.
The function should return −1 if the number of passing cars exceeds 1,000,000,000.
For example, given:
  A[0] = 0
  A[1] = 1
  A[2] = 0
  A[3] = 1
  A[4] = 1
the function should return 5, as explained above.
Assume that:
  • N is an integer within the range [1..100,000];
  • each element of array A is an integer within the range [0..1].
Complexity:
  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.

Codility. Train. Max-Counters ★★★

You are given N counters, initially set to 0, and you have two possible operations on them:
  • increase(X) − counter X is increased by 1,
  • max_counter − all counters are set to the maximum value of any counter.
A non-empty zero-indexed array A of M integers is given. This array represents consecutive operations:
  • if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
  • if A[K] = N + 1 then operation K is max_counter.
For example, given integer N = 5 and array A such that:
    A[0] = 3
    A[1] = 4
    A[2] = 4
    A[3] = 6
    A[4] = 1
    A[5] = 4
    A[6] = 4
the values of the counters after each consecutive operation will be:
    (0, 0, 1, 0, 0)
    (0, 0, 1, 1, 0)
    (0, 0, 1, 2, 0)
    (2, 2, 2, 2, 2)
    (3, 2, 2, 2, 2)
    (3, 2, 2, 3, 2)
    (3, 2, 2, 4, 2)
The goal is to calculate the value of every counter after all operations.
Write a function:
def solution(N, A)
that, given an integer N and a non-empty zero-indexed array A consisting of M integers, returns a sequence of integers representing the values of the counters.
The sequence should be returned as:
  • a structure Results (in C), or
  • a vector of integers (in C++), or
  • a record Results (in Pascal), or
  • an array of integers (in any other programming language).
For example, given:
    A[0] = 3
    A[1] = 4
    A[2] = 4
    A[3] = 6
    A[4] = 1
    A[5] = 4
    A[6] = 4
the function should return [3, 2, 2, 4, 2], as explained above.
Assume that:
  • N and M are integers within the range [1..100,000];
  • each element of array A is an integer within the range [1..N + 1].
Complexity:
  • expected worst-case time complexity is O(N+M);
  • expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.

Codility. Train. Frog-River-One ★★

A small frog wants to get to the other side of a river. The frog is currently located at position 0, and wants to get to position X. Leaves fall from a tree onto the surface of the river.
You are given a non-empty zero-indexed array A consisting of N integers representing the falling leaves. A[K] represents the position where one leaf falls at time K, measured in minutes.
The goal is to find the earliest time when the frog can jump to the other side of the river. The frog can cross only when leaves appear at every position across the river from 1 to X.
For example, you are given integer X = 5 and array A such that:
  A[0] = 1
  A[1] = 3
  A[2] = 1
  A[3] = 4
  A[4] = 2
  A[5] = 3
  A[6] = 5
  A[7] = 4
In minute 6, a leaf falls into position 5. This is the earliest time when leaves appear in every position across the river.
Write a function:
def solution(X, A)
that, given a non-empty zero-indexed array A consisting of N integers and integer X, returns the earliest time when the frog can jump to the other side of the river.
If the frog is never able to jump to the other side of the river, the function should return −1.
For example, given X = 5 and array A such that:
  A[0] = 1
  A[1] = 3
  A[2] = 1
  A[3] = 4
  A[4] = 2
  A[5] = 3
  A[6] = 5
  A[7] = 4
the function should return 6, as explained above. Assume that:
  • N and X are integers within the range [1..100,000];
  • each element of array A is an integer within the range [1..X].
Complexity:
  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(X), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.

вторник, 24 декабря 2013 г.

Codility. Train. Perm-Check ★

A non-empty zero-indexed array A consisting of N integers is given.
permutation is a sequence containing each element from 1 to N once, and only once.
For example, array A such that:
    A[0] = 4
    A[1] = 1
    A[2] = 3
    A[3] = 2
is a permutation, but array A such that:
    A[0] = 4
    A[1] = 1
    A[2] = 3
is not a permutation.
The goal is to check whether array A is a permutation.
Write a function:
def solution(A)
that, given a zero-indexed array A, returns 1 if array A is a permutation and 0 if it is not.
For example, given array A such that:
    A[0] = 4
    A[1] = 1
    A[2] = 3
    A[3] = 2
the function should return 1.
Given array A such that:
    A[0] = 4
    A[1] = 1
    A[2] = 3
the function should return 0.
Assume that:
  • N is an integer within the range [1..100,000];
  • each element of array A is an integer within the range [1..1,000,000,000].
Complexity:
  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.

Codility. Train. Tape-Equilibrium ★★★

A non-empty zero-indexed array A consisting of N integers is given. Array A represents numbers on a tape.
Any integer P, such that 0 < P < N, splits this tape into two non−empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].
The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|
In other words, it is the absolute difference between the sum of the first part and the sum of the second part.
For example, consider array A such that:
  A[0] = 3
  A[1] = 1
  A[2] = 2
  A[3] = 4
  A[4] = 3
We can split this tape in four places:
  • P = 1, difference = |3 − 10| = 7 
  • P = 2, difference = |4 − 9| = 5 
  • P = 3, difference = |6 − 7| = 1 
  • P = 4, difference = |10 − 3| = 7 
Write a function:
def solution(A)
that, given a non-empty zero-indexed array A of N integers, returns the minimal difference that can be achieved.
For example, given:
  A[0] = 3
  A[1] = 1
  A[2] = 2
  A[3] = 4
  A[4] = 3
the function should return 1, as explained above.
Assume that:
  • N is an integer within the range [2..100,000];
  • each element of array A is an integer within the range [−1,000..1,000].
Complexity:
  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.

Codility. Train. Perm-Missing-Elem ★★

A zero-indexed array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.
Your goal is to find that missing element.
Write a function:
def solution(A)
that, given a zero-indexed array A, returns the value of the missing element.
For example, given array A such that:
  A[0] = 2
  A[1] = 3
  A[2] = 1
  A[3] = 5
the function should return 4, as it is the missing element.
Assume that:
  • N is an integer within the range [0..100,000];
  • the elements of A are all distinct;
  • each element of array A is an integer within the range [1..(N + 1)].
Complexity:
  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.

Codility. Train. Frog-Jmp ★

A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.
Count the minimal number of jumps that the small frog must perform to reach its target.
Write a function:
def solution(X, Y, D)
that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.
For example, given:
  X = 10
  Y = 85
  D = 30
the function should return 3, because the frog will be positioned as follows:
  • after the first jump, at position 10 + 30 = 40
  • after the second jump, at position 10 + 30 + 30 = 70
  • after the third jump, at position 10 + 30 + 30 + 30 = 100
Assume that:
  • X, Y and D are integers within the range [1..1,000,000,000];
  • X ≤ Y.
Complexity:
  • expected worst-case time complexity is O(1);
  • expected worst-case space complexity is O(1).

понедельник, 30 сентября 2013 г.