C++ keeps skipping my "for" loop [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm trying to create a program that will find a four-digit number that meets four specific requirements: all four digits are different, the thousands number is 3x the tens number, the number is odd, and the sum of the digits is 27. For some reason, despite the program compiling, the for loop won't run and always outputs the initializer number (1000). My main code and the four functions I'm calling are below. I can't figure out why it won't run correctly. I'm completely new to coding so any tips/help are appreciated. Thanks!
main function:
5 //prototypes
6 bool differentDigits(int);
7 bool thouThreeTen(int);
8 bool numberIsOdd(int);
9 bool sumIs27(int);
10
11 #include <iostream>
12 using namespace std;
13
14 int main ()
15 {
16 //variables
17 int n;
18
19 //processing
20
21 for(n=1000;n<=9999;n++)
22 {
23 if(differentDigits(n)==true)
24 {
25 break;
26 }
27
28 if(thouThreeTen(n)==true)
29 {
30 break;
31 }
32
33 if(numberIsOdd(n)==true)
34 {
35 break;
36 }
37
38 if(sumIs27(n)==true)
39 {
40 break;
41 }
42
43 }
44
45 //output
46 cout << n << endl;
47
48 return 0;
49 }
differentDigits function:
3 //Verify all four digits are the same
4
5 #include <iostream>
6 using namespace std;
7
8 bool differentDigits (int n)
9 {
10 int n1, n2, n3, n4;
11
12 n1 = n/1000;
13 n2 = (n/100) % 10;
14 n3 = (n/10) % 10;
15 n4 = n % 10;
16
17 if(n1 != n2 != n3 != n4)
18 {
19 return true;
20 }
21 else
22 {
23 return false;
24 }
25
26 }
thouThreeTen function:
3 //Verify digit in thousands place is 3x the digit in tens place
4
5 #include <iostream>
6 using namespace std;
7
8 bool thouThreeTen(int n)
9 {
10 int n1, n2, n3, n4;
11
12 n1 = n/1000;
13 n2 = (n/100) % 10;
14 n3 = (n/10) % 10;
15 n4 = n % 10;
16
17 if(n1 = (n3 * 3))
18 {
19 return true;
20 }
21 else
22 {
23 return false;
24 }
25
26 }
numberIsOdd function:
3 //Verify that the number is odd
4
5 #include <iostream>
6 using namespace std;
7
8 bool numberIsOdd (int n)
9 {
10 if((n % 2)==1)
11 {
12 return true;
13 }
14 else
15 {
16 return false;
17 }
18
19 }
sumIs27 function:
3 //Verify that the sum of digits is 27
4
5 #include <iostream>
6 using namespace std;
7
8 bool sumIs27(int n)
9 {
10 int n1, n2, n3, n4;
11
12 n1 = n/1000;
13 n2 = (n/100) % 10;
14 n3 = (n/10) % 10;
15 n4 = n % 10;
16
17 if((n1+n2+n3+n4)==27)
18 {
19 return true;
20 }
21 else
22 {
23 return false;
24 }
25
26 }

You have several problems with your code, the first being in main(). If any of the functions return true, you will end the loop. This is probably why you see the for loop as not being executed. Another problem is that in your functions, you are using conditions such as if(n1 = (n3 * 3)) which use the assignment operator instead of checking if they are the same.You want to use if(n1 == (n3 * 3)). Your main should look something like:
int main()
{
int n = 0;
for(n = 1000; n < 9999; ++n)
{
if(differentDigits(n) && thouThreeTen(n) && numberIsOdd(n) && sumIs27(n))
{
break;
}
}
cout << n << endl;
}
In each of your functions, make sure that you are using == not = when you are checking if something is a value.

Related

how to build a two three series program in C++

i have this CS question that says:
We will define a series two three to be a series whose first term is some natural number. If the value of the member number n in the series is x, then the value of the (n +1)th member in the series is: (x % 2 ==0) ? x/2 : x*3 +1.
You must write a program that prints two or three series starting with the numbers 1 to twenty-five (not inclusive), but the creation of each series will stop when a value greater than a thousand or a value that has already appeared in a previous series is produced (and therefore the sub-series that was produced from this array onwards has already been produced). The value that is produced must be displayed again, thus stopping the production of the series.
now the code i have written outputs a similar result to the solution output but it needs some changes in order to get the same exact result which i couldn't figure out, this is my code.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
int array[25];
for (int i = 1; i < 25; i++)
{
int currentNum = i;
int theNumAfter;
bool occured = false;
while (occured == false)
{
for (int i = 0; i <= 25; i++)
{
if (array[i] == currentNum)
{
occured = true;
cout << endl;
}
}
array[currentNum] = currentNum;
cout << currentNum << " ";
if (currentNum % 2 == 0)
{
theNumAfter = currentNum / 2;
}
else
{
theNumAfter = (3 * currentNum) + 1;
}
array[theNumAfter] = theNumAfter;
cout << theNumAfter << " ";
currentNum = theNumAfter;
}
}
}
the code doesn't take any input and there is only one right output which should be this:
1 4 2 1
2
3 10 5 16 8 4
4
5
6 3
7 22 11 34 17 52 26 13 40 20 10
8
9 28 14 7
10
11
12 6
13
14
15 46 23 70 35 106 53 160 80 40
16
17
18 9
19 58 29 88 44 22
20
21 64 32 16
22
23
24 12
the result of my code:
1 4
4 2
2 1 3 10
10 5
4 2
5 16 6 3
3 10 7 22
22 11 8 4
4 2 9 28 28 14
14 7
10 5
11 34 12 6
6 3 13 40 40 20
20 10
14 7 15 46 46 23
23 70
16 8 17 52 52 26 26 13
13 40 18 9
9 28 19 58 58 29 29 88 88 44 44 22
22 11
what should i change in the code, so we have matching outputs. thanks in advance
the creation of each series will stop when a value greater than a thousand or a value that has already appeared in a previous series is produced.
Up to 24, none of the produced values is greater than a thousand, but the posted code still has an access out of bounds bug:
int main()
{
int array[25];
// ^^
for (int i = 1; i < 25; i++)
{
int currentNum = i;
int theNumAfter;
// ...
array[currentNum] = currentNum;
// ...
array[theNumAfter] = theNumAfter;
// ...
}
// ...
}
Note the many of numbers in the expected output are greater than 25.
I'm not sure what this part was supposed to achive:
for (int i = 0; i <= 25; i++)
{ // ^^^^^^^ it "checks" only the first 25 values that may occur
if (array[i] == currentNum)
{
occured = true;
cout << endl; // <-- The duplicate should be printed before the newline.
// Here it should break out of the loop.
}
}
array[currentNum] = currentNum;
cout << currentNum << " ";
But it fails to produce the expected output.
I'd use a simple array of 1000 bools to memorize the already occurred numbers.
#include <iostream>
int main()
{
constexpr int limit{ 1'000 };
bool already_seen[limit + 1]{};
for (int i = 1; i < 25; i++)
{
int current{ i };
while ( current <= limit and not already_seen[current] )
{
std::cout << current << ' ';
already_seen[current] = true;
if ( current % 2 == 0)
{
current /= 2;
}
else
{
current = (3 * current) + 1;
}
}
std::cout << current << '\n';
}
}
Testable here.

Problem in Knights Tour using backtracking

I am getting a infinite loop when I try and run my solution for the Knights Tour problem using Backtracking
My Solution Code:
Link: https://ideone.com/Ud92vF
code:
#include <bits/stdc++.h>
using namespace std;
bool valid(int arr[8][8],int r,int c)
{
if(r>=0 and r<8 and c>=0 and c<8 and arr[r][c]== -1)
return true;
return false;
}
void fun(int arr[8][8],int r,int c,int x)
{
if(x==64){
cout<<"***********************ARRAY FOUND***********************\n";
for(int i=0;i<8;i++){
for(int j=0;j<8;j++)
cout<<arr[i][j]<<" ";
cout<<"\n";
}
return;
}
if(!valid(arr,r,c))
return;
arr[r][c] = x;
fun(arr,r-2,c+1,x+1); fun(arr,r-2,c-1,x+1);
fun(arr,r-2,c+2,x+1); fun(arr,r-2,c-2,x+1);
fun(arr,r+2,c+1,x+1); fun(arr,r+2,c-1,x+1);
fun(arr,r+1,c+2,x+1); fun(arr,r+1,c-2,x+1);
arr[r][c] = -1;
}
int main()
{
int arr[8][8] ;
for(int i=0;i<8;i++){
for(int j=0;j<8;j++)
arr[i][j] = -1;
}
int r=0,c=0,x=0; fun(arr,r,c,x);
}
Make sure your move array is correct:
fun(arr,r-2,c-1,x+1); fun(arr,r-2,c+1,x+1);
fun(arr,r-1,c-2,x+1); fun(arr,r-1,c+2,x+1);
fun(arr,r+1,c-2,x+1); fun(arr,r+1,c+2,x+1);
fun(arr,r+2,c-1,x+1); fun(arr,r+2,c+1,x+1);
With this I get a right answer:
***********************ARRAY FOUND***********************
0 11 8 5 2 13 16 19
9 6 1 12 17 20 3 14
30 27 10 7 4 15 18 21
63 24 31 28 35 22 47 44
32 29 26 23 48 45 36 57
25 62 51 34 39 56 43 46
52 33 60 49 54 41 58 37
61 50 53 40 59 38 55 42
Note that as you use the 65th move to validate you answer, you'll get 8 of the same correct answers in a row. And then another 8. Etc. You can fix this by printing after your 64th move:
void fun(int arr[8][8],int r,int c,int x)
{
if(!valid(arr,r,c))
return;
arr[r][c] = x;
if(x==63){
cout<<"***********************ARRAY FOUND***********************\n";
for(int i=0;i<8;i++){
for(int j=0;j<8;j++)
cout<<arr[i][j]<<" ";
cout<<"\n";
}
}
else
{
fun(arr,r-2,c-1,x+1); fun(arr,r-2,c+1,x+1);
fun(arr,r-1,c-2,x+1); fun(arr,r-1,c+2,x+1);
fun(arr,r+1,c-2,x+1); fun(arr,r+1,c+2,x+1);
fun(arr,r+2,c-1,x+1); fun(arr,r+2,c+1,x+1);
}
arr[r][c] = -1;
}
And one last issue is that you only ever start at {0,0} so you'll only find knights tours which start on that square. You really want to start from every square to find all possible knights tours. Or if you're feeling clever you only need to check a subset of the starting squares and use symmetry to generate the others.

Memory access failure in my RNG function, while using memcpy

I'm getting a memory access failure while i try to copy the element from my random array.
I have no clue what i am doing wrong, thx for your help in advance.
Here is my code:
1 #include <TSS_API_RNG.h>
2
3 using namespace std;
4
5 // dummy rng for internal speed tests
6 void rng(uint8_t out[], size_t len) {
7
8 unsigned char iv[len];
9 size_t i, k;
10 srand(time(NULL));
11 for (i = 0; i < len; i++) {
12 k = rand()%256;
13 iv[i] = (unsigned char)k;
14 cout << iv[i] << endl;
15
16 memcpy(&out[0], &iv[0], len);
17 cout << &out[0] << endl;
18 memset(&iv[0], 0x00, len);
19 }
20 }
21
22 int main() {
23
24 rng(NULL, 10);
25 return 0;
26 }
And this is what happens when i try to execute my programme:
pi#raspberrypi:~/projects/RNG_final $ ./DUMMY_RNG
▒
Speicherzugriffsfehler
I must be using the memcopy function not correctly, but i have no idea how to solve this issue. For testing i wanted to pass 10 random numbers, but it fails at the first iteration of memcpy. The loop itselfe works properly, hence it prints the value in the first cout value correctly.
Thx guys, managed to fix the issue with your advice.
My code:
1 #include <TSS_API_RNG.h>
2
3 using namespace std;
4
5 // constructor
6 DUMMY_RNG::DUMMY_RNG()
7 :r_len(0), r_count(0)
8 {
9 std::cout << "Neue Instanz" << std::endl;
10 }
11
12
13 // destructor
14 DUMMY_RNG::~DUMMY_RNG(void)
15 {
16 }
17
18
19 // dummy rng for internal speed tests
20 int DUMMY_RNG::rng(uint8_t out[], size_t len) {
21
22 unsigned char iv[len];
23 size_t k;
24 srand(time(NULL));
25 //for (i = 0; i < len; i++) {
26 k = rand()%256;
27 iv[0] = (unsigned char)k;
28
29 memcpy(&out[0], &iv[0], len);
30 memset(&iv[0], 0x00, len);
31 //}
32 return 1;
33 }
34
35
36 // randomize function replacement from botan rng class
37 void DUMMY_RNG::randomize(uint8_t out[], size_t len)
38 {
39 r_count += 1;
40 r_len += len;
41
42 rng(out, len);
43 }

Binary Search TestCase Not Returning a Value

So I am trying to solve the following question
Input Format is
N
x x x x x ...
q
y y y y y ...
N=size of array
x,x,x ... are elements of array
q=no of queries
y,y,y .. are queries to be searched in the array using binary search
Here is My code
#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
int N,q;
cin>>N;
int a[N];
for(int i=1;i<=N;i++)
{
cin>>a[i];
}
cin>>q;
int b[q];
for(int i=0;i<q;i++)
{
cin>>b[i];
}
int len=sizeof(a)/sizeof(a[1]);
sort(a,a+len);
int beg=1,end=N;
for(int j=0;j<q;j++)
{
beg=1;end=N;
while(beg<=end)
{
int mid=(beg+end)/2;
if(b[j]==a[mid])
{
cout<<mid<<endl;
break;
}
else if(b[j]<a[mid])
{
end=mid-1;
}
else
beg=mid+1;
}
}
return 0;
}
My code is giving the following output which is wrong
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
for the input
100
100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85 84 83 82 81 80 79 78 77 76 75 74 73 72 71 70 69 68 67 66 65 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
correct output is
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Arrays are 0-based.
Arrays are not variable-length in C++.
You have a wrong update here:
else if(b[j]<a[mid])
{
end=mid-1;
}
The end is non-inclusive.
You will also want to keep going until (beg<end) not beg<=mid - otherwise mid will simply equal both.
Here's C++ version that fixes all of the above and uses iterators instead of indexes. Iterators remove the ambiguity (base-0 vs base-1) and make it very explicit that a range is [begin, end), by contract.
Live ON Coliru
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
int main() {
int N;
cin >> N;
std::vector<int> a(N);
std::copy_n(std::istream_iterator<int>(std::cin), N, a.begin());
int q;
cin >> q;
std::vector<int> b(q);
std::copy_n(std::istream_iterator<int>(std::cin), q, b.begin());
sort(a.begin(), a.end());
for (auto query : b) {
auto beg = a.begin();
auto end = a.end();
while (beg < end) {
auto mid = beg + (end-beg) / 2;
if (query == *mid) {
cout << *mid << endl;
break;
} else if (query < *mid) {
end = mid;
} else beg = mid + 1;
}
}
}
Prints
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Problem 1
Your program has undefined behavior due to accessing a using an out of bounds index in the following loop.
for(int i=1;i<=N;i++)
{
cin>>a[i];
}
That loop needs to be changed to use a 0 based index.
for(int i = 0; i < N; i++)
{
cin >> a[i];
}
Problem 2
For similar reasons, the initial value of beg needs to be 0, not 1.
Problem 3
You are comparing with values of a[mid] but you are outputting mid. The output also needs to be a[mid].
Problem 4
else if(b[j]<a[mid])
{
end=mid-1;
}
needs to be
else if(b[j]<a[mid])
{
end=mid;
}
With the above changes, the program works as expected in my environment. Here's the updated program:
#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
int N,q;
cin>>N;
int a[N];
for(int i=0;i<N;i++)
{
cin>>a[i];
}
cin>>q;
int b[q];
for(int i=0;i<q;i++)
{
cin>>b[i];
}
int len=sizeof(a)/sizeof(a[1]);
sort(a,a+len);
int beg=0,end=N;
for(int j=0;j<q;j++)
{
beg=0;end=N;
while(beg<end)
{
int mid=(beg+end)/2;
if(b[j]==a[mid])
{
cout << a[mid] << endl;
break;
}
else if(b[j]<a[mid])
{
end=mid;
}
else
beg=mid+1;
}
}
return 0;
}
See it working at https://ideone.com/wgF2IS.
Array start with 0 index.so make sure for N elements your loop must start with zero index.
for(int i = 0; i < N; i++)
{
cin >> a[i];
}
Similarly, for same reason assign beg '0' value and end 'N-1' value.

