C++ total beginner needs guidance [closed] - c++

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 8 years ago.
Improve this question
yesterday,we had to solve problems at the codeforces contest
I couldn't solve this problem since I am a total beginner.
http://codeforces.com/contest/353/problem/A
I used this algorithm, but something is wrong with it. I think it should print s or f, however it prints nothing. it just auto closes. Even when I added an input to stop instant close
#include <cstdlib>
#include <iostream>
using namespace std;
int main(){
int y=0;
int x=0;
int f;
int a;
cin >> a;
int s;
s = 0;
int number [a][a];
for(int i = 0;i<a;i++){
cin >> number[i][0] >> number[i][1];
x += number[i][0];
y += number[i][1];
}
for(int i = 0;i<a;i++){
if(x%2==0 && y%2==0){
return s;
}else if(y%2!=0 && x%2==0){
f = -1;
return f;
}else if(y%2==0 && x%2!=0){
f = -1;
return f;
}else{
y+= number[i][0];
x+= number[i][1];
s++;
}
}
int g;
if(f!=-1){
cout << s;
}else{
cout << f;
}
}

As Angew said, the return statements are incorrect and causing you to exit your main. You want to replace this by a break; to exit the loop but not the function.

I have not spent effort in trying to understand your algorithm, but at first glance it looks more complicated than it should be.
From my understanding of the problem, there are 3 possibilities:
the totals of the upper halves and the lower halves are already even (so nothing needs to be done)
the totals of the upper halves and the lower halves cannot be made even (so no solution exists)
just one Domino needs to be rotated to get the totals of the upper halves and the lower halves to be even (so the time needed is 1 second)
I base this on the fact that adding only even numbers always gives an even result, and adding an even number of odd numbers also always gives an even result.
Based on this, instead of having a 2-dimensional array like in your code, I would maintain 2 distinct arrays - one for the upper half numbers and the other for the lower half numbers. In addition, I would write the following two helper functions:
oddNumCount - takes an array as input; simply returns the number of odd numbers in the array.
oddAndEvenTileExists - takes 2 arrays as input; returns the index of the first tile with an odd+even number combination, -1 if no such tile exists.
Then the meat of my algorithm would be:
if (((oddNumCount(upper_half_array) % 2) == 0) && ((oddNumCount(lower_half_array) % 2) == 0))
{
// nothing needs to be done
result = 0;
}
else if (((oddNumCount(upper_half_array) - oddNumCount(lower_half_array)) % 2) == 0)
{
// The difference between the number of odd numbers in the two halves is even, which means a solution may exist.
// A solution really exists only if there exists a tile in which one number is even and the other is odd.
result = (oddAndEvenTileExists(upper_half_array, lower_half_array) >= 0) ? 1 : -1;
}
else
{
// no solution exists.
result = -1;
}
If you wanted to point out exactly which tile needs to be rotated, then you can save the index that "oddAndEvenTileExists" function returns.
You can write the actual code yourself to test if this works. Even if it doesn't, you would have written some code that hopefully takes you a little above "total beginner".

Related

