C++ Creating a phone number generator [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I'm working on a C++ project and have run into an issue that is leaving me puzzled. I am to create a phone number generator that has the user enter the first 4 numbers, and then generate all possible phone numbers that follow these two rules:
The last 6 digits must equal 33.
The 4th and 5th digit cannot both be even or both be odd.
This is what I've come up with so far:
#include <iostream>
using namespace std;
int main()
{//begin main
srand(time(0));
const int MAX_DIGITS = 10;
int num[MAX_DIGITS] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
cout<<"enter the first digit: ";
cin>>num[0];
cout<<"Enter the second digit: ";
cin>>num[1];
cout<<"Enter the third digit: ";
cin>>num[2];
cout<<"Enter the fourth digit: ";
cin>>num[3];
for (int e=0;e<MAX_DIGITS;e++)
{
for(int f=0;f<MAX_DIGITS;f++)
{
for(int g=0;g<MAX_DIGITS;g++)
{
for(int h=0;h<MAX_DIGITS;h++)
{
for(int i=0; i<MAX_DIGITS;i++)
{
for(int j=0;j<MAX_DIGITS;j++)
{
if ((num[e]+num[f]+num[g]+num[h]+num[i]+num[j]) == 33 && (num[3]%2 != 0 && num[4]%2 != 0) )
{
cout<<num[0]<<num[1]<<num[2]<<num[3]<<num[e]<<num[f]<<num[g]<<num[h]<<num[i]<<num[j]<<endl;
}
}
}
}
}
}
}
It all makes sense to me so far, but the program is displaying some numbers multiple times, and I'm not entirely certain how to make sense of the even/odd rule.
I'm still a rookie to programming and I'm sure that there may be a more efficient way to do this, but I'm trying my best and this has left me puzzled. Any help would be appreciated.
Thanks in advance!
EDIT: My question is this, how do I get the generator to display the numbers with the even/odd rule applied? My best idea was to use the modulus operator (%) to see if the remainder of the numbers divided by two was zero, and if so, the numbers were even. This is where I stumble a bit though, because I'm not perfectly certain how to implement this. Sorry for not being more specific the first time.

1) You're not ever changing the values in the num array, so testing to see if it contains a valid number doesn't work because the initial values you set don't fit the rules.
2) The validation is checking to see if both numbers are odd, not one or the other.
Here's a version that seems to work. The changes I made are to actually change the num array and then use a helper function to validate the numbers in the array so you don't have a mess inside your loops. I removed the srand call since you aren't using random numbers and the input of the first 4 digits to make testing easier for me. You can add that back if you like.
#include <iostream>
const int MAX_DIGITS = 10;
bool IsValid(int num[MAX_DIGITS])
{
int sum = 0;
for(int z = 4; z < MAX_DIGITS; ++z)
{
sum += num[z];
}
if(sum != 33)
{
return false;
}
int numodd = 0;
for(int z = 3; z < 5; ++z)
{
numodd += (num[z] % 2);
}
if(numodd != 1)
{
return false;
}
return true;
}
int main()
{
int num[MAX_DIGITS];
num[0] = 5;
num[1] = 5;
num[2] = 5;
num[3] = 1;
for (int e=0;e<MAX_DIGITS;e++)
{
num[4] = e;
for(int f=0;f<MAX_DIGITS;f++)
{
num[5] = f;
for(int g=0;g<MAX_DIGITS;g++)
{
num[6] = g;
for(int h=0;h<MAX_DIGITS;h++)
{
num[7] = h;
for(int i=0; i<MAX_DIGITS;i++)
{
num[8] = i;
for(int j=0;j<MAX_DIGITS;j++)
{
num[9] = j;
if(IsValid(num))
{
for(int z = 0; z < MAX_DIGITS; ++z)
{
if(z == 3 || z == 6)
{
std::cout << '-';
}
std::cout << num[z];
}
std::cout << std::endl;
}
}
}
}
}
}
}
}

Related

Unıque Random Number Check form Array c++

