Sorting integers with an array. - c++

I was attempting the following exercise, but got stuck in the process.
Write a full program that reads in an arbitrary sequence of integers
from the standard input, and writes them to the standard output in
sorted order and with all duplicates removed. You may assume the
input contains at most 100 integers .
I have a hard time understanding arrays and attempted to figure out what it is that I need to do. I have some code written down, but I have a strong feeling I'm nowhere near completing it. I'm not asking for someone to complete it for me, I just want some guidance on how to get going, or a push in the right direction. Any help is greatly appreciated.
#include <iostream>
using namespace std;
int main()
{
//I believe this is a start.
int numbers [100];
//declaring a counter
int i;
//making a for loop to count the integers from 1 to 100
for (i=0; i<100; i++)
{cin>>numbers[i];}
//This is the point where I got lost
if (i<100)
cout<<numbers[i]<<""<<endl;
}

In order to sort some int number, you have several way that you can try some of which you want.
One way is when you read data in first loop, put data in right position in array in this way that use another loop and shift new data until arrive to smaller number. Then put new data in front of that. If you find equal number you can ignore new data and use break and get new data.
for (i=0; i<100; i++)
{
int temp ;
cin>> temp;
int j;
for(j = i; j>= 0 ; j--)
{
if(j != 0 && number[j-1]== temp)
break ;
if(j != 0 && number[j-1] > temp)
{
number[j] = number[j-1] ;
}
else
{
number[j] = temp ;
break;
}
}
}
I think this way is best, but you have other way like:
sort all number using an algorithm like bubble sort or Quick sort then with a loop delete all duplicate numbers.
int temp[100] ;
int k = 0 ;
temp[0] = number[0] ;
for(int i = 1 ; i < 100 ; i++)
{
if(temp[k] != number[i])
{
k++;
temp[k] = number[i] ;
}
}

Related

2d array comparing with char

I have an array that reads data from a file, the data is binary digits such as 010011001001 and many others so the data are strings which I read in to my 2d array but I am stuck on comparing each value of the array to 0. Any help would be appreciated.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string myArr[5000][12];
int i = 0, zeroCount = 0, oneCount = 0;
ifstream inFile;
inFile.open("Day3.txt");
while(!inFile.eof())
{
for(int i = 0; i < 5000; i++)
{
for(int j = 0; j < 12; j++)
{
inFile >> myArr[i][j];
j++;
}
i++;
}
}
for(int j = 0; j < 12; j++)
{
for(int i = 0; i < 5000; i++)
{
if(myArr[i][j].compare("0") == 0)
{
zeroCount++;
}
else
{
oneCount++;
}
i++;
}
if(zeroCount > oneCount)
{
cout << "Gamma is zero for column " << i << endl;
}
else
{
cout << "Gamma is One for column " << i << endl;
}
j++;
}
}
some input from the text file:
010110011101
101100111000
100100000011
111000010001
001100010011
010000111100
Thank you for editing you question and providing more information. Now, we can help you. You have 2 major misunderstandings.
How does a for loop work?
What is a std::string in C++
Let us start with the for loop. You find an explanation in the CPP reference here. Or, you could look also at the tutorial shown here.
The for loop has basically 3 parts: for (part1; part2; part3). All are optional, you can use them, but no need to use them.
part1 is the init-statement. Here you can declare/define/initialize a variable. In your case it is int i = 0. You define a variable of data type int and initialize it with a value of 0
part2 is the condition. The loop will run, until the condition becomes false. The condition will be check at the beginning of the loop.
part3 is the so called iteration-expression. The term is a little bit misguiding. It is basically a statement that is executed at the end of the loop, before the next loop run will be executed and before the condition is checked again.
In Pseudo code it is something like this:
{
init-statement
while ( condition ) {
statement
iteration-expression ;
}
}
which means for the part of your code for(int j = 0; j < 12; j++)
{
int j = 0; // init-statement
while ( j < 12 ) { // while ( condition ) {
inFile >> myArr[i][j]; // Your loop statements
j++; // Your loop statements PROBLEM
j++; // iteration-expression from the for loop
}
}
And now you see the problem. You unfortunately increment 'j' twice. You do not need to do that. The last part3 of the for loop does this for you already.
So please delete the duplicated increment statements.
Next, the std::string
A string is, as its names says, a string of characters, or in the context of programming languages, an array of characters.
In C we used to write actually char[42] = "abc";. So using really a array of characters. The problem was always the fixed length of such a string. Here for example 42. In such an array you could store only 41 characters. If the string would be longer, then it could not work.
The inventors of C++ solved this problem. They created a dynamic character array, an array that can grow, if needed. They called this thing std::string. It does not have a predefined length. It will grow as needed.
Therefore, writing string myArr[5000][12]; shows that you did not fully understand this concept. You do not need [12], becuase the string can hold the 12 characters already. So, you can delete it. They characters will implicitely be there. And if you write inFile >> myString then the extractor operator >> will read characters from the stream until the next space and then store it in your myString variable, regardless how long the string is.
Please read this tutorial about strings.
That is a big advantage over the C-Style strings.
Then your code could look like:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string myArr[5000];
int zeroCount = 0, oneCount = 0;
ifstream inFile;
inFile.open("Day3.txt");
while (!inFile.eof())
{
for (int i = 0; i < 5000; i++)
{
inFile >> myArr[i];
}
}
for (int i = 0; i < 5000; i++)
{
zeroCount = 0; oneCount = 0;
for (int j = 0; j < 12; j++)
{
if (myArr[i][j]== '0')
{
zeroCount++;
}
else
{
oneCount++;
}
}
if (zeroCount > oneCount)
{
cout << "Gamma is zero for column " << i << endl;
}
else
{
cout << "Gamma is One for column " << i << endl;
}
}
}
But there is more. You use the magic number 5000 for your array of strings. This you do, because you think that 5000 is always big enough to hold all strings. But what, if not? If you have more than 5000 strings in your source file, then your code will crash.
Similar to the string problem for character arrays, we have also a array for any kind of data in C++, that can dynamically grow as needed. It is called std::vector and you can read about it here. A tutorial can be found here.
With that you can get rid of any C-Style array at all. But please continue to study the language C++ further and you will understand more and more.
Ther are more subtle problems in your code like while(!inFile.eof()), but this should be solved later.
I hope I could help

