Comparing digits and finding numbers with same digits - c++

here is my problem.The program needs to print out the number of numbers in the range between m and n which have different digits.For example:m=97,n=104;output:5.I seem to have problem with comparing the numbers and finding a way to check if there are 2 same digits.Here what I've written up till now:
enter code here
#include <iostream>
using namespace std;
int main()
{
int m, n;
cout << "m=";
cin >> m;
cout << "n=";
cin >> n;
for (int i = m; i <=n; ++i)
{
if (i >= m && i <= n)
{
while (i > 0)
{
m=i%=10;
i/= 10;
cout << m;
}
}
}
system("pause");
return 0;
}
If you can give me the easiest possible solution.Thanks in advance

The best way to do this is to break it down into two parts. The main part is responsible for incrementing the number set (which is easiest if the variables are integers) and the second part is to compare each part of the number to see if a number has been repeated (which is best done as a string).
So first I would define the method responsible for determining if the value has all distinct digits:
bool hasDistinctDigits(int m) {
string number = to_string(m);
for (string::size_type i = 0; i < number.size(); i++) {
for (string::size_type j = i + 1; j < number.size(); j++) {
if (number[i] == number[j]) return false;
}
}
return true;
}
This should be pretty easy to understand. First we need to convert the number to a string. Then we use 2 loops to determine if a character is repeated in a higher index. For example, with the number 102, it will compare the following sets: {1, 0}, {1,2}, {0, 2}
Then in the main function, I would call it like this:
int main()
{
int m, n, matched = 0;
cout << "m=";
cin >> m;
cout << "n=";
cin >> n;
for (int current = m; current <= n; ++current){
if (hasDistinctDigits(current)) {
cout << current << " is distinct" << endl;
matched++;
}
}
cout << "Total Matched: " << matched << endl;
system("pause");
return 0;
}

Related

C++ while loops and for loops not working

First, I'll send the code.
#include <iostream>
using namespace std;
int main() {
int times = 0;
cout << "Enter a number of candies:";
int number;
cin >> number;
while (number >= 1000) {
cout << "Please enter an integer number between 0 and 999.\n";
cin >> number;
}
for (times <= 10; times++; number--) {
cout << "nomnom I have" << number - 1 << "candies left.\n";
}
}
I am trying to practice c++ because I'm a beginner so I made a little program that is supposed to allow you to enter a number between 1 and 999, then this is gonna be the number of candies. Then, it says how many there are left. It's not working though. Can anyone tell me why? Thanks.
You should have your for loop formatted like this:
for (; times <= 10; times++, number--) {
cout << "nomnom I have" << number - 1 << "candies left.\n";
}
The format of the for loop follows the following rule:
for(<initializer, which you can skip> ; <condition for execution which is required> ; <increment or decrement of the variable which you are bounding with the condition, this part is not required either>)
Within the initializer part you can create multiple variables, you just need to separate them with a ",", the same rule applies to the final part of the for loop. Neither the initializer not the modifier at the end are required for correct syntax. This is a valid example:
int i = 0;
for(; i < 5;)
{
++i;
}
For example:
for(int i = 0, j = 5; i < 5 && j > 0; ++i, --j){}
int i = 0, j = 5;
for(; i < 5 && j > 0; ++i, --j){}
int i = 0, j = 5;
for(; i < 5 && j > 0;){
++i;
--j;
}
All of these examples are accomplishing the same task of incrementing i and decrementing j.
Your for loop is incorrect - it should be done according to this:
for( <initialization> ; <checking> ; <run_in_each_loop> ){ ...}
You can read more about for loop here.
You want your code to do 2 "increments" (<run_in_each_loop>). You can't do this using ; in between
A common idiom is to use the comma operator which evaluates both
operands, and returns the second operand. Thus:
for(int i = 0; i != 5; ++i,++j)
do_something(i,j);
read more here.
Other way would be to put number-- inside of { ... } brackets.
In the end, your code should look like that:
#include <iostream>
using namespace std;
int main() {
int times = 0;
cout << "Enter a number of candies:";
int number;
cin >> number;
while (number >= 1000) {
cout << "Please enter an integer number between 0 and 999.\n";
cin >> number;
}
for ( ; times <= 10; times++, number--) {
cout << "nomnom I have" << number << "candies left.\n";
}
return;
}
You're pretty close! There was just a slight issue with the for loop syntax:
The first part of the for loop is actually the initializer, the middle bit is the conditional, and the last bit is the iterator, it's a bit different than the while loop.
Here is what you probably meant to do:
for (times = 0; times < 9; number--, times++) {
cout << "nomnom I have" << number - 1 << "candies left.\n";
}

