2014-10-07 4 views
1

Мне нужна помощь с вводом массива поиска. Я попытался поместить двоичный поиск, но я не могу заставить его работать. все остальное работает до тех пор, пока я не поместил значение, которое я ищу в массиве, а затем просто сработает.Поиск 3d Array

Как предполагает, чтобы работать: вход 2 координаты со значением каждого затем вычисляет расстояние между ними то предположит, чтобы позволить пользователю искать координаты для значения и состояния, если найден координирующим это в.

Благодаря

#include "stdafx.h" 
#include <iostream> 
#include <iomanip> //for setprecision 
#include <math.h> 
#include <cstdbool> 
#include <cstdlib> // Needed for rand and srand 
#include <ctime> // Needed for the time function 


using namespace std; 


//Function Prototypes 
void processThroughArray(int[][10][10], int, int, int, int, int, int); 
int searchArray(int[][10][10], int, int, int, int, int, int, int, int); 
const int SIZE = 10; 

int main() 
{ 

// establish array and set all values to 0 
int myArray[10][10][10] = { 0 }; 

// establish x and y position markers 
int x = 0; 
int y = 0; 
int z = 0; 
int x2 = 0; 
int y2 = 0; 
int z2 = 0; 


// establish input for x and y from the user 
int xInput = 0; 
int yInput = 0; 
int zInput = 0; 
int xInput2 = 0; 
int yInput2 = 0; 
int zInput2 = 0; 

// variable for value entered 
int inputValue = 0; 
int inputValue2 = 0; 
double distance = 0; 
int searchValue; 
int result; 


// Get the user's value and coordinate 
cout << "\nPlease enter the x coordinate "; 
cin >> xInput; 
cout << "\nPlease enter the y coordinate "; 
cin >> yInput; 
cout << "\nPlease enter the z coordinate "; 
cin >> zInput; 


cout << "\nPlease enter the value to place in " << xInput << "," << yInput << "," << zInput << " "; 
cin >> inputValue; 

// Get the user's ending value and coordinate 
cout << "\nPlease enter the ending x coordinate "; 
cin >> xInput2; 
cout << "\nPlease enter the ending y coordinate "; 
cin >> yInput2; 
cout << "\nPlease enter the ending z coordinate "; 
cin >> zInput2; 


cout << "\nPlease enter the value to place in " << xInput2 << "," << yInput2 << "," << zInput2 << " "; 
cin >> inputValue2; 

// place the value in the coordinate 
myArray[xInput][yInput][zInput] = inputValue; 
cout << "\nYou have successfully placed the value " << inputValue << " in coordinate " << xInput << ", " << yInput << ", " << zInput << " "; 

myArray[xInput2][yInput2][zInput2] = inputValue2; 
cout << "\nYou have successfully placed the value " << inputValue2 << " in coordinate " << xInput2 << ", " << yInput2 << ", " << zInput2 << " "; 

//Function performing for loop 
processThroughArray(myArray, x, y, z, x2, y2, z2); 

//calculate distance between the two coordinates 
distance = sqrt(pow(xInput2 - xInput, 2.0) + pow(yInput2 - yInput, 2.0) + pow(zInput2 - zInput, 2.0)); 
cout << "\nThe distance between " << xInput << "," << yInput << "," << zInput << " and " << xInput2 << "," << yInput2 << "," << zInput2 << " is "; 
cout << setprecision(4) << distance << endl; 


// indicate end of array processing 
cout << "\nArray Processed" << endl; 

//User inputs value to search for 
cout << "Enter the value you wish to look for: "; 
cin >> searchValue; 

result = searchArray(myArray, SIZE, searchValue, x, y, z, x2, y2,z2); 

//If results contains a -1 the value not found 

if (result == -1) 
{ 
    cout << "That number does not exists in the array.\n"; 
} 

else 
{ 
    cout << "\nValue " << searchValue; 
    cout << " is located at position: " << result << endl; 

} 




system("pause"); 
return 0; 
} 


//************************************************************************** 
// Definition of function processThroughArray: Process through the array * 
//the for loop                * 
//************************************************************************** 
void processThroughArray(int myArray[][10][10], int x, int y, int z, int x2, int y2, int z2) 
{ 

for (int x = 0, x2 = 0; x<10, x2 < 10; x++, x2++) 
{ 
    for (int y = 0, y2 = 0; y<10, y2 < 10; y++, y2++) 

    { 
     for (int z = 0, z2 = 0; z< 10, z2 < 10; z++, z2++) 
     { 

      // Display the value of the coordinate 
      cout << "\nCordinate " << x << ", " << y << ", " << z << " value is " << myArray[x, x2][y, y2][z, z2]; 

     } 
    } 
} 



} 

//************************************************************************** 
// Definition of function searchArray: search array for the value input * 
//                   * 
//************************************************************************** 
int searchArray(int myArray[][10][10], int size, int value,int x, int y, int z, int x2, int y2, int z2) 
{ 
int index = 0; 
int position = -1; 
bool found = false; 


while (index < size && !found) 
{ 
    if (myArray[index][index][index] == value) 
    { 
     found = true; 
     position = index; 

    } 
    index++; 

} 

return position; 
} 

ответ

0

Вы определяете SIZE как 1000, и вы передаете его searchArray():

const int SIZE = 1000; 

// ... 

searchArray(myArray, SIZE, searchValue); 

Вы делаете следующее searchArray():

int searchArray(int myArray[][10][10], int size, int value) 
{ 
    int first = 0, 
     last = size - 1, 

С size - 1000, вы устанавливаете «первый» на 0 и «последний» на 999.

Затем вы делаете следующее (оставляя некоторый ненужный материал):

middle = (first + last)/2; 
if (myArray[middle][middle][middle] = value) 

Итак, давайте возьмем листок бумаги и карандаш. Так как «первая» является 0, и «последний» является 999, это устанавливает «средний» в 449.

Итак, у нас есть две проблемы здесь:

1) вы присваиваете, используя оператор «=» , вместо сравнения с использованием «==», который, по-видимому, является вашим намерением.

2) Вы назначаете значение myArray [449] [449] [449]. К сожалению, ваш массив, намного меньше:

int myArray[10][10][10] = { 0 }; 

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

+0

Вот обновление. Я работал над линейным поиском, но не совсем уверен, что я делаю неправильно в этот момент. Проблема, с которой я сталкиваюсь, заключается в том, что она не ищет массив правильно. Он находит первый номер, но не может найти второе число. Также не удается установить координаты, но я уверен, что мне нужно сосредоточиться на фиксации первой части, прежде чем двигаться дальше. Спасибо, Angela – eDz

+0

* обновленный код вверху также. – eDz

+0

Новая версия кода проверит myArray [0] [0] [0], затем myArray [1] [1] [1] и т. Д., Вплоть до myArray [9] [9] [9]. Он будет искать только десять элементов в вашем массиве и полностью игнорировать остальные 990. Таким образом, если вы не ищете что-то, что можно найти только в этих 10 координатах, вы не найдете его. –