If the generated random number to look for does not exist in hashtable array, then programm gets stuck in endless loop in function void hashSearch(),
whereas it should just get out of the loop and output that search item is not found. The exact place in code is where these to outputs are:
cout << "stuck in else loop \n"; and cout << "stuck in while loop end \n";.
I've googled around, but can't find similar examples.
#include <iostream>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <chrono>
using namespace std;
int arr [1000];
int arr2 [1000];
int randArrayInt, n, randSearchItem, searchInt, address, size2;
void printZeroArr();
void linearSentinelSearch();
void printHashArray();
void hashSearch();
int main ()
{
srand (time(nullptr)); //initialize random seed:
n = rand() % 900 + 100; //random integer number from 100 - 1000, length of the array
//n = rand() % 10; // random number in the range 1-10 for sanity tests, length of the array
//randSearchItem = rand() % 10 + 1;
randSearchItem = rand() % 900 + 100; //this is the number to search for
cout << "Array length is " << n << endl;
cout << "[";
for (int i = 0; i <= n; i++)
{
randArrayInt = rand() % 900 + 100;
//randArrayInt = rand() % 10 + 1; // generate random 1-10 number for for sanity tests
arr[i] = randArrayInt; // insert into array position the generated random number
cout<< " " << arr[i]; // print out array element at current loop position
}
cout << " ]\n" << endl;
printZeroArr();
}
void printZeroArr()
{
size2 = n + 1; //length of hashed array
cout << "This is the random key to search for in array: " << randSearchItem << endl;
cout << "This is the size2 length " << size2 << endl;
cout << "This is the hasharray with zeros" << endl;
cout << "[";
for (int i = 0; i <= size2; i++)
{
arr2[i] = 0; // insert into hasharray number 0
cout<< " " << arr2[i]; // print out hasharray element at current loop position
}
cout << " ]\n" << endl;
linearSentinelSearch();
}
void linearSentinelSearch()
{
auto start = std::chrono::high_resolution_clock::now();
arr[n + 1] = randSearchItem;
//cout << "testing arr[n + 1] is " << arr[n + 1] << endl;
int i = 0;
while (arr[i] != randSearchItem) i++;
if (i == n + 1)
cout << "Sentinel search did not found the searchitem in random array" << "\n" << endl;
else
cout << "Searchitem found in array with linearsearch at position " << i << "\n" << endl;
auto finish = std::chrono::high_resolution_clock::now();
chrono::duration<double> elapsed = finish - start;
cout << "Elapsed time: " << elapsed.count() << " s\n";
printHashArray();
}
void printHashArray()
{
//cout << "printing out 'address' value, or the modulo result: " << endl;
//cout << "[";
for (int i = 0; i <= n; i++)
{
address = arr[i] % size2;
//cout << " " << address;
while (arr2[address] != 0)
{
if (address == size2 - 1)
{
address = 0;
} else
{
address++;
}
}
arr2[address] = arr[i];
}
//cout << " ]\n" << endl;
cout << "This is the hasharray with hashitems" << endl;
cout << "[";
for (int i = 0; i <= size2; i++)
{
cout << " " << arr2[i];
}
cout << " ]\n" << endl; hashSearch();
}
void hashSearch()
{
auto start = std::chrono::high_resolution_clock::now();
int searchInt = randSearchItem % size2;
while ((arr2[searchInt] != 0) && (arr2[searchInt] != randSearchItem))
{
if (searchInt == size2 - 1)
{
searchInt = 0;
cout << "if loop \n";
}
else
{
searchInt++;
cout << " stuck in else loop \n";
}
cout << " stuck in while loop end \n";
}
if (searchInt == 0) {
cout << "Search item not found using hashSearch" << endl;
} else {
cout << "Search item " << randSearchItem << " found using hashSearch at position " << searchInt << " in arr2." << endl;
}
auto finish = std::chrono::high_resolution_clock::now();
chrono::duration<double> elapsed = finish - start;
cout << "Elapsed time: " << elapsed.count() << " s\n";
}
Whereas it should just get out of the loop and output that search item is not found.
Search for cout << " stuck in else loop \n"; and cout << " stuck in while loop end \n";.
You want to stop your loop when you hit the end of the array: To that effect, you set the item to search for to zero:
if (searchInt == size2 - 1)
{
searchInt = 0;
cout << "if loop \n";
}
But in the loop control, you don't test that. You only test the array element at the current index for zero (not found) or the item to search (found):
while ((arr2[searchInt] != 0) && (arr2[searchInt] != randSearchItem)) ...
You need an additional test:
while ((searchInt != 0) && ...) ...
It took me a while to see that you want to code an open-address hastable where a zero marks unused slots. The hash value is just the number itself. Using zero as indicator for an empty slot is not ideal: You cannot store numbers whose hash code modulo the table size is zero.
I'd also code this with a non-void function where the return value is the index or some unambiguous value meaning "not found", perhaps -1. (Alternatively, you can return a pointer to the found item or NULL if the item isn't found -- after all, the index in the hash array is part of the hash table's internals and non concern to the caller.)
Then you can use early returns:
int hashSearch(const int *arr2, int size2, int item)
{
int i = item % size2;
for (; i < size2; i++) {
if (arr2[i] == -1) break; // -1 indicated unused space
if (arr2[i] == item) return i; // return index of item
}
return -1; // not found!
}
But what do you do if there is no room for a further element when you have a hash code close to the array size? You will need to add extra space at the end or you'll need to wrap around. Perhaps that is what you wanted to achieve by setting the index back to zero. In your case, ther array is full, so there are no zeros that could serve as loop-breaking criterion. You will have to find another criterion. You could ensure that there are zeros by making the hash table 30% or so bigger than the number of entries. Or you could try to detect whether the index has come full circle to the original index.
As already pointed out to you in comments: Try to use function arguments and local variables rather than puttin everything into global space. Also, the chaining of function calls, where the last thing in a function is to call the next one is strange. It's probably better to put all sequential calls into main.
I am an absolute C++ novice it seems so i need some help.
I am trying to make a programm which determines the least amount of coins needed to pay for something.
Example: You tell it you want to pay for 2,50 so it says you need a 2€ coin and 0.50€ coin (instead of something like: you need 5 * 0.50€ coins)
So my approach was to give it the price so then it will run a while loop for each coin testing whether the coin still fits the Value.
My Problem is that i cannot change my integers at all and im pretty sure its some really simple mistake i just cant figure out.
Code (Just the Function that calculates):
int Rechner() {
int Betrag;
int ZweiEuro = 0;
int EinEuro = 0;
int FuenfzigCent = 0;
int ZwanzigCent = 0;
int ZehnCent = 0;
int FuenfCent = 0;
int ZweiCent = 0;
int EinCent = 0;
cin >> Betrag;
cout << "Die kleinse Menga an Muenzen um ihren Betrag zu bezahlen ist:" << endl << endl << endl;
ZweiEuro + 2;
cout << "2.00 = " << ZweiEuro << endl;
cout << "1.00 = " << EinEuro << endl;
cout << "0.50 = " << FuenfzigCent << endl;
cout << "0.20 = " << ZwanzigCent << endl;
cout << "0.10 = " << ZehnCent << endl;
cout << "0.05 = " << FuenfCent << endl;
cout << "0.02 = " << ZweiCent << endl;
cout << "0.01 = " << EinCent << endl << endl << endl << endl << endl << endl;
cout << "[Enter] druecken um zu beenden.";
cin.sync();
cin.get();
return 0;
So this doesnt have any while loops because they dont work just like the ZweiEuro + 2 doesnt change anything.
The Result always stays 0 whether I add something or not.
Im pretty sure i can finish this programm easily if i get behind changing the god damn values of my Variables.
Thanks for help.
Thats not how its done. Both of these should work:
ZweiEuro = ZweiEuro + 2;
ZweiEuro += 2;
Thats the way if you want to increment it.
You could also just assign it the 2 as long as you dont want to loop it or anything
ZweiEuro = 2;
You have to store the integer. By writing ZweiEuro + 2; you don to change ZweiEuro value. You should write ZweiEuro = ZweiEuro + 2; or ZweiEuro += 2; instead, which means that ZweiEuro would be ZweiEuro value plus two. This is just the syntax of c++. You will get used to it soon.
So I need some help with this. I want to print out all integers between 2 and 2^20 that are integer powers of 2. I figured out that I need to increase the power by 1 each time but I can't seem to figure out what goes inside the inner for loop. I cannot use the pow() function
c = 2;
cout << "\nPROBLEM C" << endl;
for (int powerC = 1; powerC <= 20; powerC++) // powerC is exponent
{
cout << setw(5) << powerC << " ";
counterC++;
for (int x = 1; x <= 20; x++) // where I am having trouble with
{
c = (c*powerC);
cout << setw(5) << c;
} // end inner for loop
if (counterC % 8 == 0)
{
cout << endl;
}
}
cout << "\nNumber of numbers = " << counterC;
This is much simpler by using the << operator.
Since 2 is 2^1, you want to print all integers from 2^1 to 2^20 inclusively, or 20 numbers:
int c = 2;
for (int i=0; i<20; i++)
{
std::cout << c << std::endl;
c <<= 1;
}
I need the user input to be saved into my array and then output the array before the user inputs the next time. I have been moving things around different ways but cannot seem to get them to perform properly. I tried to cut down the code to the two functions I am having issues with.
void PlayGame()
{
const int HighestNum = 50;
const int LowestNum = 1;
int RandomNumber = LowestNum + rand() % HighestNum; //set for better random results
cout << "Guess the random number between " << LowestNum << " and " << HighestNum << "!\n\n";
const int attempts = 15;// limits the attempts to guess the random number to 15
int Guess [attempts] = {};
cout << "Enter your guess " << endl;
for (int count = 0; count < attempts; count++)
{
cin >> Guess[count];
int z = RandomNumber, y = Guess[count], r;
r = reviewGuess (z,y);//calling the function that determines the results
switch (r)//switch statement for function results, letting the user know if they matched the number, if the number is higher, or lower
{
case 0:
cout << "You Win!!" << endl;
cout << "\n";
cin.get();
return;
case 1:
cout << "The number is higher than your guess" << endl;
break;
case -1:
cout << "The number is lower than your guess" <<endl;
break;
}
if (count == 15)
{
cout << "Sorry, no guesses remain. The random number was... " << RandomNumber << "!";//so the user can see the random number at the end of their attempts
cout << "\n";
cin.get();
Again();
}
}
return;
}
int DisplayGuess(int member[])
{
for(int i = 0; i < 15; ++i)
cout << "\nGuess " << i + 1 << ": " << member[i];
cout << endl;
return;
}
Try this inside your loop
if(count > 0)
{
for (int j= 0; j < count; j++)
{
cout<<Guess[j];
}
}
Call DisplayGuess() in the first line of the for loop. Since the first you time you call it your array is empty, it shouldn't output anything.
So,
for (int count = 0; count < attempts; count++)
{
DisplayGuess(Guess[count]);
cin >> Guess[count];
int z = RandomNumber, y = Guess[count], r;
r = reviewGuess (z,y);//calling the function that determines the
results
. . . . . .
I am making a 20 questions game in C++ and have everything working, except for the displayWords function. The code I currently have keeps breaking. Any explanation would be appreciated! Thank you!
void displayWords()
{
int x = 0;
string words[50] = {"LCHS","Shark","Pencil","Pizza","New York","Fish","Car","Ice Cream","Los Angeles","Bird","Basketball","Fried Chicken",
"Dog","Tiger","Penguin","Plane","Rock","Barbecue Sauce","Mustard","Ketchup","Hot sauce","Peppers","Salt","Tacos","Shrimp","Pickels",
"Tomatos","Bannanas","Burger","Computer","Iphone","Motorcycle","Bicycle","Skateboard","Lightbulb","Golf Ball","Surfboard","Luggage",
"Rollercoaster","Cat","Lion","Cockroach","Grasshopper","Beach","Theme Park","Swimming Pool","Bowling Ally","Movie Theater","Golf Course","Shopping Mall"};
cout << "The following list of words are what the computer is capable of guessing" << endl;
cout << endl;
while(x < 50)
{
for (int y = 0; y <= 5; y++)
{
cout << words[x] << ", ";
if(x<50)
x++;
}
cout << endl;
}
}
I would like it to display the list of 50 words in an organized fashion.
By example, as:
for( int x = 0; x<sizeof(words)/sizeof(*words); x++ ) {
if( x%5==0 ) cout << endl; else cout << ", ";
cout << words[x];
}
take into account the problematic of the array's size calculation: see this link How do I find the length of an array?
If I understand correctly, you want your list displayed as 5 columns. Simplest way, use a nested for loop and proper formatting with std::setw (must #include <iomanip>):
for(size_t i = 0; i < 10; ++i)
{
for(size_t j = 0; j < 5; ++j)
{
std::cout << std::setw(20) << std::left << words[i * 5 + j];
}
std::cout << std::endl;
}
Your actual loop is incorrect, as it will lead to repetitions.
Maybe I'm not interpreting your question correctly but if you want to just print out the 50 words then you can use something like the code below. Not sure of the reason that the nested for loop iterating y was there.
Edit
void displayWords()
{
int x;
string words[50] = {"LCHS","Shark","Pencil","Pizza","New York","Fish","Car","Ice Cream","Los Angeles","Bird","Basketball","Fried Chicken",
"Dog","Tiger","Penguin","Plane","Rock","Barbecue Sauce","Mustard","Ketchup","Hot sauce","Peppers","Salt","Tacos","Shrimp","Pickels",
"Tomatos","Bannanas","Burger","Computer","Iphone","Motorcycle","Bicycle","Skateboard","Lightbulb","Golf Ball","Surfboard","Luggage",
"Rollercoaster","Cat","Lion","Cockroach","Grasshopper","Beach","Theme Park","Swimming Pool","Bowling Ally","Movie Theater","Golf Course","Shopping Mall"};
cout << "The following list of words are what the computer is capable of guessing" << endl;
cout << endl;
for(x = 0; x < words.size();x++)
{
cout << words[x]<< ", ";
}
}
Also some information on how the code is breaking, like are any errors being thrown or has debugging caused issues so far?