Inputting numbers separated by spaces

I am trying to make a code for one of the problems on an online coding platform. I have already made the code, but cannot get the input in the desired format. I need to take an input which has three integers (say n1, n2 and m). The question says that the input can be numbers separated by white spaces. I tried looking for help and even found a way, but it isn't working.
Here is my code:
#include <string>
#include <ctype.h>
#include <iostream>
#include <conio.h>
#include <stdlib.h>
using namespace std;
int main()
{
int t;
cout << "Enter the number of test cases" << endl;
cin >> t;
do
{
string rawInput;
int isNum, n1, n2, m, t, i, j;
int arr[3];
arr[0] = 0;
arr[1] = 0;
arr[2] = 0;
cout << "Enter a number, or numbers separated by a space, between 1 and 1000." << endl;
while (getline(cin, rawInput))
{
cout << "Rawinput" << rawInput.length();
for (i = 0; i < rawInput.length(); ++i)
{
cout << rawInput[i];
}
int j = 0, k = 0;
for (int j; j < rawInput.length(); ++j)
{
isNum = isdigit(rawInput[j]);
if (isNum)
{
arr[k] = arr[k] * 10 + atoi(rawInput[j]);
}
else
k = k++;
}
cout << "I am Array" << endl;
for (int l = 0; l < 3; l++)
cout << arr[l] << endl;
}
if (arr[0] >= arr[2] && arr[1] >= arr[2])
{
for (int i = 1; i <= arr[2]; i++)
{
if (arr[0] >= i && arr[1] >= i)
{
arr[0] = arr[0] - i;
arr[1] = arr[1] - i;
}
}
}
cout << arr[1] + arr[0];
t--;
} while (t > 0);
}
Specifically the function atoi doesn't seem to work. I tried using stoi, but even that isn't working.
If you are simply trying to collect a series of integers separated by spaces as user input..ie 1 2 3 4 5, you don't have to user the getline method.
You can redo the while loop for a condition like this:
int input;
while (cin >> input)
{
<<HANDLE INPUT>>
}
This is drastically reduce the line parsing you are trying to do and will capture the next inputted integer on that line as long as there is one to take. The loop iteration will go like this with the same series above...
Loop # Input Taken
1 1
2 2
3 3
... ...
This way there is no parsing necessary as it will handle ONE integer input per iteration.

How to count how many times each number has been encountered?

