Поиск нечетных чисел в 2 массиве - Assembler

Узнай цену своей работы

Формулировка задачи:

Всем привет, у меня вот такая проблема которую я не могу решить уже 2 дня. Нужно посчитать нечетные числа в каждой строчке и записать их кол-во в одномерный массив. Но вот у меня проблема с частью записи кол-ва нечетных чисел в одномерный массив. Очень прошу помочь, а то голова уже не варит На си++ это выглядело бы так:
const int ROWS = 2;
const int COLS = 3;
 
int data1[ROWS][COLS] = { { 7, -1, 11 }, { 3, 4, -5 } };
    int result1[ROWS] = {};
 
for (int i= 0; i<=ROWS-1 ; i++)
     for (int j = 0; j<=COLS-1 ;j++)
           {
                  if ( data1[i][j] % 2 ==1 || data1[i][j] % 2 == -1)
                     {
                           result1[i] +=1;  // эта часть не получается на MASM
                     }     
                 else // skip
           }
#include "stdafx.h"
#include <cstdio>
#include <cassert>
 
// For each grade level variant implement own function, e.g.:
void solution_for_grade_7(const int* arr, size_t arr_rows, size_t arr_cols, int* result)
{
    int counter = 0;
    int modNumb = 2;
    __asm
    {

        //  mov ebx, arr//definition of arr 
            mov ecx, [arr_rows] // ecx == for(int ROWS = 2;----;----;)
        RowLoop:
                mov ebx, arr//definition of arr 
            push ecx //save row loop counter
                xor esi, esi
                mov ecx, [arr_cols]
            ColLoop :
                    xor edx, edx
                    mov eax, dword ptr[ebx + esi] // eax = arr[ROWS][n]
                    idiv[modNumb]        // eax = eax mod 2
                    cmp edx, 0 // (eax mod 2) == 0 ?
                    je Skip  // go to Skip, if true
                    inc [counter] 
                Skip:
            add esi, 4
                loop ColLoop // repeat (for COL=N;------;-----) loop
                add ebx, esi //next row
                pop ecx //restore RowLoop counter i.e. ecx = 2
                
//Store counted odd values to result1 array
                xor edx, edx
                xor eax, eax
                mov edx, result
                mov eax, [counter]
                mov [edx + ecx * 4], eax
                mov [counter], 0
                loop RowLoop
    }
}
 
const int ROWS = 2;
const int COLS = 3;
 
int main()
{
 
    // Change the array definitions to be appropriate for your assignments:
    int data1[ROWS][COLS] = { { 7, -1, 11 }, { 3, 4, -5 } };
    int result1[ROWS] = {};  // Note: for some assignments the result will depend on the number of COLS! 
 
    // Change the parameters according to your assignment function, e.g.:
    solution_for_grade_7((const int*)data1, ROWS, COLS, result1);
 
    // Print the result one-dimensional array to the console:
    for (size_t i = 0; i <= 1; i++)
    {
        _tprintf(_T("%d "), result1[i]);
    }
    // :::
    getchar();
    return 0;
}

Решение задачи: «Поиск нечетных чисел в 2 массиве»

textual
Листинг программы
#include "stdafx.h"
#include <cstdio>
#include <cassert>
 