#include <iostream>
#include<ctime>
#include<cstdlib>
#include<string>
#include<cmath>
using namespace std;
int main()
{
bool cont = false;
string str;
int num, num2;
cin >> str >> num;
int arr[10];
int a = pow(10, num);
int b = pow(10, (num - 1));
srand(static_cast<int>(time(NULL)));
do {
num2 = rand() % (a - b) + b;
int r;
int i = 0;
int cpy = num2;
while (cpy != 0) {
r = cpy % 10;
arr[i] = r;
i++;
cpy = cpy / 10;
}
for (int m = 0; m < num; m++)
{
for (int j = 0; j < m; j++) {
if (m != j) {
if (arr[m] == arr[j]) {
break;
}
else {
cont = true;
}
}
}
}
cout << num2 << endl;
} while (!cont);
return 0;
}
I want to take a number from the user and produce such a random number.
For example, if the user entered 8, an 8-digit random number.This number must be unique, so each number must be different from each other,for example:
user enter 5
random number=11225(invalid so take new number)
random number =12345(valid so output)
To do this, I divided the number into its digits and threw it into the array and checked whether it was unique. The Program takes random numbers from the user and throws them into the array.It's all right until this part.But my function to check if this number is unique using the for loop does not work.
Because you need your digits to be unique, it's easier to guarantee the uniqueness up front and then mix it around. The problem-solving principle at play here is to start where you are the most constrained. For you, it's repeating digits, so we ensure that will never happen. It's a lot easier than verifying if we did or not.
This code example will print the unique number to the screen. If you need to actually store it in an int, then there's extra work to be done.
#include <algorithm>
#include <iostream>
#include <numeric>
#include <random>
#include <vector>
int main() {
std::vector<int> digits(10);
std::iota(digits.begin(), digits.end(), 0);
std::shuffle(digits.begin(), digits.end(), std::mt19937(std::random_device{}()));
int x;
std::cout << "Number: ";
std::cin >> x;
for (auto it = digits.begin(); it != digits.begin() + x; ++it) {
std::cout << *it;
}
std::cout << '\n';
}
A few sample runs:
Number: 7
6253079
Number: 3
893
Number: 6
170352
The vector digits holds the digits 0-9, each only appearing once. I then shuffle them around. And based on the number that's input by the user, I then print the first x single digits.
The one downside to this code is that it's possible for 0 to be the first digit, and that may or may not fit in with your rules. If it doesn't, you'd be restricted to a 9-digit number, and the starting value in std::iota would be 1.
First I'm going to recommend you make better choices in naming your variables. You do this:
bool cont = false;
string str;
int num, num2;
cin >> str >> num;
What are num and num2? Give them better names. Why are you cin >> str? I can't even see how you're using it later. But I presume that num is the number of digits you want.
It's also not at all clear what you're using a and b for. Now, I presume this next bit of code is an attempt to create a number. If you're going to blindly try and then when done, see if it's okay, why are you making this so complicated. Instead of this:
num2 = rand() % (a - b) + b;
int r;
int i = 0;
int cpy = num2;
while (cpy != 0) {
r = cpy % 10;
arr[i] = r;
i++;
cpy = cpy / 10;
}
You can do this:
for(int index = 0; index < numberOfDesiredDigits; ++index) {
arr[index] = rand() % 10;
}
I'm not sure why you went for so much more complicated.
I think this is your code where you validate:
// So you iterate the entire array
for (int m = 0; m < num; m++)
{
// And then you check all the values less than the current spot.
for (int j = 0; j < m; j++) {
// This if not needed as j is always less than m.
if (m != j) {
// This if-else is flawed
if (arr[m] == arr[j]) {
break;
}
else {
cont = true;
}
}
}
}
You're trying to make sure you have no duplicates. You're setting cont == true if the first and second digit are different, and you're breaking as soon as you find a dup. I think you need to rethink that.
bool areAllUnique = true;
for (int m = 1; allAreUnique && m < num; m++) {
for (int j = 0; allAreUnique && j < m; ++j) {
allAreUnique = arr[m] != arr[j];
}
}
As soon as we encounter a duplicate, allAreUnique becomes false and we break out of both for-loops.
Then you can check it.
Note that I also start the first loop at 1 instead of 0. There's no reason to start the outer loop at 0, because then the inner loop becomes a no-op.
A better way is to keep a set of valid digits -- initialized with 1 to 10. Then grab a random number within the size of the set and grabbing the n'th digit from the set and remove it from the set. You'll get a valid result the first time.

How find the count integers that are divisible by 7 in the given range using only While loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
---How write a program that will get A and B inputs and the numbers in the [A, B] range will be divisible by 7 without the remainder... using while loop in C++...---
For Example:
Input data: 7 13
console result: 1
Input data 5 21
console result: 3
Input data -8 -5
console result: 1
C++ code example with for loop
int main() {
int a, b,i,count;
input >> a >> b;
count = 0;
for(i = a; i <= b; i++) {
if(i % 7 == 0)
count++
}
}
I'm not sure if this is pseudo-code or actual code, but the main mistake I see here is that you've used 'input' and I'm not sure what that's supposed to be. See the following example:
#include <iostream>
using namespace std;
int main() {
int count=0;
int a = 0;
int b = 0;
cin >> a >> b;
for(int i = a; i <= b; i++) {
if(i % 7 == 0) {
count++;
}
}
cout << count;
}
I replaced your 'input' with 'cin'. Then, I added an output of the 'count' variable so that we could see the result.
Now, to take it further and use a while loop, you just need to manually count:
#include <iostream>
using namespace std;
int main() {
int count=0;
int a = 0;
int b = 0;
cin >> a >> b;
while (a <= b) {
if (a % 7 == 0) {
count++;
}
a = a +1;
}
cout << count;
}
So, we simply need to say while a is less than or equal to b, do the same thing as before. But, make sure that you increase a, or your loop will go on forever!
Everything is correct in terms of pseudo code. Do you want the negative number to be included or not?
Anyway, I am counting negative numbers also.
#include <iostream>
int main()
{
int a, b, i, count = 0;
std::cin >> a >> b;
i = a;
while (i <= b) // While loop
{
if (i % 7 == 0)
{
count++;
}
i++;
}
std::cout << "Count: " << count << "\n";
return 0;
}