As a student, how can I improve poor code? [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 4 years ago.
Improve this question
How do I improve this spaghetti code? I am a student and this is me being slow in my first programming course.
What I think I want to achieve
Find an alternating sum up to a number.
Problem overview
https://www.hackerrank.com/contests/cs102-s18-march31/challenges/treasure-road
This is a problem from the archive at provided by the teacher. I have deduced that an alternating sum has to be calculated, where the sum of the first odd integers has to be subtracted from the sum of the first even integers (of course up to #ofsteps/2).
What I did
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int arrodds[100]={0},arrevens[100]={0},sumevens=0,sumodds=0;
int steps;
cin >> steps;
int i=0;
while(i<steps/2)
{
if(i%2==0)
arrevens[i]=i;
else arrodds[i]=i;
i++;
}
for(int d=0;d<100;d++)
sumevens+=arrevens[d];
for(int h=0;h<100;h++)
sumodds+=arrodds[h];
cout << sumodds-sumevens;
return 0;
}
My logic/reasoning
Zingo can only move Steps/2, if he moves an odd step he moves forward, and Ringo moves a step closer to to Zingo, else if Zingo moves an even step Ringo moves away from Zingo.
Let's say there are 10 steps... 10/5=5... 5 steps= 1+2+3+4+5, odd steps=1,3,5; even steps=2,4; so displacement is 1+3-(2+4)=-2.
The code
I try to store the even and odd numbers in different arrays, then take the sum of each one and subtract the sums.
What's wrong?
My code works for small numbers it seems, as some test cases go beyond what I think My code could handle.
What I tried
I tried playing around with the sizes of my arrays but didn't get what I want.
Should I abandon this code and try something else? If not, how can I fix this abomination and guide me through it?
You can use a running sum instead of using arrays:
sum_evens = 0;
sum_odds = 0;
for (int i = 0; i < steps; ++i)
{
if (i & 1)
{
sum_odds += i;
}
else
{
sum_evens += i;
}
}
Edit 1:
The sum of the first N odd numbers is N*N.
You could change the calculation to:
sum_odds = steps * steps;
I'll leave the calculation of the first N even numbers up to the reader / OP.

Vector + for + if

OK, so the goal of this was to write some code for the Fibonacci numbers itself then take those numbers figure out which ones were even then add those specific numbers together. Everything works except I tried and tried to figure out a way to add the numbers up, but I always get errors and am stumped as of how to add them together. I looked elsewhere but they were all asking for all the elements in the vector. Not specific ones drawn out of an if statement.
P.S. I know system("pause") is bad but i tried a few other options but sometimes they work and sometimes they don't and I am not sure why. Such as cin.get().
P.S.S I am also new to programming my own stuff so I have limited resources as far as what I know already and will appreciate any ways of how I might "improve" my program to make it work more fluently. I also take criticism well so please do.
#include "../../std_lib_facilities.h"
int main(){
vector<int>Fibonacci;
int one = 0;
int two = 1;
int three = 0;
int i = 0;
while (i < 4000000){
i += three;
three = two + one; one = two; two = three;
cout << three << ", ";
Fibonacci.push_back(three);
//all of the above is to produce the Fibonacci number sequence which starts with 1, 2 and adds the previous one to the next so on and so forth.
//bellow is my attempt and taking those numbers and testing for evenness or oddness and then adding the even ones together for one single number.
}
cout << endl;
//go through all points in the vector Fibonacci and execute code for each point
for (i = 0; i <= 31; ++i)
if (Fibonacci.at(i) % 2 == 0)//is Fibonacci.at(i) even?
cout << Fibonacci.at(i) << endl;//how to get these numbers to add up to one single sum
system("pause");
}
Just do it by hand. That is loop over the whole array and and keep track of the cumulative sum.
int accumulator = 0; // Careful, this might Overflow if `int` is not big enough.
for (i = 0; i <= 31; i ++) {
int fib = Fibonacci.at(i);
if(fib % 2)
continue;
cout << fib << endl;//how to get these numbers to add up to one single sum
accumulator += fib;
}
// now do what you want with "accumulator".
Be careful about this big methematical series, they can explode really fast. In your case I think the calulation will just about work with 32-bit integers. Best to use 64-bit or even better, a propery BigNum class.
In addition to the answer by Adrian Ratnapala, I want to encourage you to use algorithms where possible. This expresses your intent clearly and avoids subtle bugs introduced by mis-using iterators, indexing variables and what have you.
const auto addIfEven = [](int a, int b){ return (b % 2) ? a : a + b; };
const auto result = accumulate(begin(Fibonacci), end(Fibonacci), 0, addIfEven);
Note that I used a lambda which is a C++11 feature. Not all compilers support this yet, but most modern ones do. You can always define a function instead of a lambda and you don't have to create a temporary function pointer like addIfEven, you can also pass the lambda directly to the algorithm.
If you have trouble understanding any of this, don't worry, I just want to point you into the "right" direction. The other answers are fine as well, it's just the kind of code which gets hard to maintain once you work in a team or have a large codebase.
Not sure what you're after...
but
int sum=0; // or long or double...
for (i = 0; i <= 31; ++i)
if (Fibonacci.at(i) % 2 == 0) {//is Fibonacci.at(i) even?
cout << Fibonacci.at(i) << endl;//how to get these numbers to add up to one single sum
sum+=Fibonacci.at(i);
}
// whatever
}

Learning C++, looking for a clarification on this project from a book