// For each grade level variant implement own function, e.g.:
void solution_for_grade_7(const int* arr, size_t arr_rows, size_t arr_cols, int* result)
{
    int counter = 0; //counter of odd values
    int resIndex = 0; //result index
    int modNumb = 2; 
    __asm
    {
             //col counter
            
            mov ecx, [arr_rows] // ecx == for(int ROWS = 2;----;----;)
            mov ebx, [arr]// arr definition
            
        RowLoop:
                push ecx //save row loop counter
                mov ecx, [arr_cols] // ecx == for(int COLS = 3;----;----;)
                xor esi, esi
            ColLoop:
                     xor edx, edx
                     mov eax, dword ptr[ebx + esi] // eax = arr[ROWS][n]
                     idiv[modNumb]       // eax = eax mod 2
                     cmp edx, 0 // (eax mod 2) == 0 ?
                     je Skip  // go to Skip, if true
                     inc [counter] // counter of odd value increasing
                 Skip:
                     add esi, 4 // next column
            loop ColLoop // repeat (for COL=N;------;-----) loop
                xor edx, edx 
                add ebx, esi //next row offset
                mov edi, result //result array definition
                mov eax, [counter] // eax == amount of odd values
                mov edx, [resIndex] // load result arr index
                mov dword ptr[edi + edx*4], eax //load to result amount of odd values
                mov [counter], 0 //reset counter
                add [resIndex], 1 // next result arr index
                pop ecx // next row
        loop RowLoop
    }
}
 
const int ROWS = 2;
const int COLS = 3;
 
int main()
{
 
    // Change the array definitions to be appropriate for your assignments:
    int data1[ROWS][COLS] = { { 5, 13, 11 }, { 3, 7, -5 } };
    int result1[ROWS];  // Note: for some assignments the result will depend on the number of COLS! 
 
    // Change the parameters according to your assignment function, e.g.:
    solution_for_grade_7((const int*)data1, ROWS, COLS, result1);
 
    // Print the result one-dimensional array to the console:
    for (size_t i = 0; i < ROWS; i++)
    {
        _tprintf(_T("%d "), result1[i]); 
    }
    
    getchar();
    return 0;
}

Объяснение кода листинга программы

Código a Assembler:

  1. mov ecx, [arr_rows] - Эффективно ecx равным arr_rows, что используется в качестве счетчика для цикла.
  2. mov ebx, [arr] - Эффективно ebx равным arr, что используется для доступа к элементам массива.
  3. xor esi, esi - Эффективно esi равным 0, что используется в качестве счетчика для столбца.
  4. xor edx, edx - Эффективно edx равным 0, что используется для хранения результата операции деления.
  5. mov eax, dword ptr[ebx + esi] - Эффективно eax равным arr[row][col], где row и col являются текущими индексами.
  6. idiv[modNumb] - Эффективно делит eax на modNumb с сохранением остатка в edx.
  7. cmp edx, 0 - Проверяет, равен ли остаток от деления edx нулю.
  8. je Skip - Если остаток от деления равен нулю, переходит к метке Skip.
  9. inc [counter] - Увеличивает счетчик на 1.
  10. Skip: - Метка, к которой переходит выполнение, если остаток от деления не равен нулю.
  11. add esi, 4 - Увеличивает счетчик столбца на 1.
  12. loop ColLoop - Переходит к началу цикла ColLoop.
  13. xor edx, edx - Эффективно edx равным 0, что используется для хранения индекса строки.
  14. add ebx, esi - Эффективно ebx равным arr + row, что используется для доступа к следующей строке.
  15. mov edi, result - Эффективно edi равным result, что используется для доступа к результату.
  16. mov eax, [counter] - Эффективно eax равным counter, что используется для хранения количества нечетных чисел.
  17. mov edx, [resIndex] - Эффективно edx равным resIndex, что используется для доступа к индексу результата.
  18. mov dword ptr[edi + edx*4], eax - Эффективно записывает eax в result[resIndex], увеличивая resIndex на 1.
  19. mov [counter], 0 - Сбрасывает счетчик на 0.
  20. add [resIndex], 1 - Увеличивает resIndex на 1.
  21. pop ecx - Восстанавливает значение ecx перед выходом из функции.
  22. loop RowLoop - Переходит к началу цикла RowLoop.

ИИ для рефератов и докладов


  • Экспорт Word по ГОСТу
  • Минимум 80% уникальности текста
  • Поиск релевантных источников в интернете
  • Готовый документ за 2 минуты

Оцени полезность:

6   голосов , оценка 3.833 из 5
Похожие ответы