-1

Was trying out a question that I saw online, the questions requires the user to input the number of time the random number will be generated and to count how many digit 1, digit 2, digit 3, are there int he generated number.

For example
Enter number of time to loop : 4
2241 1204 5532 8593
There are 8 digits 1, digit 2 and digit 3.

code:

int main()
{
    int input;
    int ranNum;
    cout << "Enter the number of time to loop" << endl;
    cin >> input;
    srand(time(NULL));
    int i = 0;

    if (input < 0 || input > 50)
    {
        cout << "Invalid entry";
    }
    else
    {
        while(i++ < userInput) 
        {
            ranNum = (rand() % 10000);
            cout << ranNum<< " ";
        }

    }
    return 0;
}

The questions stated that using a switch case will be easier to get it done. However, I am not too sure how can a switch case worked for this. Or, is there any other method that I can use?

I've completed the code for the first 2 part, which is requiring user to input number as well as generating the random number based on user input

muXXmit2X
  • 2,745
  • 3
  • 17
  • 34
moon
  • 23
  • 3
  • `std::isdigit` and `std::map`. – LogicStuff Aug 17 '17 at 07:15
  • 1
    @moon Please show the code you have so far. That is probably the main reason you are getting downvotes, since you describe the problem quite well. – BoBTFish Aug 17 '17 at 07:16
  • 1
    @BoBTFish I've edited the question with code. – moon Aug 17 '17 at 07:20
  • When you say "the questions", to what are you referring? – David Schwartz Aug 17 '17 at 07:22
  • @DavidSchwartz the question that I saw online – moon Aug 17 '17 at 07:23
  • FWIW, I can't think of any sensible way a `switch`/`case` could be used to solve the problem. Maybe they're expecting you to foolishly use separate variables for each digit? – David Schwartz Aug 17 '17 at 07:24
  • @moon And I've counteracted one of the downvotes! Not related to your question, but there are several other points I consider "beginner mistakes" you might want to think about: [`using namespace std;`](http://stackoverflow.com/q/1452721/1171191), [`endl`](http://chris-sharpe.blogspot.co.uk/2016/02/why-you-shouldnt-use-stdendl.html), and ["`rand()` considered harmful"](https://www.youtube.com/watch?v=LDPMpc-ENqY). – BoBTFish Aug 17 '17 at 07:24
  • @DavidSchwartz that what I thought so as well, is there any other way that I could possibly do it? – moon Aug 17 '17 at 07:30
  • @moon You may as well just count all the digits. So you want an associative container, such as an `unordered_map`, from digit to count. Now what kind of container would be really handy from mapping a small integer to something... maybe a [`std::array`](http://en.cppreference.com/w/cpp/container/array)? Then just find a way to loop over all the digits in a number. Would you rather do it mathematically, or as a string? (Either is easy enough, try both and see which you think is cleaner). – BoBTFish Aug 17 '17 at 07:33
  • There are 2 ways to access digits in integer numbers: 1. modulo 10 and divide by 10, 2. turn the number into a string and access the characters in the string. – stefaanv Aug 17 '17 at 07:34
  • @BoBTFish I didn't learn this yet. Is there any other way to use it instead of using array? – moon Aug 17 '17 at 07:34
  • @stefaanv how do you access in string? – moon Aug 17 '17 at 07:35

2 Answers2

1

To count the number of occurrences of 1, 2 and 3 in a single integer value it would be easiest IMO to convert the integer into a string and then count the digits you are interested in:

int countDigits(int number, std::string digitsOfInterest = "123") {
  int ret = 0;
  std::string numberAsString = std::to_string(number); // convert it to string
  for (const char& digit : numberAsString) { // loop over every character
    if (digitsOfInterest.find(digit) != std::string::npos) {
      ret++;
    }
  }
  return ret;
}

Simply pass a randomly generated number into the function and add up the results. As you can see, by changing digitsOfInterest to another string, you can alter the digits you want to count.

PS.: Since I'm assuming that you have access to C++11 I would recommend to change your number generation to <random>.


Here is a non C++11 solution which works the same way the above one does:

int countDigits(int number, std::string digitsOfInterest = "123") {
  int ret = 0;
  std::ostringstream oss;
  oss << number;
  std::string numberAsString = oss.str(); // convert it to string
  for (size_t i = 0; i < numberAsString.size(); ++i) { // loop over every character
    if (digitsOfInterest.find(numberAsString[i]) != std::string::npos) {
      ret++;
    }
  }
  return ret;
}

Here is an example:

std::cout << "This number: '1243' contains " << countDigits(1243) << " times a digit of 1,2 or 3\n";

Result: This number: '1243' contains 3 times a digit of 1,2 or 3

muXXmit2X
  • 2,745
  • 3
  • 17
  • 34
0

I divided it to functions so it will be easier to understand. I used switch case because that what you asked, but there are other ways as well.

#include<time.h>
#include <iostream>
#include <stdlib.h>

// This function is the UI, i.e. asking the user how many numbers to generate
int HowManyNumbers()
{
    int input;
    std::cout << "Enter the number of time to loop" << std::endl;
    std::cin >> input;
    return input; 
}

// This function counts 1,2,3 for individual number 
int Count123InNum(int num)
{
        int count = 0;
        while(num)
        {
            int lastDig = num % 10;
            // count only if lastDigit in number is 1,2 or 3
            switch(lastDig)
            {
                case 1:
                case 2:
                case 3:
                    ++count;
                    break;

                default:
                    break;                          
            }
            num /= 10;
        }
        return count;
}

// This function receives number of random numbers to generate,
// and its output is a print of the numbers and the joint occurences of 1,2 and 3
void Get123FromRandomNums(int nRandNumbers)
{
    srand(time(NULL));
    std::cout << "In the numbers: ";
    int count = 0;

    while(nRandNumbers--)
    {
        int num = rand() % 10000;
        std::cout << num << " ";
        count += Count123InNum(num);
    }
    std::cout << "There are " << count << " digits 1, digit 2, digit 3." << std::endl;
}

int main()
{
    // Get number of random numbers (i.e. iterations)
    int nRandNumbers = HowManyNumbers();

    // check validity
    if (nRandNumbers < 0 || nRandNumbers > 50)
    {
        std::cout << "Invalid entry" << std::endl;
    }
    else
    {
        //if valid, count and print 1,2,3 occurences
        Get123FromRandomNums(nRandNumbers);
    }
    return 0;
}
Noam Ohana
  • 186
  • 14