• Напишите пожалуйста комментарии к программе на С++, что к чему скажем так.
    Задание было такое:
    Заполните случайным образом массив (100 элементов) поочередно бук-вами латинского алфавита от A до H и символами цифр от 1 до 8. Про-верьте, есть ли в данном массиве записи, сходные с записью ходов коня по шахматной доске, и, если есть заполните ими второй массив. Выполните сортировку полученных массивов. Для контроля результата сделайте распечатку массивов, в том числе исходного.

    #include
    #include
    #include

    char string[101]; // вводимое число
    char * temp;
    char tempWord[1024];

    void checkIdentical(char str[]) {
    int i, j, size;
    char c;
    bool br;

    size = strlen(str);

    for(i = 0; i < size; i++) {
    c = str[i];
    for(j = i + 1; j < size; j++) {
    if(c == str[j]) {
    printf("%s", str);
    br = !br;
    break;
    }
    }
    if(br) {
    break;
    }
    }
    }

    int main()
    {

    printf("enter");
    gets(string);

    temp = strtok(string, " ");

    printf("words with identical letters:");
    for(; temp != NULL;) {
    strcpy(tempWord, temp);
    checkIdentical(tempWord);
    temp = strtok(NULL, " ");
    }

    return 0;
    }

Ответы 1

  • Сама задачка порадовала, написал используя только функции С++. Задание реализовал полностью. В прикреплённом файле с нормальным форматированием.#include <iostream>#include <random>#include <vector>#include <algorithm>// Описывает шахматную нотацию.struct Notation;// Заполняет массив случайными шахматными ходами.void FillField(std::vector<Notation>&);// Поиск в массиве комбинаций "ход конём".std::vector<Notation> SearchMoves(const std::vector<Notation>&);// Поиск возможных комбинаций для хода.std::vector<Notation> SearchMoves(const Notation&);// Проверка выхода за границу.bool CheckMov(const Notation&, int, int);// Выводит массив в поток.std::ostream& PrintGround(const std::vector<Notation>&, std::ostream& = std::cout);int main(){ std::vector<Notation> field(100); // Заполняем поле. FillField(field); // Выводим исходный массив. PrintGround(field, std::cout) << std::endl; // Поиск комбинаций "ход конём". std::vector<Notation> fieldMovs = SearchMoves(field); // Выводим полученный массив. PrintGround(fieldMovs, std::cout) << std::endl; // Отсортируем оба массива в порядке возрастания. std::sort(field.begin(), field.end()); std::sort(fieldMovs.begin(), fieldMovs.end()); // Выводим полученные массивы. PrintGround(field, std::cout) << std::endl; PrintGround(fieldMovs, std::cout) << std::endl; return 0;}// Описывает шахматную нотацию.struct Notation{ unsigned char H; unsigned int  V; bool operator==(const Notation& rhs) const{ return ((rhs.H == H) && (rhs.V == V)); } bool operator<(const Notation& rhs) const{ return ((rhs.H < H) || ((rhs.H == H)  && (rhs.V < V))); }};// Заполняет массив случайными шахматными ходами.void FillField(std::vector<Notation>& field){ std::default_random_engine generator; std::uniform_int_distribution<int> distribution(1, 8); for (auto& i : field){ i.H = 'a' + distribution(generator) - 1; i.V = distribution(generator); }}// Поиск возможных комбинаций для хода.std::vector<Notation> SearchMoves(const Notation& stroke){ std::vector<Notation> temp; int x, y; for (int i = 0; i < 8; ++i){ switch (i){ case 0: // Вверх влево. y = +3; x = -1; break; case 1: // Вверх вправо. y = +3; x = +1; break; case 2: // Вправо вверх. y = +1; x = +3; break; case 3: // Вправо вниз. y = -1; x = +3; break; case 4: // Вниз вправо. y = -3; x = +1; break; case 5: // Вниз влево. y = -3; x = -1; break; case 6: // Влево вниз. y = -1; x = -3; break; case 7: // Влево вверх. y = +1; x = -3; break; } // Если ход возможен, добавим его в массив. if (CheckMov(stroke, x, y)) temp.push_back(Notation{ stroke.H + x, stroke.V + y }); } return std::vector<Notation>(temp);}// Проверка выхода за границу.bool CheckMov(const Notation& stroke, int x, int y){ bool isLTBorder = (stroke.H + x >= 'a') && (stroke.V + y >= 1); bool isRBBorder = (stroke.H + x <= 'h') && (stroke.V + y <= 8); return (isLTBorder && isRBBorder);}// Поиск в массиве комбинаций "ход конём".std::vector<Notation> SearchMoves(const std::vector<Notation>& field){ std::vector<Notation> possible; // Все возможные ходы одного элемента. std::vector<Notation> temp = SearchMoves(*field.begin()); for (auto i = field.begin() + 1; i < field.end(); ++i){ for (auto u : temp){ // Ход в массиве - есть ход конём. if (u == *i) { possible.push_back(u); break; } } temp = SearchMoves(*i); } return std::vector<Notation>(possible);}// Выводит массив в поток.std::ostream& PrintGround(const std::vector<Notation>& field, std::ostream& out){ for (auto i : field) out << i.H << i.V << " - "; return out;}
    • Автор:

      fleming
    • 6 лет назад
    • 0
  • Добавить свой ответ

Войти через Google

или

Забыли пароль?

У меня нет аккаунта, я хочу Зарегистрироваться

How much to ban the user?
1 hour 1 day 100 years