I'm really new to programming. I tried to make some sort of sorting application that sorts an array by swapping the values in the array. But when I try to build it, it just says build failed. Visual Studio doesn't give an error, so I'm kind of stuck. Could you help me out?
I've tried to increase the array size, and made sure there isn't any loop writing more integers to the array than is possible.
#include <iostream>
using namespace std;
int arr[10];
bool sorted = false;
int compare(int x, int y);
int cycle;
int compres;
int slot;
int main()
{
for (int c = 0; c < 5; c++)
{
cin >> arr[c];
}
while (cycle <= 5)
{
compres = compare(cycle, cycle + 1);
if (compres == 1)
{
slot = arr[cycle];
arr[cycle] = arr[cycle + 1];
arr[cycle + 1] = slot;
cout << arr[cycle] << " and " << arr[cycle + 1] << "swapped" << endl;
}
else if (compres == 0)
{
cout << arr[cycle] << " is equal to " << arr[cycle + 1] << endl;
}
else if (compres == -1)
{
cout << arr[cycle] << " and " << arr[cycle + 1] << "are already sorted" << endl;
}
else
{
cout << "(!) Compare issue." << endl;
}
cycle++;
}
for (int i = 0; i < 5; i++)
{
cout << arr[i];
}
}
int compare(int x, int y)
{
if (x > y) { return 1; }
if (x == y) { return 0; }
if (x < y) { return -1; }
}
Output log:
https://i.stack.imgur.com/6mw5d.png
I think something went wrong while creating the project...
I made a new one and copy-pasted the code, it worked.
Thanks for your answers!
Related
I am working on a project for school that tests Binary Search vs. Linear Search. My LinearSearch method seems to work fine when the array is in either increasing order or reversed. However, the BinarySearch only works when the array is in increasing order, but fails to work when the array is reversed. I am not sure what is causing this and would appreciate any suggestions/solutions.
Here is my code
/*
* SearchTest.cpp
*
* Created on: Oct 16, 2022
* Author: JH
*/
#include <iostream>
#include <time.h>
using namespace std;
//BinarySearch method
int BinarySearch(int numbers[], int numbersSize, int key) {
int mid;
int low;
int high;
low = 0;
high = numbersSize - 1;
while (high >= low) {
mid = (high + low) / 2;
if (numbers[mid] < key) {
low = mid + 1;
}
else if (numbers[mid] > key) {
high = mid - 1;
}
else {
return mid;
}
}
return -1; // not found
}
//LinearSearch method
int LinearSearch(int* array, int arraySize, int key) {
for (int i = 0; i < arraySize; i++) {
if (array[i] == key) {
return i;
}
}
return -1; // not found
}
//method to reverse array elements
void reverseArray(int arr[], int start, int end)
{
while (start < end)
{
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
int main() {
//declare array
int reverseArr[1000];
int size = sizeof(reverseArr)/sizeof(reverseArr[0]);
//initialize array
for (int i = 0; i < size; i++) {
reverseArr[i] = i;
}
//reverse array
reverseArray(reverseArr, 0, size-1);
//print array
for (int i = 0; i < size; i++) {
cout << reverseArr[i] << " ";
}
cout << endl;
cout << endl;
//generate random number
srand(time(NULL));
int randomNum = rand() % 1000;
//print statements
cout << "[Linear vs. Binary Search]" << endl;
cout << "The target value is " << reverseArr[randomNum] << endl;
cout << endl;
//call BinarySearch method for array
cout << "Binary Search Test: " << endl;
int key1 = reverseArr[randomNum];
int keyIndex1 = BinarySearch(reverseArr, size, key1);
if (keyIndex1 == -1) {
cout << key1 << " was not found." << endl;
}
else {
cout << "Found " << key1 << " at index " << keyIndex1 << "." << endl;
}
cout << endl;
//call LinearSearch method for array
cout << "Linear Search Test: " << endl;
int key2 = reverseArr[randomNum];
int keyIndex2 = LinearSearch(reverseArr, size, key2);
if (keyIndex2 == -1) {
cout << key2 << " was not found." << endl;
}
else {
cout << "Found " << key2 << " at index ";
cout << keyIndex2 << "." << endl;
}
}
I am new to programming so please help me completing the task
the problem is:
After pressing y the while loop does not run again.
and secondly, how to print or get the array elements in descending order?
thank you!
#include <iostream>
using namespace std;
int main()
{
int item;
int flaging = 0;
int ind_low = 0;
int ind_high = 9;
int ind_mid = (ind_low + ind_high) / 2;
char conti;
//Array declaration and taking user input
int arr[10];
cout << "enter some values here : \n" << endl;
for (int i = 0; i < 10; i++)
{
cin >> arr[i];
}
// for sorthing the array
int temp;
for (int p = 1; p <= 9; p++)
for (int c = 0; c <= 8; c++)
if (arr[c] > arr[c + 1])
{
temp = arr[c];
arr[c] = arr[c + 1];
arr[c + 1] = temp;
}
do {
//asking for searching
cout << "Enter the value you want to search : " << endl;
cin >> item;
while (ind_low <= ind_high)
{
if (item == arr[ind_mid])
{
cout << "At " << ind_mid << " index the value " << item << " is found " << endl;
flaging++;
break;
}
if (item < arr[ind_mid])
{
ind_high = ind_mid - 1;
ind_mid = (ind_low + ind_high) / 2;
}
else
{
ind_low = ind_mid + 1;
ind_mid = (ind_low + ind_high) / 2;
}
}
if (flaging == 0)
{
cout << "Value not found" << endl;
}
cout << "To search again press 'y', to exit press any key" << endl;
cin >> conti;
} while ((conti == 'y') || (conti == 'Y'));
}
when I ran it on my pc after pressing y it did run again, can you provide the input that failed you?
for the second question what do you mean?
you can do a for loop that goes like this:
for(int index = ARR_SIZE -1 ; index >= 0 ; --index){
cout << array[index];
}
edit: I understand what you mean. after each run you should reset your indexes otherwise you will always run on the same once:
before you end the loop the values should be reseted.
ind_low = 0;
ind_high = 9;
ind_mid = (ind_low + ind_high) / 2;
that gonna print the array from end to start.
I have to write out a list of prime numbers from 1-100, using a function we have previously wrote, to a file. The commented out part isn't anything related; it's just the previous code we used for the function. I don't know exactly what's going on because the file isn't even being created, and the part inside the for loop is executing with just 2's, 100 times.
#include <iostream>
#include <fstream>
using namespace std;
bool isPrime(int);
int main () {
ofstream outputFile;
int p = 2;
cout << "I will be giving you the first 100 prime numbers " << endl;
cout << "And giving you a file containing those numbers." << endl;
outputFile.open("PrimeNumbers100.txt");
for (int i = 2; i <= 100; i++)
{
isPrime(p);
cout << p << endl;
outputFile << p << endl;
}
outputFile.close();
cout << "You should now have the file." << endl;
/* int n;
int counter = 0;
int p = 2;
cout << "Welcome to prime counter. " << endl;
cout << "Which prime number would you like? ";
cin >> n;
while (counter < n) {
if (isPrime(p)) {
counter++;
}
p++;
}
p = p - 1;
cout << "Prime number " << n << " is " << p << "." << endl;
*/
return 0;
}
bool isPrime(int p) {
bool result = true;
if (p < 2) {
result = false;
}
else {
int stop = (int) (sqrt(p + .5));
for (int d = 2; d <= stop; d++) {
if (p % d == 0) {
result = false;
break;
}
}
}
return result;
}
Could someone please explain what I'm doing wrong here, and why it isn't even creating the file?
You initialize p at the top with 2. You should be calling isPrime with i instead.
You're getting 2s because you're printing out and storing p, but the loop is going over i.
Here is the updated code. Upon research I did find where it was saving the files, and there are instances of it just not working at all. However, This code runs and does give me everything I need it to.. Thank you for the tips, and I appreciate the very.... constructive feedback.
#include <iostream>
#include <fstream>
using namespace std;
bool isPrime(int);
int main () {
ofstream outputFile;
cout << "I will be giving you the first 100 prime numbers " << endl;
cout << "And giving you a file containing those numbers." << endl;
outputFile.open("PrimeNumbers100.txt");
for (int i = 2; i <= 100; i++)
{
if (isPrime(i)) {
outputFile << i << endl;
}
}
outputFile.close();
cout << "You should now have the file." << endl;
return 0;
}
bool isPrime(int p) {
bool result = true;
if (p < 2) {
result = false;
}
else {
int stop = (int) (sqrt(p + .5));
for (int d = 2; d <= stop; d++) {
if (p % d == 0) {
result = false;
break;
}
}
}
return result;
}
I'm implementing a binary search and the code is below, however, it doesn't print out the right answer buy it prints out correct answer inside the function body, so it makes me really confused.
#include <iostream>
using namespace std;
int research(int a[], int target, int lowIndex, int highIndex)
{
int finalIndex;
cout << lowIndex << " " << highIndex << endl;
int midIndex = (lowIndex + highIndex) / 2;
if (a[midIndex] == target)
{
finalIndex = midIndex;
cout << "The final index is: " << finalIndex << endl;
}
else
{
if (a[midIndex] < target)
{
research(a, target, midIndex + 1, highIndex);
}
else
{
research(a, target, lowIndex, midIndex - 1);
}
}
return finalIndex;
}
int main()
{
int* array = new int[1000];
for (int i = 0; i < 1000; i++)
{
array[i] = i + 1;
}
cout << research(array, 234, 0, 999) << endl;
return 0;
}
The line:
cout << "The final index is: " << finalIndex << endl;
prints out the right final index but the line
cout << research(array, 234, 0, 999) << endl;
doesn't, instead it prints out random number. Anyone know what is going wrong here? Thank you!
The only time you actually set finalIndex to anything is when a[midIndex] == target, so when you recurse you're returning the value of an uninitialised variable.
(The finalIndex variable isn't shared between function invocations - each invocation uses its own variable.)
You need to use the return value from the recursive calls:
if (a[midIndex] < target)
{
finalIndex = research(a, target, midIndex + 1, highIndex);
}
else
{
finalIndex = research(a, target, lowIndex, midIndex - 1);
}
I am writing a program that generates any size maze you want. It does this by first creating every cell in the maze and assuming they are entirely walled in. They are each declared as their own set. Then a random cell is selected and then a random direction to break down a wall. The random direction funcion makes sure that its also a valid direction for that cell. The program makes sure that the two cells its looking to join arent already connected somehow and if they arent it breaks the wall. If they are already connected either directly or indirectly then it selects a new random cell and direction. This continues until the number of sets left is just 1 ensuring that you can get from any point in the maze to any other point. The program works but it is painfully slow. I dont think it should be as slow as it is and I am unsure why.
I can imagine a scenario where all the cells are connected but one. Thus it would take a little while to randomly select that one cell and that could slow things down but I would imagine when you are dealing with under 100,000 cells it still shouldn't take as long as it does. Rand should be prettu fast at spitting out numbers.
Ive attatched my code below. Its fairly simple but I am sorry about the lack of notes.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
class dset {
struct element {
element() { rank=0, parent=-1; }
int rank;
int parent;
vector<int> connections;
};
public:
dset(int nr=0,int nc=0);
int size() {return Nsets; }
int merge (int, int);
int find(int);
// Functions
bool isin(int i, vector<int> test);
int randdir(int i);
int randcell();
int dir(int, int);
void print();
vector<int> possibledir(int cell);
vector<int> walls(int cell, vector<int> possible);
private:
int Nsets;
int nrows, ncols;
vector<element> S;
};
int main(int argc, char* argv[]){
int nrows, ncols, cell, direction;
if (argc != 3){
cout << "Usage: nrows ncols\n";
}
stringstream convert;
convert << argv[1];
convert << " ";
convert << argv[2];
convert >> ncols;
convert >> nrows;
dset maze(nrows,ncols);
srand(time(NULL));
while(maze.size() != 1){
cell = maze.randcell();
// cell = 11;
direction = maze.randdir(cell);
// direction = 0;
// cout << "cell: " << cell << " direction: " << direction << " new cell: " << maze.dir(cell, direction) <<endl << endl;
// cout << maze.size() << endl<<endl;;
maze.merge(cell, maze.dir(cell, direction));
}
maze.print();
}
dset::dset(int nr,int nc) {
nrows = nr;
ncols = nc;
int N = (nrows * ncols);
if (0<N) S.insert(S.end(), N, element());
Nsets = N;
}
void dset::print(){
vector<int> wall;
cout << "MAZE " << nrows << " " << ncols << endl;
for ( int i = 0; i < (nrows*ncols); i++ ){
wall = walls(i,possibledir(i));
for( int j = 0; j < wall.size(); j++){
if (i < wall[j])
cout << i << " " << wall[j] << endl;
}
}
}
int dset::randcell(){
return (rand()%(nrows*ncols));
}
int dset::dir(int cell, int direction){
if(direction == 0)
return (cell - 1);
if(direction == 1)
return (cell - (ncols));
if(direction == 2)
return (cell+1);
if(direction == 3)
return (cell + ncols);
}
int dset::randdir(int i){
srand(time(NULL));
int direction;
vector<int> used;
//cout << "i : " << i << endl;
while (true){
direction = rand() % 4;
while (true){
if(isin(direction,used))
direction = rand()%4;
else
break;
}
// cout << "rand: " << direction << endl;
if(direction ==0){
if( i != 0){
// cout << 0 << " i%(ncols -1) :" << (i%(ncols -1)) << endl;
if(i%(ncols) != 0){
break;
}
}
}
if(direction == 1){
// cout << 1 << " i - ncols :" << (i-ncols) << endl;
if(i-ncols > 0){
break;
}
}
if (direction == 2){
// cout << 2 << " i%(ncols) :" << (i%ncols) << endl;
if ( i == 0 )
break;
if (i%ncols != ncols-1){
break;
}
}
if (direction == 3){
if (i+ncols < ((nrows*ncols))){
// cout << 3 << " i+ncols :" << (i+ncols) << endl;
break;
}
}
used.push_back(direction);
}
return direction;
}
vector<int> dset::possibledir(int cell){
vector<int> possible;
// cout << "cell " << cell << " possible connections:\n";
for (int i = 0; i < 4; i++){
if (i == 0){
if( cell != 0 ){
if(cell%(ncols) !=0){
// cout << dir(cell,i) <<endl;
possible.push_back(dir(cell,i));
}
}
}
if(i==1){
if (cell-ncols > 0){
// cout<<dir(cell,i) <<endl;
possible.push_back(dir(cell,i));
}
}
if(i==2){
if(cell == 0){
// cout<<dir(cell,i) <<endl;
possible.push_back(1);
}else if(cell%ncols != ncols-1){
// cout<<dir(cell,i) <<endl;
possible.push_back(dir(cell,i));
}
}
if(i==3){
if ( cell+ncols < ((nrows*ncols))){
// cout<<dir(cell,i) <<endl;
possible.push_back(dir(cell,i));
}
}
}
// cout << endl;
return possible;
}
vector<int> dset::walls(int cell, vector<int> possible){
vector<int> walls;
// cout << cell << " connection 0: " << S[cell].connections[0] << endl;
for(int i = 0; i < possible.size(); i++){
if (!isin(possible[i], S[cell].connections)){
// cout << "true\n";
walls.push_back(possible[i]);
}
// cout << "false\n";
}
return walls;
}
int dset::merge(int i, int j) {
int cell1 = i;
int cell2 = j;
i = find(i);
j = find(j);
if (i != j) {
element &Si = S[i];
element &Sj = S[j];
// Adjust Adjacency List
// cout << "inconnections\n";
S[cell1].connections.push_back(cell2);
S[cell2].connections.push_back(cell1);
// cout << "notinconnections\n";
// merge (union) by rank
if (Si.rank > Sj.rank) Sj.parent = i;
else if (Si.rank < Sj.rank) Si.parent = j;
else { Sj.parent = i; Si.rank +=1; }
Nsets -=1;
}
return find(i);
}
int dset::find(int i) {
if (S[i].parent == -1){
return i;
}
// recursive path compression
S[i].parent = find(S[i].parent);
return S[i].parent;
}
bool dset::isin(int i, vector<int> test){
bool out = false;
for(int j = 0; j < test.size(); j++){
if(test[j] == i)
out = true;
}
return out;
}
Please learn to pass by reference, not value.
For example:
bool dset::isin(int i, vector<int> test)
You are passing a vector by value. That means that an entire copy is made when the function is called. If your vector has 100,000 items, then an unnecessary copy is made. Change to this:
bool dset::isin(int i, vector<int>& test)
Now no copy is done. Make this same change in all of your other functions.
You also return a vector by value, but I would leave those alone unless it is proven that your compiler can't or won't optimize the copy away.
Also, make sure you are timing a release, optimized program, and not a "debug" or unoptimized program. Since you didn't mention the compiler you're using, use the settings that generate optimized code when building your program.
Although I do not know much about c++, it would seem to me from your program description at the start that your slowdown may happen when your program is determining whether two prospectively connectable cells are already connected. Since the majority if not all cases when this is done that are used must determine that the cells are NOT connected, so that there is only one proper solution, every time this is done your program has to examine/solve the entire maze to that point to make sure that there is no way in which it could already be connected. This means that as the existing part of the maze gets larger, the time it takes to complete this task will get longer and longer.
To test whether this is the case, you could have your program record how long it takes to determine if two cells are connected every time ( or 10 times) it does so, and if the times on the list get longer linearly, then this or something similar is part of the issue.
You could fix this by either allowing already-connected to be connected by another path, or by simplifying the way in which your program checks what cells are connected.
Sorry I can't give better code-specific advice, but I'm researching how to create a maze and ran across your question, hopefully my answer at least is food for thought.