Printing an array of STL list

I'm having some trouble printing an array of lists (ex. list<string> hashTable[100] )
Heres what I have so far, my question is at the bottom:
hash2.h
1 #ifndef __HASH2_H
2 #define __HASH2_H
3
4 #include<string>
5 #include<list>
6 #include<fstream>
7
8 using namespace std;
9
10 class Hash
11 {
12 public:
13 void processFile(string fileName);
14 void print();
15
16 private:
17 list<string> hashTable[100];
18
19 private:
20 int hf(string ins);
21
22
23 };
24
25 #endif
hash_function2.cpp
1 #include<iostream>
2 #include<string>
3 #include<fstream>
4 #include "hash2.h"
5
6 using namespace std;
7
8 void Hash::processFile(string fileName)
9 {
10 string word;
11 ifstream myIfile(fileName.c_str());
12 while(getline(myIfile, word))
13 {
14 int index = hf(word);
15 hashTable[index].push_back(word);
16 }
17 myIfile.close();
18 }
19
20 void Hash::print()
21 {
22 for(int i = 0; i < 100; i++)
23 {
24 if(hashTable[i] != NULL)
25 {
26 list<int>::iterator i;
27 for(i = hashTable[i].begin(); i != hashTable[i].end(); ++i)
28 {
29 cout << *i << endl;
30 }
31 }
32 }
33 }
34
35 int Hash::hf(string ins)
36 {
37 return ( (int) ins[0] ) % 100;
38 }
main2.cpp
1 #include "hash2.h"
2 #include<iostream>
3 #include<iomanip>
4 #include<fstream>
5
6 using namespace std;
7
8 int main()
9 {
10 Hash hashTable;
11 hashTable.processFile("test1.txt");
12 hashTable.print();
13 }
So, what I have now is the processFile function, which takes the text file, reads each word in, performs the hash function(crappy, i know), then puts that word in the array index which the hash function returned. That is working fine I think.
What im having issues with is essentially using the STL list. So, in hash_function2.cpp, i want to print my hash table. I'm not sure how to check if the array index is empty(doesn't have any of the words I stored), and I am also not sure how to print all the strings in the list at a given array index. Basically what I would like to do is just print my hash table; get my print() function working.
If anyone could point me in the right direction that would be awesome! It would be greatly appreciated.
You shouldn't be checking for NULL because you have an array of std::list objects, not pointers.
You can check if the list at index i has any elements with:
if (!hashTable[i].empty())
{
// there are elements in the list
}
Or
if (hashTable[i].size())
{
// there are elements in the list
}
Also in your print() function, you're using an iterator of type std::list<int>, but it should be std::list<string>, which matches the declaration of hashTable.
Your problem is not with std list, it is with the array.
You could try using the std::array
#include <array>
std::array< std::list<string>, 100> hashTable;
this way you can check if it is emtpy
if (!hashTable.empty())
{
// do stuff
}
and inside you can check each list
if(!hashTable[i].empty())
{
// do even more stuff
}
Awesome, Thanks a lot guys! I understand how to check each array index and iterate through the list! Heres what I did:
1 #include "hash2.h"
2
3 #include<iostream>
4 #include<string>
5 #include<fstream>
6
7 using namespace std;
8
9 void Hash::processFile(string fileName)
10 {
11 string word;
12 ifstream myIfile(fileName.c_str());
13 while(getline(myIfile, word))
14 {
15 int index = hf(word);
16 hashTable[index].push_back(word);
17 }
18 myIfile.close();
19 }
20
21 void Hash::print()
22 {
23 for(int i = 0; i < 100; i++)
24 {
25 if(hashTable[i].empty() != true)
26 {
27 list<string>::iterator r;
28 for(r = hashTable[i].begin(); r != hashTable[i].end(); ++r)
29 {
30 cout << *r << endl;
31 }
32 }
33 }
34 }
35
36 int Hash::hf(string ins)
37 {
38 return ( (int) ins[0] ) % 100;
39 }