How to compare structs faster (who met the most people problem)

I will start by saying that I'm not a native speaker so please excuse me my grammatical errors.
I'm an university student and my task is the following: I have an input that tells me the number of people, and then every line contains the time of arrival and the time of exit, both natural numbers separated by a space.
I have to find the (index of the) person who met the most people and then output the number of meetings that person had.
Example input and output:
If person A has datestamps of 3 and 6 and person B has 6 and 7, it is still considered a meeting.
I already solved this problem with a fixed size array of structs that compares every person to everybody else to find out the number of meetings and then searched for the person with the most meetings.
My problem is that this code is very slow and I must hadle inputs consisting of maximum 200000 people and timestamps ranging from 1 to 1000000.
This - compare everyone with everyone else - solution works for small sample sizes, but there is no way it can work for 200000 structs.
Also, this code has to successfully run under 0.2 sec.
What is a faster way to solve this?
#include <iostream>
using namespace std;
const int maxN = 20000;
struct Data {
int arrival;
int departure;
int meetings = -1;
};
int main()
{
Data x[maxN];
int N;
///input
cin >> N;
for (int i = 0; i < N; i++) {
cin >> x[i].arrival;
cin >> x[i].departure;
}
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++){
if ( ((x[i].arrival >= x[j].arrival && x[i].arrival <= x[j].departure) || (x[i].departure >= x[j].arrival && x[i].departure <= x[j].departure)) || ((x[j].arrival >= x[i].arrival && x[j].arrival <= x[i].departure) || (x[j].departure >= x[i].arrival && x[j].departure <= x[i].departure)) ) {
x[i].meetings++;
}
}
}
int maxInd = 0;
int maximum = 0;
for(int i = 0; i < N; i++) {
if (x[i].meetings > maximum){
maxInd = i;
maximum = x[i].meetings;
}
}
///output
cout << maxInd+1 << endl;
cout << maximum << endl;
return 0;
}
I will only give you a starting point...
If I had to solve it, i would start by defining the following structure:
struct come_or_go {
size_t person_index;
int time;
bool arrival; // true for arrival, false for leaving
};
Next I would read the input into a vector<come_or_go> with two entries for each person. One when it arrives and one when it leaves. Next I'd sort that vector with respect to the elements time member. Finally I'd try to come up with a clever idea that requires to traverse this vector only once.
So far thats all I can provide, maybe I will update when I can give more hints. Hope this helps to push you into a differernt direction, because your brute force simply looses by complexity. Instead of trying to get details of it "faster" you need to change your overall approach.
I managed to do it by creating a vector and storing the 100.000 points of time in it.
I added 1 to each index where a person came in, stayed, and left.
Working with 100.000 long vectors, I managed to solve this problem with only one for loop se it ran reasonably fast.

