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--)
Related
I have recently started learning c++ and I have a question regarding the last section I reached, the while loop one.
In this code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int i = 0;
while (i <= 5) {
cout << "Hello" << endl;
i = i + 1;
}
return 0;
}
will the while command continue checking if i <=5 after the value goes over 5 or will it stop?
If I was making a program and changed the value of i down the line to one that meets the condition of the loop would it start again or would I have to rewrite the loop code again?
Thanks in advance for the answers!
edit: Thanks for your answers and comments. I tried putting into code what I was thinking and I noticed that changing the value of i after the loop didn't make it start again(meaning that it had already stopped checking after i surpassed 5).
I realize it was a stupid question that I could have simply solved by trying to put it into code, but I still asked for answers just to be sure. Thanks again!
If you changed i to 0 after the loop has ended like this:
int main()
{
int i = 0;
while (i <= 5) {
cout << "Hello" << endl;
i = i + 1;
}
i=0;
return 0;
}
The loop wouldn't start again because it would just set i to 0 and then go to return 0. Once the loop is executed it won't be run again.
Note that C++ executes the code sequentially, this means that its goes through every line, executes it, then goes to the next one. This is confusing for loops because you see previous code being executed again; therefore, to solve this dilemma, think of the loop segment as a block, once this block executes, the normal sequential execution continues.
For Future reference: C++ has a beautiful feature called Multi-threading, where you can allow several code to execute in a parallel fashion. You will meet this feature sometime in the future.
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.
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.
I've successfully used std::async in the past, but lately in checking the fidelity of some new code, I've run into an oddity that has me stumped. I'm sure there should be a simple explanation and a proper solution, but I can't find a discussion of it anywhere.
The following bit of minimal code illustrates the matter:
#include <functional>
#include <thread>
#include <future>
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
int main(int argc, char **argv) {
for (size_t delay = 0; delay < 2; delay++) {
std::vector<std::future<std::string>> futures;
for (size_t i = 0; i < 10; i++) {
auto fut = std::async(std::launch::async,
[&i] () -> std::string
{
std::stringstream ss;
ss << "work on number " << i << " " << std::this_thread::get_id();
return ss.str();
}
);
if (delay == 1) {
std::this_thread::sleep_for (std::chrono::milliseconds(10));
}
futures.push_back(std::move(fut));
}
// do not proceed until all threads are done
std::for_each(futures.begin(), futures.end(), [](std::future<std::string>& fut)
{
auto codeconf = fut.get();
std::cout << codeconf << std::endl;
}
);
std::cout << std::endl;
}
}
Without the delay (i.e. first time through the outer loop), some loop-elements (integers) get missed and don't get assigned to a thread/task, while other loop elements get assigned to more than one thread. The loop also runs beyond it's limits:
work on number 4 139770383861504
work on number 4 139770375468800
work on number 4 139770367076096
work on number 6 139770358683392
work on number 5 139770350290688
work on number 6 139770341897984
work on number 7 139770333505280
work on number 8 139770325112576
work on number 10 139770248296192
work on number 10 139770239903488
Including a minor delay (10 ms) allows loop increments and threads to correspond as expected and intended -- i.e. a one-to-one correspondence between loop increment and task/thread (the order of completion doesn't matter, of course, even though they are in order here):
work on number 0 139770239903488
work on number 1 139770248296192
work on number 2 139770325112576
work on number 3 139770333505280
work on number 4 139770383861504
work on number 5 139770375468800
work on number 6 139770367076096
work on number 7 139770358683392
work on number 8 139770350290688
work on number 9 139770341897984
My understanding is that the async launch policy should just pick up the integer that corresponds to the loop iteration, feed it into the lambda function, and execute it on an independent task/thread; when it starts (which is essentially immediate) and when it ends doesn't really matter to the functioning and logic of the loop. But here, without a delay, "async" seems to quite literally to describe the relationship between loop iterations and tasks.
Is the tiny delay workaround legitimate? What am I failing to understand?
Without the delay (i.e. first time through the outer loop), some loop-elements (integers) get missed and don't get assigned to a thread/task, while other loop elements get assigned to more than one thread
This is an immediate red flag for trying to access a loop counter from another thread that was spawned in that loop.
In this case, your tasks use a reference to i, which is being incremented (and eventually destroyed) in the main thread.
You should pass a copy of i to each task, so that the task assuredly uses whatever the value of i was on that iteration.
As #RichardCritten said in the comments, having one thread (the main one) writing to i while other threads are reading it leads to undefined behaviour. I wouldn't try to figure out why the output is like it is, the compile can change the ordering of memory stores/writes can change at will without synchronisation (mutex's etc).
A couple of helpful talks on the subject:
Herb Sutter's "atomic<> weapons": http://channel9.msdn.com/Shows/Going+Deep/Cpp-and-Beyond-2012-Herb-Sutter-atomic-Weapons-1-of-2
Han's Boehm's "Threads and Shared Variables in C++11": http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Threads-and-Shared-Variables-in-C-11
when i run the following c++ code
#include<iostream>
int main()
{
for(int i=1;i<=10;i++)
{
cout<<i<<endl;
}
cout<<i;
getch();
return 0;
}
I get result from no. 1 to 11.
i don't understand why the value of i = 11 after the block of for loop is finished,Please give me the reason.I have declared i inside for loop and scope of i has been finished after loop so why i get the outpout i=11 after execute second cout statement .I have not declared i in the variable declaration inside main.My question is that is i is visible outside of for loop?
Thanks in advance.
For multiple reasons, this program does not compile. You are either using an extremely old compiler, an extremely permissive compiler, or not showing us the program you're actually having a problem with.
From your comments it seems that you actually can compile it. I can only guess that you are using a very old compiler. Perhaps an old MS-DOS compiler (Zortech C++? Turbo C++?) since the getch function is not generally a standard library function and doesn't do the right thing in the curses library anyway. It's probably an old BIOS-based function from the MS-DOS days.
The standard was changed awhile ago (over 10 years now) so that variable declarations in the parenthesized section of a for loop are local to that loop. It was once not actually the case that this was true.
I no longer have access to any compiler that's so old it doesn't handle things this way. I'm surprised anybody does. Your program will not compile on my compiler.
Here is a version of your program that does compile, even though it requires the -lcurses option to link:
#include <iostream>
#include <curses.h>
using ::std::cout;
using ::std::endl;
int main()
{
for(int i=1;i<=10;i++)
{
cout<<i<<endl;
}
getch();
return 0;
}
Notice how the offending cout << i; statement is gone? That because it will not compile on a modern compiler.
Now, lets edit your program some more so it will compile with the cout << i; statement you're vexed about:
#include <iostream>
#include <curses.h>
int main()
{
using ::std::cout;
int i;
for (i = 1; i <= 10; i++)
{
cout << i << '\n';
}
cout << "last: " << i << '\n';
getch();
return 0;
}
This, of course, does print out last: 11 at the very end. This happens for a very obvious reason. What value does i have to have in order for the i <= 10 test to fail? Why, any value greater than 10! And since i is having one added to it every loop iteration, the first value i has that has the property of being greater than 10 is 11.
The loop test happens at the top of the loop and is used to decide if the remainder of the loop should be executed or not. And the increment happens at the very bottom of the loop (despite appearing in the body of the for statement). So i will be 10, will be printed, and then 1 will be added to it. Then the loop test (i <= 10) will be done, it will be discovered that 11 <= 10 is false, and control will drop out of the loop down to the print statement after the loop, and last: 11 will be printed.
And yes, the exact same thing will happen in C.
Because the loop breaks when the condition i<=10 becomes untrue, and this can happen when i becomes 11. Simple!
I think you wanted to write i < 10 .
Also, as #Omnifarious noted in the comment, the code shouldn't even compile, as i doesn't exist outside the loop. Maybe, you've declared i outside the loop, in your original code?
Besides the fact that it shouldn't compile (because i doesn't exist outside the loop block).
The loop runs from 1 to 10, so it stops when i reaches 11 and the condition fails. So i is 11 in the end of the loop.
This is because you have an old compiler.
cout<<i<<endl; should not compile, as cout and endl need to be qualified by the std namespace.
Fixing that, std::cout<<i; shouldn't compile because your variable is loop-scoped, so shouldn't even be visible outside the loop.
Fixing that, here's your code:
#include<iostream>
#include<conio.h>
int main()
{
int i;
for(i = 1; i <= 10; i++)
{
std::cout << i << std::endl;
}
std::cout << i;
getch();
return 0;
}
It should become more obvious why 11 is printed now.
When i == 10, the loop executes, increments i, and checks its value. It is then equal to 11, so it exits the loop.
Then you have another print statement, that will print the post-loop value, which is 11.
Here's the output I get from that corrected program:
1
2
3
4
5
6
7
8
9
10
11
This is the same as you are getting.
If you only want to print 1-10, then why have the extra std::cout << i;?
Recommendation
Get an up to date C++ compiler that will give you syntax errors on things that are no longer valid in standard-compliant C++
Get rid of the extra std::cout << i;
Keep your i variable loop-scoped, as in your original code
The result from my recommendations will be that you only see 1 through 10 printed, and you will have slightly fewer unexpected surprises in the future (as some "bad" and surprising code won't even compile).