C++ recursive backtracking - c++

I am trying to do recursive backtracking to find a path from point 0 to point 8. I have defined the paths but its goes 0 1 2 and them stops. Can anyone help?
#include <iostream>
#include <vector>
using namespace std;
vector< vector<int> > roads;
void find_path(int Point = 0) {
cout << Point;
int rds = roads.size();
for(int i = 0; i < rds; i++) {
find_path(roads[Point][i]);
}
}
main() {
roads.resize(8);
//VNESUVANJE PATISTA
roads[0].push_back(1);
roads[0].push_back(3);
roads[1].push_back(2);
roads[3].push_back(4);
roads[3].push_back(6);
roads[4].push_back(5);
roads[4].push_back(7);
roads[7].push_back(8);
find_path();
return 0;
}

I did some changes i think now it works properly.
#include <iostream>
#include <vector>
using namespace std;
vector< vector<int> > roads;
int path_finded = 0; //Added new variable to know if path is finded.
void find_path(int Point = 0) {
if(Point == 8) { //Checks if the point where we are is 8 and if it is stops the whole thing and chages path_finded to 1
path_finded = 1;
return;
}
int rds = roads[Point].size();//changed roads.size to roads[Point].size so it gives the size of the possible roads from the point where we are.
for(int i = 0; i < rds; i++) {
find_path(roads[Point][i]);
}
return;
}
main() {
roads.resize(8);
//VNESUVANJE PATISTA
roads[0].push_back(1);
roads[0].push_back(3);
roads[1].push_back(2);
roads[3].push_back(4);
roads[3].push_back(6);
roads[4].push_back(5);
roads[4].push_back(7);
roads[7].push_back(8);
find_path();
if(path_finded == 1) cout << "RABOTI"; //prints if it works.
return 0;
}

Related

Struct doesn't print with cout

I'm trying to print the structure in an array whose int prejetih member is highest.
#include <iostream>
using namespace std;
struct Tekma {
int prejetih;
};
Tekma najvec_kosev(Tekma tekme[]) {
int maksi = 0, index = 0;
for (int i = 0;i < 2;i++) {
if (maksi < tekme[i].prejetih) {
index = i;
maksi = tekme[i].prejetih;
}
}
return tekme[index];
}
void vpis(Tekma tekme[]) {
for (int i = 0;i < 2;i++)
cin >> tekme[i].prejetih;
}
int main() {
Tekma tekme[2];
vpis(tekme);
cout << najvec_kosev(tekme);
}
The compiler reports
C++ no operator matches these operands
operand types are: std::ostream << Tekma
over cout << najvec_kosev(tekme);
Here using a solution with std::vector and fixing your cout problem:
#include <iostream>
#include <vector>
using namespace std;
struct Tekma {
int prejetih;
};
Tekma najvec_kosev(vector<Tekma>& tekme) {
Tekma lowest = tekme[0]
for(auto& t : tekme) {
if(lowest.prejetih < t.prejetih) {
lowest = t;
}
}
return lowest ;
}
void vpis(vector<Tekma>& tekme) {
int input;
while(true) {
cin >> input;
// Check if the input is valid else quit the loop.
if(input == valid) {
Tekma newStruct = {input};
tekme.push(newStruct);
}
else {
// Stop the loop
break;
}
}
}
int main() {
vector<Tekma> tekme;
vpis(tekme);
cout << najvec_kosev(tekme).prejetih; // This fixes your error.
}

Using array from private access specifier