I am trying to write a program to count each number the program has encountered. by putting M as an input for the number of the array elements and Max is for the maximum amount of number like you shouldn't exceed this number when writing an input in the M[i]. for some reason the program works just fine when I enter a small input like
Data input:
10 3
1 2 3 2 3 1 1 1 1 3
Answer:
5 2 3
But when I put a big input like 364 for array elements and 15 for example for max. the output doesn't work as expected and I can't find a reason for that!
#include "stdafx.h"
#include <iostream>
#include<fstream>
#include<string>
#include <stdio.h>
#include<conio.h>
using namespace std;
int ArrayValue;
int Max;
int M[1000];
int checker[1000];
int element_cntr = 0;
int cntr = 0;
int n = 0;
void main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> ArrayValue>> Max;
for (int i = 0; i < ArrayValue; i++)
{
cin >> M[i];
checker[i]= M[i] ;
element_cntr++;
if (M[i] > Max)
{
cout << "the element number " << element_cntr << " is bigger than " << Max << endl;
}
}
for (int i = 0; i < Max; i++)
{
cntr = 0;
for (int j = 0; j < ArrayValue; j++)
{
if (M[n] == checker[j])
{
cntr+=1;
}
}
if (cntr != 0)
{
cout << cntr << " ";
}
n++;
}
}
You have general algorithm problem and several code issues which make code hardly maintainable, non-readable and confusing. That's why you don't understand why it is not working.
Let's review it step by step.
The actual reason of incorrect output is that you only iterate through the first Max items of array when you need to iterate through the first Max integers. For example, let we have the input:
7 3
1 1 1 1 1 2 3
While the correct answer is: 5 1 1, your program will output 5 5 5, because in output loop it will iterate through the first three items and make output for them:
for (int i = 0; i < Max; i++)
for (int j = 0; j < ArrayValue; j++)
if (M[n] == checker[j]) // M[0] is 1, M[1] is 1 and M[2] is 1
It will output answers for first three items of initial array. In your example, it worked fine because the first three items were 1 2 3.
In order to make it work, you need to change your condition to
if (n == checker[j]) // oh, why do you need variable "n"? you have an "i" loop!
{
cntr += 1;
}
It will work, but both your code and algorithm are absolutely incorrect...
Not that proper solution
You have an unnecessary variable element_cntr - loop variable i will provide the same values. You are duplicating it's value.
Also, in your output loop you create a variable n while you have a loop variable i which does the same. You can safely remove variable n and replace if (M[n] == checker[j]) to if (M[i] == checker[j]).
Moreover, your checker array is a full copy if variable M. Why do you like to duplicate all the values? :)
Your code should look, at least, like this:
using namespace std;
int ArrayValue;
int Max;
int M[1000];
int cntr = 0;
int main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> ArrayValue >> Max;
for (int i = 0; i < ArrayValue; i++)
{
cin >> M[i];
if (M[i] > Max)
{
cout << "the element number " << i << " is bigger than " << Max << endl;
}
}
for (int i = 0; i < Max; i++)
{
cntr = 0;
for (int j = 0; j < ArrayValue; j++)
{
if (i == M[j])
{
cntr ++;
}
}
if (cntr != 0)
{
cout << cntr << " ";
}
}
return 0;
}
Proper solution
Why do you need a nested loop at all? You take O(n*m) operations to count the occurences of items. It can be easily counted with O(n) operations.
Just count them while reading:
using namespace std;
int arraySize;
int maxValue;
int counts[1000];
int main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> arraySize >> maxValue;
int lastReadValue;
for (int i = 0; i < arraySize; i++)
{
cin >> lastReadValue;
if (lastReadValue > maxValue)
cout << "Number " << i << " is bigger than maxValue! Skipping it..." << endl;
else
counts[lastReadValue]++; // read and increase the occurence count
}
for (int i = 0; i <= maxValue; i++)
{
if (counts[i] > 0)
cout << i << " occurences: " << counts[i] << endl; // output existent numbers
}
return 0;
}

Ensure unique input is entered and stored in an array