Incorrect output for the second smallest integer

I'm having trouble finding the second smallest integer in my array. The array is unsorted (it's what's in the data.txt file), so I know that might be part of the problem, I'm not sure how to fix this in the simplest way. Afterwards I have to remove that integer from the array, move every number over and reprint the array, if anyone could help I'd really appreciate it.
const NUM = 10;
int Array[NUM];
ifstream infile;
infile.open("Data.txt");
for (int i = 0; i < NUM; i++)
{
infile >> Array[i];
cout << Array[i] << endl;
}
int Min = Array[0];
int Next = 0, SecondMin = 0;
for (int k = 0; k < NUM; k++)
{
if (Min > Array[k])
Min = Array[k];
}
for (int m = 2; m < NUM; m++)
{
Next = Array[m];
if (Next > Min)
{
SecondMin = Min;
Min = Next;
}
else if (Next < SecondMin)
{
SecondMin = Next;
}
}
cout << "The second smallest integer is: " << SecondMin << endl;
You don't have to loop over the array twice to find the second smallest number. As long as you're keeping track of both the smallest and the second smallest, you should be able to find them both with a single loop.
There are a couple of other problems with this code:
Your check for end of file should probably be if (!infile.eof())
You don't need to check if (i < NUM) inside your loop. i will always be less than NUM due to the constraint on the loop.
If for some reason the number of items in the file is less than NUM, the rest of the items in the array will have undefined values. For instance, if there were only nine items in the file, after reading the file, Array[9] would have whatever value happened to be in that spot in memory when the array was created. This could cause problems with your algorithm.
I assume that this is some sort of homework problem, which is why the use of an array is required. But keep in mind for the future that you'd probably want to use a std::vector in this sort of situation. That way you could just keep reading numbers from the file and adding them to the vector until you reached the end, rather than having a fixed number of inputs, and all of the values in the vector would be valid.

why am I getting seg fault in this?

Problem Statement
Mark is an undergraduate student and he is interested in rotation. A conveyor belt competition is going on in the town which Mark wants to win. In the competition, there's A conveyor belt which can be represented as a strip of 1xN blocks. Each block has a number written on it. The belt keeps rotating in such a way that after each rotation, each block is shifted to left of it and the first block goes to last position.
There is a switch near the conveyer belt which can stop the belt. Each participant would be given a single chance to stop the belt and his PMEAN would be calculated.
PMEAN is calculated using the sequence which is there on the belt when it stops. The participant having highest PMEAN is the winner. There can be multiple winners.
Mark wants to be among the winners. What PMEAN he should try to get which guarantees him to be the winner.
Definitions
PMEAN = (Summation over i = 1 to n) (i * i th number in the list)
where i is the index of a block at the conveyor belt when it is stopped. Indexing starts from 1.
Input Format
First line contains N denoting the number of elements on the belt.
Second line contains N space separated integers.
Output Format
Output the required PMEAN
Constraints
1 ≤ N ≤ 10^6
-10^9 ≤ each number ≤ 10^9
Code
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main (void)
{
int n;
cin>>n;
vector <int> foo;
int i = 0,j = 0,k,temp,fal,garb=0;
while (i < n)
{
cin>>fal;
foo.push_back(fal);
i++;
}
vector<int> arr;
//arr.reserve(10000);
for ( i = 0; i < n; i++ )
{
garb = i+1;
arr.push_back(garb);
}
long long product = 0;
long long bar = 0;
while (j < n)
{
i = 0;
temp = foo[0];
while ( i < n-1 )
{
foo[i] = foo[i+1];
i++;
}
foo[i] = temp;
for ( k = 0; k < n; k++ )
bar = bar + arr[k]*foo[k];
if ( bar > product )
product = bar;
j++;
}
return 0;
}
My Question:
What I am doing is basically trying out different combinations of the original array and then multiplying it with the array containing the values 1 2 3 ...... and then returning the maximum value. However, I am getting a segmentation fault in this.
Why is that happening?
Here's some of your code:
vector <int> foo;
int i = 0;
while (i < n)
{
cin >> fal;
foo[i] = fal;
i++;
}
When you do foo[0] = fal, you cause undefined behavior. There's no room in foo for [0] yet. You probably want to use std::vector::push_back() instead.
This same issue also occurs when you work on vector<int> arr;
And just as an aside, people will normally write that loop using a for-loop:
for (int i=0; i<n; i++) {
int fal;
cin >> fal;
foo.push_back(fal);
}
With regards to the updated code:
You never increment i in the first loop.
garb is never initialized.