Here I have an array within the private section of my class which is unable to retain the values set in different members of the clas; during the fight sequence both of the values in the array equate to 0.
#include <iostream>
#include <string>
#include<math.h>
#include<cstdlib>
using namespace std;
class champions {
private:
int health_array[2] = { };
int attack_array[2] = { };
public:
void health_attack_set() {
int health_set{};
int attack_set{};
for (int i = 0; i < 2; i++) {
health_array[i] = health_set;
attack_array[i] = attack_set;
}
}
void fight_sequence(int random_champion, int random_opponent) {
cout << "FIGHT\n\n";
while (health_array[random_champion] > 0 or health_array[random_opponent] > 0) {
(health_array[random_opponent] -= attack_array[random_champion]);
if (health_array[random_opponent] <= 0) {
break;
}
(health_array[random_champion] -= attack_array[random_opponent]);
}
if (health_array[random_champion] > 0) {
cout << "CHAMPION 1 WINS!!!";
}
if (health_array[random_opponent] > 0) {
cout << "CHAMPION 2 WINS!!!";
}
if (health_array[random_champion] == 0 && health_array[random_opponent] == 0) {
cout << "NO ONE WINS!!";
}
}
void champion_1() {
health_attack_set();
health_array[0] = 400;
attack_array[0] = 150;
}
void champion_2() {
health_attack_set();
health_array[1] = 500;
attack_array[1] = 100;
}
};
int main() {
champions fight;
fight.fight_sequence(0, 1);
return 0;
}
I believe it may be a simple mistake but hard to spot; thank you for any help that is given.
I think your problems are coming from not understanding how to structure your code in the presence of classes and multiple objects. I have restructured your code below in a cleaner and more common way (it is not the only way to do it, but it is more typical). Hopefully there are not typos.
#include <iostream>
#include <string>
#include<math.h>
#include<cstdlib>
using namespace std;
class Champion{
public:
int health;
int attack;
Champion(int health_, int attack_) : health(health_), attack(attack_) {
}
};
void fight_sequence(Champion& champion, Champion& opponent) {
cout << "FIGHT\n\n";
while (champion.health > 0 || opponent.health > 0) {
(opponent.health -= champion.attack);
if (opponent.health <= 0) {
break;
}
(champion.health -= opponent.attack);
}
if (champion.health > 0) {
cout << "CHAMPION 1 WINS!!!";
}
if (opponent.health > 0) {
cout << "CHAMPION 2 WINS!!!";
}
if (champion.health == 0 && opponent.health == 0) {
cout << "NO ONE WINS!!";
}
}
int main() {
Champion champion_1(400, 150);
Champion champion_2(500, 100);
fight_sequence(champion_1, champion_2);
return 0;
}

Search Using 2 threads

'Is the threading correct in this code ?
I am searching a specific key in an array using 2 threads, one thread searches in first half of the array and second thread in second half of the array.'
I have created a struct named as Parameters which I fill with my parameters and pass it to the thread.
I made two Parameters objects to pass to two different threads.
Both have same array and same key, but starting point and ending point are different for both parameters because one thread has to search in first half and the other one has to search in second half.
starting point and ending point are set accordingly.
#include <pthread.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdlib.h>
#include <iostream>
using namespace std;
#define len 5
struct Parameters{
int start;
int end;
int*arr;
int key;
};
void* search(void* param)
{
Parameters *pm = (Parameters*) param;
int s = pm->start;
int e = pm->end;
int *A = pm->arr;
int k = pm->key;
bool flag = false;
for(int i= s; i<e ;i++){
if(A[i] == k){
flag = true;
}
}
pthread_exit( (void*) flag);
}
int main(int argc,char* args[])
{
pthread_t id[2];
int A[len] ;
cout<<"Enter "<<len<<" elements \n";
for(int i=0;i<len;i++){
cin>>A[i];
}
Parameters p;
p.arr = A;
p.start = 0;
p.end = len/2;
p.key = 7;
pthread_create(&id[0],NULL,&search,&p);
Parameters p2;
p2.arr = A;
p2.start = len/2;
p2.end = len;
p2.key = 7;
pthread_create(&id[1],NULL,&search,&p2);
bool *found = new bool(false);
for(int i=0;i<2;i++){
pthread_join(id[i], (void**)found);
}
if(*found==true){
cout<<"Found\n";
}
else{
cout<<"Not found\n";
}
return 0;
}

C++ Creating Lottery Guessing Program

Okay so the project is to create a lottery number composed of 10 random positive integers and the user is suppose to guess it until the user guesses the correct number. All of my code looks good but when I run the program and enter in a number it gives me this MSVS Runtime Library error? I dont even know what it means as I am fairly new to programming. Help would be very appreciated!
Main.cpp
#include <iostream>
#include <cmath>
#include <ctime>
#include "Lottery.h"
using namespace std;
int main() {
const int size = 9; //declare variables
int win[size];
int g;
srand(time(NULL));
assign(win, size);
draw(win, size);
g = entry();
if (check(win,size,g) == true) {
cout << "Congradulations! You have won the lottery!" << endl;
}
else {
cout << "Try again!" << endl;
}
printOut(g);
}
Lottery.cpp
#include <iostream>
#include <cmath>
#include "Lottery.h"
using namespace std;
int entry() {
int guess;
cout << "Enter a number from 0 to 99." << endl;
cin >> guess;
return guess;
}
void assign(int w[], int s) {
for (int i = 0; i < s; i++) {
w[s] = -1;
}
}
bool check(int w[], int s, int g) {
for (int i = 0; i < s; i++) {
if (g == w[i]) {
return true;
}
}
return false;
}
void draw(int w[], int s) {
for (int i = 0; i < s; i++) {
int tmp = rand() % 100;
if (check(w, s, tmp)) {
i--;
}
else
w[i] = tmp;
}
}
void printOut(int g) {
cout << "Numbers you have chosen:" << " " << g << endl;
}
Lottery.h
#ifndef LOTTERY_INCLUDED
#define LOTTERY_INCLUDED
void assign(int[], int);
bool check(int[], int, int);
void draw(int[], int);
int entry();
void printOut(int);
#endif //LOTTERY
Debugging tutorials are available elsewhere. But if something bad happens, don't panic and look for instructions.
First, your runtime error:
This has a link "Break and open exception settings" link or a "Break" button. Break which will take you to the end of main if you click it.
The details say we did something bad near win.
Look at this:
void assign(int w[], int s) {
for (int i = 0; i < s; i++) {
w[s] = -1; //<------Oh oops!
}
}
We know the length of the array is s i.e. 9, and are using w[s] where we clearly meant w[i].
The extra details in the error are telling you a possible place to look.