Is this program OK, or can it be improved (but simply)? How do I make sure no repeat numbers are entered?
int n;
int array[9];
cout<<"Enter Number Between 9-0 Only"<<endl;
for(int i = 0; i<=10; i++){
cout<<"Enter Number" <<(i+1)<<endl;
cin >> n;
if((n >= 0) && (n <=9)){
array[i]=n;
}
else{
cout<<"Numbers from 0-9 only\n"<<endl;
break;
}
}
(edit) complete, compiling code
To check if the numbers are used with higher performance, try something like this (using the working code from Jack Radcliffe):
#include <iostream>
using namespace std;
int main()
{
int n = 0;
int array[9] = {0};
bool isUsed[10] = {0};
for(int i = 0; i < 9; i++)
{
cout << "Enter Number " << (i + 1) << endl;
cin >> n;
if((n >= 0) && (n <= 9))
{
if (isUsed[n] == false)
{
array[i] = n;
isUsed[n] = true;
}
else
{
cout << "Number has already been used." << endl;
i--;
}
}
else
{
cout << "Numbers from 0-9 only." << endl;
i--;
}
}
return 0;
}
Optimization isn't exactly necessary with this simple of code, but it's this seems to be an exercise of practice, so why not practice optimized code, too?
Most of it is fine, though there are two problems standing out.
First, you have an array of size 9, but you are taking in 11 numbers since you're starting the for loop at 0 and going through to 10.
Second, since you have it so if the entered number is not between 0 and 9, inclusive, the for loop breaks. This entails that fewer than 9 numbers will be put into the array if an invalid number is entered. Change the entire loop to read this and you should be good:
for(int i = 0; i < 9; i++) {
cout << "Enter Number " << (i + 1) << endl;
cin >> n;
if((n >= 0) && (n <= 9))
array[i] = n;
else {
cout << "Numbers from 0-9 only\n" << endl;
i--;
}
}
The whole fire part was right, but I removed the break in the else-statement and added in the i--. I added that in so when the user is prompted to re-enter the number, the entry number will be at the correct index.
I hope this was helpful.

Sum of Numbers C++

I am supposed to write a program that asks the user for a positive integer value. The program should use a loop to get the sum of
all the integers from 1 up to the number entered. For example, if the user enters 50, the loop will find the sum of
1, 2, 3, 4, ... 50.
But for some reason it is not working, i am having trouble with my for loops but this is what i have down so far.
#include <iostream>
using namespace std;
int main()
{
int positiveInteger;
int startingNumber = 1;
int i = 0;
cout << "Please input an integer up to 100." << endl;
cin >> positiveInteger;
for (int i=0; i < positiveInteger; i++)
{
i = startingNumber + 1;
cout << i;
}
return 0;
}
I am just at a loss right now why it isn't working properly.
The loop is great; it's what's inside the loop that's wrong. You need a variable named sum, and at each step, add i+1 to sum. At the end of the loop, sum will have the right value, so print it.
try this:
#include <iostream>
using namespace std;
int main()
{
int positiveInteger;
int startingNumber = 1;
cout << "Please input an integer upto 100." << endl;
cin >> positiveInteger;
int result = 0;
for (int i=startingNumber; i <= positiveInteger; i++)
{
result += i;
cout << result;
}
cout << result;
return 0;
}
I have the following formula that works without loops. I discovered it while trying to find a formula for factorials:
#include <iostream>
using namespace std;
int main() {
unsigned int positiveInteger;
cout << "Please input an integer up to 100." << endl;
cin >> positiveInteger;
cout << (positiveInteger * (positiveInteger + 1)) / 2;
return 0;
}
You can try:
int sum = startingNumber;
for (int i=0; i < positiveInteger; i++) {
sum += i;
}
cout << sum;
But much easier is to note that the sum 1+2+...+n = n*(n+1) / 2, so you do not need a loop at all, just use the formula n*(n+1)/2.
mystycs, you are using the variable i to control your loop, however you are editing the value of i within the loop:
for (int i=0; i < positiveInteger; i++)
{
i = startingNumber + 1;
cout << i;
}
Try this instead:
int sum = 0;
for (int i=0; i < positiveInteger; i++)
{
sum = sum + i;
cout << sum << " " << i;
}
int result = 0;
for (int i=0; i < positiveInteger; i++)
{
result = startingNumber + 1;
cout << result;
}
First, you have two variables of the same name i. This calls for confusion.
Second, you should declare a variable called sum, which is initially zero. Then, in a loop, you should add to it the numbers from 1 upto and including positiveInteger. After that, you should output the sum.
You are just updating the value of i in the loop. The value of i should also be added each time.
It is never a good idea to update the value of i inside the for loop. The for loop index should only be used as a counter. In your case, changing the value of i inside the loop will cause all sorts of confusion.
Create variable total that holds the sum of the numbers up to i.
So
for (int i = 0; i < positiveInteger; i++)
total += i;