so I'm trying to write a guess the number game in C++.The computer is Supposed to take a random number with 4 digits then the player should enter a number too.Rules are:
if the computer chooses:1234
And the player enters:1356
1 must be displayed in green,3 must in yellow since it's in the wrong place and 5&6 in red.the game goes on till the player gets the right answer.
#include<iostream>
#include <windows.h>
#include <stdlib.h>
#include <time.h>
#include<unistd.h>
using namespace std;
int main()
{
int b;
HANDLE handle=GetStdHandle(STD_OUTPUT_HANDLE);
cout<<"System is now generating a number...."<<"\n";
int *Number = new int[4];
srand (time(NULL));
for(int counter=0;counter<4;)
{
Number[counter]=(rand()%9)+1;
if(Number[counter]!=Number[counter-1]&Number[counter]!=Number[counter-2]
2]&Number[counter]!=Number[counter-3])
{
counter ++;
}
else
{
counter--;
}
}
cout<<Number[0]<<Number[1]<<Number[2]<<Number[3]<<"\n";
int *Guess=new int[4];
cout<<"please enter 4 digits for your number"<<"\n";
for(int counterG=0;counterG<4;counterG++) //line 34
{
cin>>Guess[counterG];
for(int counter;counter<4&counter>0;)
{
if((counter=counterG)&(Guess[counterG]=Number[counter])) //line 40
{
b=Guess[counterG];
SetConsoleTextAttribute(handle,10);
cout<<b<<"\n";
}
if((counter=counterG)&(Guess[counterG]==Number[counter- 1]|Guess[counterG]==Number[counter+1]|Guess[counterG]==Number[counter-2]|Guess[counterG]==Number[counter+2]))
{
b=Guess[counterG];
SetConsoleTextAttribute(handle,14);
cout<<b<<"\n";
}
else
{
b=Guess[counterG];
SetConsoleTextAttribute(handle,12);
cout<<b<<"\n";
}
}
}
now the program is fine until line 34 but nothing happens after that!
It just gets the player digits
I'd be glad if you could tell me what I've done wrong
Not a complete answer, but it's too long for a comment:
if(Number[counter]!=Number[counter-1]&Number[counter]!=Number[counter-2]
2]&Number[counter]!=Number[counter-3])
This line alone contains a lot of errors:
To have the logical AND operator you need &&, not &.
You have typed an extra 2] at the beginning of the second line. I hope it's just a typo that you introduced when writing the question.
The first time you run this, counter is 0. What happens when you try to access Number[counter-3]? It's an out of bounds access, which leads to Undefined Behaviour, which can lead to anything.
And there are probably many more.
What to do now:
Work on your code indentation. It's really bad.
Start from a much simpler program, and verify that it works. Then, add one small step, verify it, and don't move on until you are happy with the result
Turn on your compiler warnings. Warnings are your friends, not a boring annoyance
Learn how to use a debugger. You won't go very far without debugging.
1- replace & with &&(AND operator)
2- take input in a simple integer variable and then validate the number by performing first check of number greater than 0 and less than 9999.
3- then seperate digits from this variable and then assign those digits to aaray indexes respectvely.
Related
I found a video on youtube that says by using n&(n-1) we can able to count number of 1's bits and it's much faster than - right shifting the bits by one and then checking the last bit . When I wrote the code using this method to calculate number of bits it's giving output as 9 instead of 3 - if we 01011 as parameter.
I debug the program and not able to find why it's happening so ?I am confused when in while loop condition , both A and A-1 is 512, it get out of loop even A&(A-1) = 1000000000 not 0 (zero).
If anyone knows what I am missing please let me know .
#include <iostream>
using namespace std;
int bits(unsigned int A){
int counter=0;
unsigned int t;
while (A&(A-1))
{
counter++;
A--;
}
return counter;
}
int main()
{
unsigned int A=01011;
int res=bits(A);
cout<<"Result is "<<res<<"\n";
return 0;
}
Thanking You
Yours Truly,
Rishabh Raghwendra
This is the Kerningham trick to calculate the number of bits without shifting. (Original author precedes Kerningham by a decade, but mr K popularised it).
n&(n-1) peels off the least significant one, meaning that one should write the result back to n.
while (n) {
++counter;
n&=n-1;
}
Can anyone explain me the difference in the execution of both of the codes?
1)
#include <iostream>
using namespace std;
int main() {
// your code goes here
string code;
getline(cin,code);
for(int i=0;i<code.length();i++){
if(code[i]=='.'){
code.replace(i,1,"[.]");
}
}
cout<<code;
return 0;
}
The output screen of the above program code shows "time limit exceeded".
Time limit exceeded #stdin #stdout 5s 5220KB
#include <iostream>
using namespace std;
int main() {
// your code goes here
string code;
getline(cin,code);
for(int i=0;i<code.length();i++){
if(code[i]=='.'){
code.replace(i,1,"[.]");
i++;
}
}
cout<<code;
return 0;
}
whereas no.2 code shows the output as desired.
1[.]1[.]1[.]1
Can anyone explain how the execution took in both of the cases that one of the output shows "TLE"(the iteration count has to be declared in the for loop itself) and whereas the other one displays the output?
In this loop:
for(int i=0;i<code.length();i++){
if(code[i]=='.'){
code.replace(i,1,"[.]");
}
}
when you do a replacement of [.], in the next iteration of the loop i is now the index of the . that you just inserted. That . will be replaced again, and so on, infinitely many times, leading to a "time limit exceeded".
In the 2nd version, when a replacement is done, i is correctly being moved to point to the ] instead. You could move it one step further as well, since you know there is no . at that position either.
We can do this and see what happens, for example with this input:
code = "google.com"
After a while, i will be equal to 6, and then it happens:
i code
6 google[.]com (and now there's a dot on place 7)
7 google[[.]]com (and now there's a dot on place 8)
8 google[[[.]]]com (and now there's a dot on place 9)
... ...
And there is no way to stop this.
As the replacement makes the place of the dot shift one to the right, it might be a good idea to have a for-loop in the other sense:
for(int i=code.length()-1;i>=0;i--)
I'm trying to write a program to check if a number between 1 and 9999999 is a number whose digits either stay the same or increases from left to right(The variable and function names are in Vietnamese)
#include<stdio.h>
int daykhonggiam(int n)
{
while (n>=10)
{
int donvi=n%10;
n=n/10;
if(donvi<n%10)
{
return 0;
}
}
return 1;
}
int main(void)
{
for(int i=1;i<=9999999;i++)
{
if(daykhonggiam(i)==1)
printf("%d\n",i);
}
}
The problem is, when i compile and run the code ,only some of the results were shown( the results from 5555999 to 9999999 ). when i hit f9 i can the the results run from 1 but the final screen only shows from 5555999 to 9999999. I tried an online compiler and all the results were shown.
So i guessing my dev c++ 5.11 is the problem here. Is there any chance any of you know why that's the case ?
It looks like printf just fills console buffer completely and old lines get removed. Try writing results to file or increase console buffer capacity somehow.
Open your terminal, click the top left corner, go to properties, and increase your buffer size. Save, and test. Repeat if needed.
That being said, I concur with previous comments that you should just use an output file.
Edit: After some testing, I could only get a max number of 9,000 lines to display concurrently. I'd pursue using an output file in your case.
Background Info
I am designing a program in C++ to generate a weekly rota for my work.
It begins by specifying certain criteria, such as how many hours each person is required to work as well as what types of shifts they should work i.e. only day shifts, only at the weekend, etc.
The way I was thinking of designing the part of the code that randomly generates the rota was to initialize a 7 x 18 array (7 days in the week and 18 hours of working hours to cover a day). The program would then start with a for loop to determine what day and then a nested for loop to determine what hour of the day we are focussing on (sorry I know the terminology usage here is a bit sketchy). Each hour of each day it would generate a random number and assign it to the element. (Note: each person at the start of the program is assigned an integer to represent them.)
My question
I want to assign elements in the array more than one value (I require more than one person to work at any given time.) So I was wondering if this is even possible and if so, how would I go about doing it.
The code that I have so far is inserted below.
(Note: I do realise that this is at its very beginning stages. I first want to see if my general idea works before spending a lot of time writing it up.)
Thank you in advance.
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{ ofstream outFile;
outFile.open("array.dat");
srand(time(NULL));
int NoOfDaysInWeek=7;
int NoOfHoursinDay=18;
int array[NoOfDaysInWeek][NoOfHoursinDay];
James=1;
Mark=2;
Will=3;
Jamie=4;
Lisa=5;
Sandra=6;
Chris=7;
Julia=8;
Jane=9;
Anne=10;
Alexandra=11;
Jenny=12;
for (int i=0; i<NoOfDaysInWeek; i++) { // loop for day of week
for (int j=2; j<12; j++) { // loop for hours 2 to 12 (already
array[i][j]=5;
}
for (int j=0; j<8; j++) {
array[i][j]=(rand() % 4)+1; // only want mark, james, will or jamie to get these shifts.
}
}
}
Hello dear members of stackoverflow I've recently started learning C++, today I wrote a little game but my random function doesn't work properly. When I call my random function more than once it doesn't re-generate a number instead, it prints the same number over and over again. How can I solve this problem without using for loop?
Thanks
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
int rolld6();
int main()
{
cout<<rolld6()<<endl;
cout<<rolld6()<<endl;
system("PAUSE");
return 0;
}
int rolld6()
{
srand(time(NULL));
return rand() % 6 + 1;;
}
srand(time(NULL)); should usually be done once at the start of main() and never again.
The way you have it will give you the same number every time you call rolld6 in the same second, which could be a lot of times and, in your sample, is near guaranteed since you call it twice in quick succession.
Try this:
#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <stdlib.h>
int rolld6 (void) {
return rand() % 6 + 1;
}
int main (void) {
srand (time (NULL));
std::cout << rolld6() << std::endl;
std::cout << rolld6() << std::endl;
system ("PAUSE");
return 0;
}
One other thing to keep in mind is if you run this program itself twice in quick succession. If the time hasn't changed, you'll get the same two numbers in both runs. That's only usually a problem when you have a script running the program multiple times and the program itself is short lived.
For example, if you took out your system() call and had a cmd.exe script which called it thrice, you might see something like:
1
5
1
5
1
5
It's not something you usually do but it should be kept in mind on the off chance that the scenario pops up.
You are constantly reseeding the random number generator. Only call srand(time(NULL)); once at the beginning of your program.
Random functions (no matter the language) are only partially random.
in every technology you will have a equivalent to
srand(time(NULL));
This piece of codes seeds the random function to a start value and then the numbers a generated from there onwards
this means if your always reseeding form the same value you'll always get the same numbers
In your case you want to do something like this (calling srand(time(NULL)); only once).
int rolld6 (void) {
return rand() % 6 + 1;;
}
int main (void) {
srand (time (NULL));
...
//call your function here
}
one of the advantage of seeding with the same value is to offer the possibility to regenerate the same sequence of random numbers.
in one of my games, I would randomly place objects on the screen, but I also wanted to implement a retry option. this options of reseeding from the same value allows me to redo it without storing all the random values ^^