How to alphabetically sort strings?

I have been trying to use this c++ program to sort 5 names alphabetically:
#include <iostream>
#include <cstring>
#include <conio.h>
using namespace std;
int main()
{
char names[5][100];
int x,y,z;
char exchange[100];
cout << "Enter five names...\n";
for(x=1;x<=5;x++)
{
cout << x << ". ";
cin >> names[x-1];
}
getch();
for(x=0;x<=5-2;x++)
{
for(y=0;y<=5-2;y++)
{
for(z=0;z<=99;z++)
{
if(int(names[y][z])>int(names[y+1][z]))
{
strcpy(exchange,names[y]);
strcpy(names[y],names[y+1]);
strcpy(names[y+1],exchange);
break;
}
}
}
}
for(x=0;x<=5-1;x++)
cout << names[x];
return 0;
}
If I enter Earl, Don, Chris, Bill, and Andy respectively, I get this:
AndyEarlDonChrisBill
Could someone please tell me whats wrong with my program?
You could use std::set or std::multiset (if you will allow repeated items) of strings, and it will keep the items sorted automatically (you could even change the sorting criteria if you want).
#include <iostream>
#include <set>
#include <algorithm>
void print(const std::string& item)
{
std::cout << item << std::endl;
}
int main()
{
std::set<std::string> sortedItems;
for(int i = 1; i <= 5; ++i)
{
std::string name;
std::cout << i << ". ";
std::cin >> name;
sortedItems.insert(name);
}
std::for_each(sortedItems.begin(), sortedItems.end(), &print);
return 0;
}
input:
Gerardo
Carlos
Kamilo
Angel
Bosco
output:
Angel
Bosco
Carlos
Gerardo
Kamilo
You can use the sort function:
#include <algorithm>
#include <vector>
using namespace std;
...
vector<string> s;
sort(s.begin(),s.end());
You are using too much unnecessary loops. Try this simple and efficient one. You need to just swap when a string is alphabetically latter than other string.
Input
5
Ashadullah
Shawon
Shakib
Aaaakash
Ideone
Output
Aaaakash
Ashadullah
Ideone
Shakib
Shawon
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s[200],x[200],ct,dt;
int i,j,n;
cin>>n;
for(i=0;i<n;i++)
{
cin>>s[i];
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(s[i]>s[j])
{
ct=s[i];
s[i]=s[j];
s[j]=ct;
}
}
}
cout<<"Sorted Name in Dictionary Order"<<endl;
for(i=0;i<n;i++)
{
cout<<s[i]<<endl;
}
return 0;
}
Your code implements a single-pass of bubble sort. Essentially missing the 'repeat until no changes are made to the array' loop around the outside.
The code does not take care when the names are already in order. Add the following
else if(int(names[y][z])<int(names[y+1][z]))
break;
To the if statement.
Putting this here in case someone needs a different solution.
/* sorting example */
#include <iostream>
using namespace std;
bool isSwap( string str1, string str2, int i)
{
if(str1[i] > str2[i])
return true;
if(str1[i] == str2[i])
return isSwap(str1,str2,i+1);
return false;
}
int main()
{
string str[7] = {"you","your","must","mike", "jack", "jesus","god"};
int strlen = 7;
string temp;
int i = 0;
int j = 0;
bool changed = false;
while(i < strlen-1)
{
changed = false;
j = i+1;
while(j < strlen)
{
if(isSwap(str[i],str[j],0))
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
changed = true;
}
j++;
}
if(changed)
i = 0;
else
i++;
}
for(i = 0; i < strlen; i++)
cout << str[i] << endl;
return 0;
}