Solving sudoku puzzle with c++

I want to make a program for solving a 3*3 sudoku puzzle. I have made a program but it is only working for 50% problems and for the rest it gives 60% right solution. I do not know how to solve it in a finite number of steps for every possible problem. The technique I have used is that I am searching every individual element of array and check which no does not exist in the same row and column and then I put it in that unit and move to the next. But this is not the solution for every problem. The next thing that come to mind was that we should have to write each and every possible number for a unit and then proceed. But how will we decide that which number we should finally put in the unit. I just want that how to write a solution that will work for every problem. I hope you got the point.
The code I have written is
#include<iostream>
using namespace std;
int rowsearch(int l[9][9],int row,int num) // function to search a particular number from a row of array
{
int counter=0;
for (int c=0 ; c<9 ; c++)
{
if (l[row][c]==num)
counter=counter+1;
}
if (counter>0)
return 1;
else
return 0;
}
int colsearch(int l[9][9],int col,int num) // function to search a number from a column of an array
{
int counter=0;
for (int c=0 ; c<9 ; c++)
{
if (l[c][col]==num)
counter=counter+1;
}
if (counter>0)
return 1;
else
return 0;
}
int rowcolnotexist(int x[9][9],int row , int col) // to find a nuber which does not exists int a row and column
{
for (int c=1 ; c<=9 ; c++)
{
if ( rowsearch(x,row,c)!=1 && colsearch(x,col,c)!=1)
return c;
}
return 0;
}
int main()
{
int l[9][9]={};
// input of the list
for (int i=0 ; i<9 ; i++)
for (int j=0 ; j<9 ; j++)
{
cout<<"Enter "<<i+1<<"*"<<j+1<<"entry of the list(For not entering a number enter 0).";
cin>>l[i][j];
}
// operations
for (int i=0 ; i<9 ; i++)
{
for (int j=0 ; j<9 ; j++)
if (l[i][j]==0)
l[i][j]=rowcolnotexist(l,i,j);
}
// printing list
for (int i=0 ; i<9 ; i++)
{
for (int j=0 ; j<9 ; j++)
{
cout<<l[i][j];
if ((j+1)%3==0)
cout<<" ";
else
cout<<" ";
}
if ((i+1)%3==0)
cout<<"\n\n\n";
else
cout<<"\n\n";
}
return 0;
}
I'd recommend the same algorithm I use when solving them myself ;-)
Choose an arbitrary square and list all the valid values for it, based on what is present in all the other rows (there's probably a way to make a more efficient decision about which square to start with).
Then move on to a related empty square (there's probably a way to make a more efficient decision about which square to check next) and store all its possible values.
Rinse and repeat until you find a square that has only one valid value.
Then unzip.
This should sounds like a recursive problem, by now. (note: almost anything that can be done recursively can be done conventionally, but the idea is the same).
So, store up a list of partially solved squares, and when you get to a square that's been solved completely, go back through your list in reverse order re-evaluating your partial solutions with the new data (namely, the one you WERE able to solve).
Rinse and repeat for full body and volume.