Duplicates in X element array

I have an interval (m,n) and there I have to print out all the numbers which have different digits. I wrote this, but it only works for 2 digit numbers. I simply do not know how to make it work for anything but 2 digit numbers. I imagine that, if I added as much for loops as the digits of my number it would work, but the interval(m,n) isn't specified so it has to be something reliable. I've been trying to solve this problem on my own for 6 damn hours and I'm absolutely fed up.
Input 97,113;
Output 97,98,102,103,104,105,106,107,108,109
Numbers 99,100,101,110+ don't get printed, because they have 2 digits that are
the same.
#include<conio.h>
#include<math.h>
#include<stdio.h>
int main()
{
int m,n,test,checker=0;
scanf("%d%d",&m,&n);
if(m>n)
{
int holder=n;
n=m;
m=holder;
}
for(int start=m;start<=n;start++)
{
int itemCount=floor(log10(abs(start)))+1;
int nums[itemCount];
int index=0;
test=start;
do
{
int nextVal = test % 10;
nums[index++]=nextVal;
test = test / 10;
}while(test>0);
for (int i = 0; i < itemCount - 1; i++)
{ // read comment by #nbro
for (int j = i + 1; j < itemCount; j++)
{
if (nums[i] == nums[j])
{
checker++;
}
}
if(checker==0)printf("%d ",start);
}
checker=0;
}
}
Since you tagged this as C++, here is a very simple solution using simple modulus and division in a loop. No conversion to string is done.
#include <iostream>
#include <bitset>
bool is_unique_digits(int num)
{
std::bitset<10> numset = 0;
while (num > 0)
{
// get last digit
int val = num % 10;
// if bit is on, then this digit is unique
if (numset[val])
return false;
// turn bit on and remove last digit from number
numset.set(val);
num /= 10;
}
return true;
}
int main()
{
for (int i = 97; i <= 113; ++i)
{
if (is_unique_digits(i))
std::cout << i << "\n";
}
}
The is_unique_digit function simply takes the number and repeatedly extracts the digits from it by taking the last digit in the number. Then this digit is tested to see if the same digit appears in the bitset. If the number already exists, false is immediately returned.
If the number is not in the bitset, then the bit that corresponds to that digit is turned "on" and the number is divided by 10 (effectively removing the last digit from the number). If the loop completes, then true is returned.
Live Example
As an idea for a design:
print the number to a string, if it isn't a string already;
declare an array of int d[10]; and set it to all zeroes
for each ascii digit c of the string,
if (d[c-'0']==1) return 0; // this digit exists already in the number
else d[c-'0']= 1;
just put if(checker==0)printf("%d ",start); outside of second loop the loop
like this
for (int i = 0; i < itemCount - 1; i++)
{
for (int j = i + 1; j < itemCount; j++)
{
if (nums[i] == nums[j])
{
checker++;
break;
}
}
}
if(checker==0)
printf("%d ",start);
checker=0;
However instead of using two nested for loop you can use count array which is more efficient
to check 1 number, you can do
X=10; //number to analyze
char counts[10]; for int i=0;i<10;i++) counts[i]=0;
char number[10];
sprintf(&number,"%s",X); bool bad=false;
for(int i=0;i<strlen(number);i++)
{
if(++counts[number[i]-'0']>1) {bad=true;break;}
}`

C++ program to find the largest palindrome which is product of two two digit numbers [closed]

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 8 years ago.
Improve this question
I have seen this, but this is not what I am looking for.
The problem is same that is to find the largest palindrome which is the product of two three digit numbers.
Since my program was not working so I made a little change, instead of finding the largest palindrome which is the product of two three digit numbers I have written the program to find the largest palindrome which is the product of two two digit numbers.
Kindly see the program:
#include <iostream>
using namespace std;
int main() {
int i, j, n, s, m, w;
for (i = 99; i > 9; i--) {
for (j = 99; j > 9; j--)
n = i * j;
s = n;
while (n != 0) {
w = 0;
m = n % 10;
w = w * 10 + m;
n = n / 10;
}
if (s == w)
cout << s << endl;
break;
}
return 0;
}
The problem with this program is that it is neither showing any error nor giving any result.
So kindly help me to find the problem in my program.
Right now you are missing the curly braces for the j-loop. The current code is doing 99! * i.
Then you would have to focus on storing the largest palindrome value instead of just printing all those values to the screen (this is considering your implementation, it is not the most efficient one by any means).
Some modified version of your code:
#include <iostream>
using namespace std;
int main() {
int max_product = 0;
for (int i = 99; i > 9; i--) {
for (int j = i; j > 9; j--) {
int product = i * j;
if (product < max_product)
break;
int number = product;
int reverse = 0;
while (number != 0) {
reverse = reverse * 10 + number % 10;
number /= 10;
}
if (product == reverse && product > max_product) {
max_product = product;
}
}
}
cout << "Solution: " << max_product << endl;
return 0;
}
You have various problems:
Need one more pair of {, }. After the for-loop of j. The only instruction the for-loop of j is executing is: n = i * j; with the braces the rest of the instruction (testing if it's a palindrome) are out of the loop.
the variable w the reverse of the number to test for palindrome is reset his value to 0 in every execution of while (n != 0) loop resulting in incorrect reverse value (and never find the palindrome).
The max palindrome product of 2 two digits number don't have to be the first one found with this 2 for-loop, eg: suppose that there is 2 valid solutions i = 98, j = 2 and i = 70, j = 65 in this case i*j would be in first solution = 196 in the second = 4550 and when you found the first you could not stop the search. In your code using the break don't do what I think you are waiting for (stop the search), only stop the search with the actual i value.
Some notes about the modified code:
The two for-loop don't need to be from 99..9, in this case you are testing a lot of product two times (eg: 98*99, are testing when i == 98 and j == 99 and i == 99 and j == 98), you could restrict j to be always less or equal to i.
Using max_product to maintain the maximum palindrome product found. And use that info in the inner loop (if (product < max_product)) for early exit when no better solution could be found.

How Do I determine if a number is a prime number in array that has 1000 elements in it? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am making a program that determines if a value is composite, Prime, or Unvisited. The program ignores the first two values because they are 0 and 1, and labels them as I for ignore. Instead of outputting numbers it outputs the letter representation. example: "0123456" would output "IIPPCPC". It need to determines all the values up to 1000. The program uses loops to go through the array and change the value to the correct letter that represents it. I am confused on what code I would use to loop through the array and change all the values that are set to P at the moment that are composite to C. The program is suppose to reloop through the code in steps until all the values have be set to the correct representation.
/*
/ Name: Ralph Lee Stone
/ Description: Uses an array to find all the prime numbers up to 1000.
/ Date: 11/13/2013
/ Project: RLStone3_HW_10
*/
#include <iostream>
using namespace std;
int main()
{
// Declares an array to print all prime numbers up to 1000.
char mychararray[1001];
// Set all array index values to 'U', which stands for unvisited.
for(int i = 0; i <= 1000; i++)
{
mychararray[i] = 'U';
}
// Set the first two elements of the array index 0 & 1 to 'I'. which stands for ignore.
mychararray[0] = 'I';
mychararray[1] = 'I';
//for ( int i = 0 ; i < 1001 ; i ++ )
// cout << mychararray[i] ;
//cout << mychararray;
//Skips the first two values, so that the first two values are skipped.
int i = 0;
while(mychararray[i] !='U')
i++;
// Changes the all the values that are set to U to P.
for(int i = 2; mychararray[i] >= mychararray[1001]; i++)
mychararray[i] = 'P';
//i++;
// Loops through the array again and changes all the values that are set to P that are composite to C.
// Outputs the array.
for ( int i = 0 ; i < 1001 ; i ++ )
cout << mychararray[i] ;
//Pauses the console window.
system("pause");
// returns the value 0.
return(0);
}
This looks a lot like homework, so I'll skip the details. What you want is called the sieve of eratosthenes and consists in takin the numbers you already know are primes and discard all their multiples from the rest of the array.
for (int i = 2; i < 1001; i++)
{
for (int j = 2; j <= (int) sqrt(i); j++)
{
if (i % j == 0)
{
mychararray[i] = 'C';
break;
}
}
}
^^ For every number in the array check if the number is divisible by any numbers from 2 up to the square root of the number
for (int i = 2; i < 1001; i++)
{
for (int j = 2; j * i < 1001; j++)
mychararray[j * i] = 'C';
}
^^ Sieve of Eratosthenes
For definition, 1 is prime, 2 is the only prime number, so, you can have something like this:
bool isPrime(unsigned int number) {
if (number == 1 || number == 2) {
return true;
}
if (number % 2 == 0) {
return false;
}
for (int i = 2; i < number / 2; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
Then, you iterate over you array:
char representation[SIZE];
for (int i = 0; i < SIZE; i++) {
representation[i] = isPrime(data[i]) ? 'P' : 'C';
}