The goal here was to create a program that found and output all the prime numbers between 1 and 100. I've noticed I have a tendency to complicate things and create inefficient code, and I'm pretty sure I did that here as well. The initial code is mine, and everything that I've put between the comment tags is the code given in the book as a solution.
// Find all prime numbers between 1 and 100
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int counter; // loop counter
int count_two; // counter for second loop
int val; // equals the number of count, used in division to check for primes
bool check;
check = true;
for(counter = 1; counter <= 100; counter++){
val = counter;
for(count_two = 2; count_two <= 9; count_two++){
if((val % count_two) == !(check)){
cout << val << " is a prime number.\n";
}
}
}
return 0;
}
// program didn't work properly because of needless complication; all that needs to be checked for is whether a number is divisible by two
/*
*********correct code***********
#include <iostream>
using namespace std;
int main()
{
int i, j;
bool isprime;
for(i=1; i < 100; i++) {
isprime = true;
// see if the number is evenly divisible
for(j=2; j <= i/2; j++)
// if it is, then it is not prime
if((i%j) == 0) isprime = false;
if(isprime) cout << i << " is prime.\n";
}
return 0;
}
********************************
*/
From what I can gather, I was on a reasonably correct path here. I think I complicated things with the double loop and overuse of variables, which probably led to the program working incorrectly -- I can post the output if need be, but it's certainly wrong.
My question is basically this: where exactly did I go wrong? I don't need somebody to redo this because I'd like to correct the code myself, but I've looked at this for a while and can't quite figure out why mine isn't working. Also, since I'm brand new to this, any input on syntax/readability would be helpful as well. Thanks in advance.
As it is, your code says a number is prime if it is divisible by any of the numbers from 2 to 9. You'll want a bool variable somewhere to require that it's all and not any, and you'll also need to change this line:
if((val % count_two) == !(check)){
Since check = true, this resolves as follows:
if ((val % count_two) == !true){
and
if ((val % count_two) == false){
and
if ((val % count_two) == 0){
(Notice how the value false is converted to 0. Some languages would give a compile error here. C++ converts it into an integer).
This in fact does the opposite of what you want. Instead, write this, which is correct and clearer:
if (val % count_two != 0) {
Finally, one thing you can do for readability (and convenience!) is to write i, j, and k instead of counter, count_two, and count_three. Those three letters are universally recognized by programmers as loop counters.
In addition to the points made above:
You seemed to think you didn't need to have 2 loops. You do need them both.
Currently, in your code, the upper range of the inner loop is in-dependent on the value of your outer loop. But this is not correct; you need to test divisibility up the the sqrt(outer_loop_value). You'll note in your "correct" code they use half of the outer_loop_value - this could be a performance trade off but strictly speaking you need to test up to sqrt(). But consider that your outer loop was up to 7, your inner loop is testing division all the way up to 9 and 7 is in that range. Which means 7 would be reported as not prime.
In your "correct" code the indenting makes the code harder to interpret. The inner for loop only has a single instruction. That loop loops through all possible divisors. This is unnecessary it could break out at the first point that the mod is zero. But the point is that the if(isprime) cout << i << " is prime.\n"; is happening in the outer loop, not the inner loop. In your (un-commented) code you have put that in the inner loop and this results in multiple responses per outer loop value.
Stylistically there is no need to copy the counter into a new val variable.

For loop variable going to hell for seemingly no reason? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have run into what seems to be a very obscure bug. My program involves looping some code for a long time, and eventually running some functions in the loop. Weirdly, after I run a specific function, my for loop variable, 'z', jumps from 3200 to somewhere around 1059760811 (it changes every time). The function does not naturally use the loop variable, so I honestly have no idea what is happening here.
The entire code is too long to paste here, so I will try to paste only the important parts, with the relevant functions first and the for loop after:
void enterdata(float dpoint,int num){
autodata[num] += dpoint;
}
float autocorr(){
float autocorrelation = 0;
for(int a = 0; a<SIZEX; a++)
{
for(int b = 0; b<SIZEY; b++)
{
if(grid[a][b] == reference[a][b]){autocorrelation++;}
}
}
autocorrelation /= SIZEX*SIZEY;
autocorrelation -= 0.333333333333;
return autocorrelation;
}
for (long z = 0.0; z<MAXTIME; z++)
{
for (long k=0; k<TIMESTEP; k++)
{
grid.pairswap();
}
if (z == autostart_time)
{
grid.getreference();
signal = 1; // signal is used in the next if statement to verify that the autocorrelation has a reference.
}
if ((z*10)%dataint == 0)
{
if (signal == 1) {
//!!! this is the important segment!!!
cout << z << " before\n";
grid.enterdata(grid.autocorr(),count);
cout << z << " after\n";
cout << grid.autocorr() << " (number returned by function)\n";
count++;
}
}
if (z%(dataint*10) == 0) { dataint *= 10; }
}
From the "important segment" marked in the code, this is my output:
3200 before,
1059760811 after,
0.666667 (number returned by function)
Clearly, something weird is happening to the 'z' variable during the function. I have also become convinced that it is the enterdata function and not the autocorrelation function from tests running each separately.
I have no idea how to fix this, or what is going on. Help?!?!?
Thanks!
Looks like you may have a Stack Overflow issue in your enterdata function.
Writing to before the array starts or past the end of the array result in undefined behavior, including writing over variables already on the stack.
#WhozCraig is right, a stack overwrite by a called function seems the most likely explanation.
You should be able to find out in your debugger how to break on any change to the memory at address of z, this will quickly provide an exact diagnosis.
For Visual Studio (for example), see here.

Optimizing C code [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
Suppose we have an array of numbers say {1,2,3} and we want to equalize the numbers in the least number of turns possible; where the definition of a "turn" is as follows:
In a turn, you need to fix the value of one of the elements as is, and increment every other number by 1.
Considering the eg. already mentioned - A={1,2,3} , the goal is to equalize them.What I've already done is formulate the logic i.e The method to using a minimum number of turns is to choose the maximum number in each turn.
Iteration 1: Hold A[2]=3. Array at end of iteration => {2,3,3}
Iteration 2: Hold A[2]=3. Array at end of iteration => {3,4,3}
Iteration 3: Hold A[1]=4. Array at end of iteration => {4,4,4}
So,number of turns taken = 3
The code I've written is as follows:
#include<iostream>
#include<stdio.h>
int findMax(int *a,int n)
{
int i,max;
max=1;
for(i=2;i<=n;i++)
{
if(a[i]>a[max])
{
max=i;
}
}
return max;
}
int equality(int *a,int n)
{
int i;
for(i=1;i<n;i++)
{
if(a[i]!=a[i+1]) return 0;
}
return 1;
}
int main()
{
int a[100],i,count,t,posn_max,n,ip=0;
scanf("%d",&t);
while(ip<t)
{
count=0;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
while(equality(a,n)==0)
{
posn_max=findMax(a,n);
for(i=1;i<=n;i++)
{
if(i!=posn_max)
{
a[i]=a[i]+1;
}
}
count++;
}
printf("%d\n",count);
ip++;
}
return 0;
}
This gives me the correct answer I need alright. But I want to optimize it further.
My Time Limit is 1.0 s . But the judge site tells me my code takes 1.01s. Can anyone help me out?
As far as I can see, I've used scanf/printf statements as compared to cout/cin, in a bid to optimize the input/output part. But what else should I be doing better?
In your algorithm, you are increasing all numbers in the expect for the maximum.
If you do it the other way around, decreasing the maximum and leaving the rest of the numbers, the result should be the same (but with much less memory/array operations)!
To make it even faster, you can get rid of the memory oeprations completely (as suggested by Ivaylo Strandjev also): Find the minimum number and by the idea above (of decreasing numbers instead of increasing) you know how much decreases you require to decrease all numbers to this minimum number. So, after finding the minimum you need one loop to calculate the number of turns.
Take your example of {1,2,3}
The minimum is 1
Number of turns: (1-1)+(2-1)+(3-1) = 0 + 1 + 2 = 3
If you are really clever, it is possible to calculate the number of turns directly when inputting the numbers and keeping track of the current minimum number... Try it! ;)
You only care about the count not about the actual actions you need to perform. So instead of performing the moves one by one try to find a way to count the number of moves without performing them. The code you wrote will not pass in the time limit no matter how well you optimize it. The maximum element observation you've made will help you along the way.
Besides the other comments, if I get this right and your code is just a little bit too slow, here are two optimizations which should help you.
First, you can combine equality() and findMax() and only scan once through the array instead of your current worst case (twice).
Second, you can split the "increase" loop into two parts (below and above the max position). This will remove the effort to check the position in the loop.
1) Try unrolling the loops
2) Can you use SIMD instruction? That would really speed this code up
I would printf in a separate thread, since it's an I/O operation and is much slower than your calculations.
It also does not demand complicated management e.g Producer-Consumer queue, since you only pass the ordered numbers from 0 to last count.
Here's the pseudo-code:
volatile int m_count = 0;
volatile bool isExit = false;
void ParallelPrint()
{
int currCount = 0;
while (!isExit)
{
while (currCount < m_count)
{
currCount++;
printf("%d\n", currCount);
}
Sleep(0); // just content switch
}
}
Open the thread before the scanf("%d",&t); (I guess this initialization time is not counted), and close the thread by isExit = true; before the return from your Main().