My homework program has to write random numbers for arrival time and burst time into a file. Then after they are written, it reads the file and sorts the contents.
I figured setting up a 2d array would be the easiest way for me to go about this. But I am unsure on how to implement my sort so that if an arrival time swaps places then burst time of that arrival goes along for the ride.
I feel like I worded that poorly, but a basic example would be:
array[3][10] > array[2][23]
So since second array has an earlier arrival time I need both its arrival 2 and its burst 23 to move before array[3][10], but I need this do that and compare 100 inputs.
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <fstream>
const int max = 100;
using namespace std;
int main()
{
multimap<int [][]> myMap;
int randomBurst[max];
int arrivalTime[max];
int line[max][2];
int first = 0;
for (int i = 0; i < 100; i++)
{
if (i < 100)
{
ofstream write("Schedule.txt", ios::app);
randomBurst[i] = rand() % 1000;
arrivalTime[i] = rand() % 1000;
write << arrivalTime[i] << " " << randomBurst[i] << endl;
}
}
ifstream read("Schedule.txt");
for (int i = 0; i <= max; i++)
{
for (int j = 0; j < 2; j++)
{
read >> line[i][j];
cout << line[i][j] << " " ;
}
cout << endl;
}
cout << endl;
cout << endl;
for (int i = 0; i <= max; i++)
{
for (int j = 0; j < 2; j++)
{
myMap.insert(pair<int[][]>(line[i][j]);
}
cout << endl;
}
system("pause");
return 0;
}
My code sets up my array correctly after it reads the written file content, but I'm kind of lost what I should implement for a sort.
Well coming forward with this, mainly left that comment to be able to find this question faster on my laptop.
Like I said in the comment, if you want a presorted, by key value 2D "array", the quickest manner in which you could do this is with the map container., and if you really need the internal points to be ordered, and you will be using multiple entries within it, lets say entries 2,30 2,12 ... You could either build a map of vectors, or arrays, or use a Multimap. Not too sure of this data structure, as I have never really had a reason to use it as of yet. Referenced here http://www.cplusplus.com/reference/map/multimap/
The above will provide you with the sorting done for you, and the reason why I recommended a vector is the lack of order within it, and not sure if the 'bursts?' are to be ordered as well.
EDIT:
Forgot to mention, that a map will not hold more than one key of any given value, so if you are, again, inputting multiple points a above, then you will. if implementing things as you were before, overwrite things.
EDIT:
So this is more or less the fix I think I have, but you are working around this in a very indirect manner, that is hard to follow honestly.
#include <map>
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <fstream>
using namespace std;
const int MAX = 100;
int main()
{
multimap<int,int> myMap;
int randomBurst[100];
int arrivalTime[100];
int line[100][2];
int first = 0;
for (int i = 0; i < 100; i++)
{
if (i < 100)
{
ofstream write("Schedule.txt", ios::app);
randomBurst[i] = rand() % 1000;
arrivalTime[i] = rand() % 1000;
write << arrivalTime[i] << " " << randomBurst[i] << endl;
}
}
ifstream read("Schedule.txt");
for (int i = 0; i <= 100; i++)
{
for (int j = 0; j < 2; j++)
{
read >> line[i][j];
cout << line[i][j] << " " ;
}
cout << endl;
}
// cout << endl;
// cout << endl;
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 2; j++)
{
//Attain the value in the index, and the held value within it.
myMap.insert(pair<int, int> (line[i][j], line[i][j]));
}
cout << endl;
}
// system("pause");
return 0;
This fixes the insertion point, just because you give it an array it does not mean that the program will take that as a pair, as the first index is a point to another array in itself. And so on. I recommend starting off wiht a map object instead, as the multimap makes things a bit annoying, if you are familiar with the vector containers then use that instead within the map to log multiple values.
Related
#include <iostream>
#include <vector>
int i=0; //points at the current stack that we are working with
int box=0; //no. of boxes held by the crane
int64_t H; //max. height of the stacks given in the que.
int main()
{
int n, value; //storing no. of stacks and creating an additional variable value to store operations
std::cin>> n >> H;
int64_t arr[n]; //storing the no. of boxes each stack has in an array
std::vector<int> arr2; //storing the operations we have to perform in a vector
for(int j=0; j<n; j++){std::cin>> arr[j];} //getting arr
while(std::cin>>value) //getting arr2
{
arr2.push_back(value);
}
for(int xy=0; xy<n; xy++){if(arr[xy]>H){return 0;}} //ensuring that all stacks have no.of boxes less than max. height
if(arr2.size()<1 || arr2.size()>10e5 || n<1 || n>10e5 || H<1 || H>10e8){return 0;} //constraints given in the que.
int k=0; //creating a variable to keep count of how many programs we have already executed
while(k<arr2.size()){
if(arr2[k] == 1){MoveLeft();}
else if(arr2[k]==2){MoveRight(n);}
else if(arr2[k]==3){PickBox(arr, i);}
else if(arr2[k]==4){Dropbox(arr, i);}
else if(arr2[k]==0){k=arr2.size();}
k++;
}
for(int j=0; j<n; j++){std::cout<< arr[j] << " ";} //printing the arr after executing the code
return 0;
}
This is a question from a past year ZCO. And the above code is what I wrote to solve the prob.
The four functions Moveleft, MoveRight, Pickbox, Dropbox have been defined in the same file but aren't shown here because I think there's no issue with them.
When I submit the code, all test cases passed except 2. I don't know what is the problem with my code. Pls help me.
I have tried my best to make the code readable. Sorry if the code looks messy.
With the method you're trying to define an array with a user-input length is unfortunately invalid in C++.
But fortunately, there are basically two methods use to allocate arrays dynamically.
Method 1: Using Vectors
Vector is an important part of C++. It has a lot of features (e.g. its size don't need to be defined static unlike a normal array does, can redefine array size, etc.) An example's given:
#include <iostream>
#include <vector>
int main(void) {
std::vector<int> vArray; // vector<> declaration
int size = 0;
int getInput = 0;
std::cout << "Enter an array size: ";
std::cin >> size;
for (int i = 0; i < size; i++) {
std::cout << "Enter a value: ";
std::cin >> getInput;
vArray.push_back(getInput); // inserts one+ container and data in it
}
for (int i = 0; i < vArray.size(); i++) {
// retrieving contained data...
std::cout << vArray[i] << std::endl;
}
return 0;
}
Method 2: Using 'new' Keyword with Pointed Variable
The simple use of new will help you to achieve your requirement. It's less recommended since already there's concept of vectors which actually works efficiently than arrays. Let's take a look into a simple program:
#include <iostream>
int main(void) {
int *pArray;
int size;
std::cout << "Enter an array size: ";
std::cin >> size;
pArray = new int[size]; // initializing array with dynamic size
for (int i = 0; i < size; i++) {
std::cout << "Enter value: ";
std::cin >> pArray[i];
}
for (int i = 0; i < size; i++) {
std::cout << pArray[i] << std::endl;
}
delete[] pArray;
return 0;
}
Both are nice options to work with, but it's recommended by most using vector<>.
I want to output my histogram using the fewest amount of for loops possible
int* histogram(int size, int* arr)
{
int bin[10] = {};
for (int i = 0; i < size; i++)
{
if (arr[i] >= 0 && arr[i] < 10)
{
bin[0]++;
}
else if (arr[i] >= 10 && arr[i] < 20)
{
bin[1]++;
}
return bin;
}
Currently I am outputting the histogram like this:
cout << "0|";
for (int j = 0; j < bin[0]; j++)
cout << "*";
cout << endl;
But this is long and annoying. Is there a way to achieve the same output in fewer
for loops?
I am going to ignore the bugs in your histogram code, as it isn't really relevant to the question of optimising histogram output.
For information on the bug (returning a local variable), check out this Stack Overflow question.
Also, you are missing a curly brace. Always check that your code compiles and runs in its most minimalist form before posting it.
You state that the problem is that the method you use is "long and annoying", but it isn't clear if you are referring to the design of your code or the speed at which it performs.
Performance
The fastest you can possibly read the histogram is with O(n), where n is the number of bins in the histogram. In this sense your code is about as fast as it can get without micro-optimising it.
If you include the printing out of your histogram, then you have O(n*m), where m is the average number of entries per bin.
Writing a histogram is also O(n*k), where k is the number of entries in your array, because you have to figure out which bin each value belongs in.
Design
If the problem you have is that the code is bloated and unwieldy, then use less magic numbers and add more arguments to the function, like this:
#include <iostream>
void histogram(int const size, int const * const arr, unsigned int const number_of_bins, float const bin_min, float const bin_max, int * output)
{
float const binsize = (bin_max - bin_min)/number_of_bins;
for (int i = 0; i < size; i++)
{
for(int j = 0; j < number_of_bins; ++j)
{
if (arr[i] >= bin_min + binsize*j && arr[i] < bin_min + binsize*(j+1))
{
output[j]++;
}
}
}
}
int main(){
int const number_of_bins = 10;
float const bin_min = 0;
float const bin_max = 100;
int const size = 20;
int const array[size] = {5,6,20,40,44,50,110,6,-1,51,55,56,20,50,60,80,81,0,32,3};
int bin[number_of_bins] = {};
histogram(size, array, number_of_bins, bin_min, bin_max, bin);
for(int i = 0; i < number_of_bins; ++i)
{
std::cout << i << "|";
for (int j = 0; j < bin[i]; j++)
{
std::cout << "*";
}
std::cout << std::endl;
}
}
Compiled with:
g++ main.cc -o Output
Output:
0|*****
1|
2|**
3|*
4|**
5|*****
6|*
7|
8|**
9|
(Bonus, your bugs are fixed)
First of all your program is incorrect since, as pointed out, you return a pointer to a local variable form a function. To correct this you should use either std::array<Type, Size> or std::vector<Type>.
Regarding your question if you want short and compact code try this:
#include <string>
#include <algorithm>
#include <iostream>
#include <array>
std::array<int, 10> bin;
// Fill your array here
int i = 0;
std::for_each(bin.begin(), bin.end(), [&i](auto x)
{
std::cout << i++ << "|" << std::string(x, '*') << std::endl;
});
This code takes advantage of fill constructor of std::string which avoids your for cycle. But since you want to iterate through the array you need to do it in one way or the other. Either by an explicit for or by calling another function.
Note: this code is less efficient than a standard for loop but your question is how to avoid these.
I have made this code that should build two vectors, one with the integers up to 100 and the other with the squares of these integers, and would like to write two columns so that the values line up in two columns. The program compiles ok, but the output is empty, i.e., nothinkg appears but only the message "Process returned 0 (0x0)". What exactly am I missing here?
#include <iostream>
#include <cmath>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
vector<int> numbers;
typedef vector<int>::size_type vec_sz;
vec_sz size = numbers.size();
for (vec_sz i = 0; i != numbers.size(); ++i)
{
numbers.push_back(i);
}
vector<int> squares;
for (vec_sz i = 0; i!= squares.size(); i++)
{
squares.push_back(i^2);
}
for (vec_sz i = 0; i != numbers.size(); ++i)
{
cout << setw(3)
<< numbers[i]
<< setw(6)
<< squares[i]
<< endl;
}
return 0;
}
When you write this line at the beginning of your main function,
vec_sz size = numbers.size();
you want to obtain the size of the vector. However, numbers is empty, it does not contain any data. Hence size will be 0. Here numbers.size() is going to return 0.
Hence for (vec_sz i = 0; i != numbers.size(); ++i) will not execute even once.
Let's say that you want to fill numbers, then you should know how many values do you want to fill in numbers. Once you know this value, store it in a variable let's say count.
Sample:
const int count = 10;
for (int i = 0; i < count; ++i) {
numbers.push_back(i);
}
// now numbers.size() will return 10;
Same goes for your squares vector.
I recently started to learn C++ programing, and watched many of your posts and answers with interest when my mind would lack the creativity. I have a few issues with this code right here. Basically it should show "n" words in alphabetical order. "n" being introduce by the user and the words as well. I get a weird error, could someone give me a few hints on what should i do?
#include <iostream>
#include <vector>
#include <string>
int main () {
int n=0;
std::string cuvant;
std::vector<std::string> lista_cuvinte;
std::cout<<" Cate cuvinte doriti sa comparati = "<< std::endl;
std::cin>> n;
for (int i=0; i<n; i++)
{
std::cout<<"cubantul al " << i + 1 <<" -lea = ";
std::cin>> cuvant;
lista_cuvinte.push_back(cuvant);
for (int i=0; i < n; i++)
{
for (int j=i + 1; j < n; j++)
{
if (lista_cuvinte.at(i) > lista_cuvinte.at(j))
{
std::string temp=lista_cuvinte.at(i);
lista_cuvinte[i]=lista_cuvinte.at(j);
lista_cuvinte[j]=temp;
i=i-1;
break;
std::cout<< temp << std::endl;
}
}
}
}
return 0;
}
You are doing a lot things wrong. Simply sorting starts before all data was read in in your code. Code after a break will never executed. And there is no output.
But you can achieve the same result much simpler by using sort from algorithm. I believe your code is only for learning, so it maybe makes sense to do it by hand. Normally it does not :-)
#include <iostream>
#include <vector>
#include <string>
int main () {
int n=0;
std::string cuvant;
std::vector<std::string> lista_cuvinte;
std::cout<<" Cate cuvinte doriti sa comparati = "<< std::endl;
std::cin>> n;
// read data
for (int i=0; i<n; i++)
{
std::cout<<"cubantul al " << i + 1 <<" -lea = ";
std::cin>> cuvant;
lista_cuvinte.push_back(cuvant);
}
// sort data
for (int i=0; i < n; i++)
{
for (int j=i + 1; j < n; j++)
{
if (lista_cuvinte.at(i) > lista_cuvinte.at(j))
{
std::string temp=lista_cuvinte.at(i);
lista_cuvinte[i]=lista_cuvinte.at(j);
lista_cuvinte[j]=temp;
i=i-1;
break;
}
}
}
// output data
for (int i=0; i<n; i++)
{
std::cout << lista_cuvinte[i] << std::endl;
}
return 0;
}
And with std::sort your code in the section sorting reduces to:
// sort data
std::sort( lista_cuvinte.begin(), lista_cuvinte.end());
Thats all!
As a hint to you for writing and finding errors in general: Please use a debugger. Your code simply throws an exception. Your debugger will catch it for you and you go in the backtrace to the point where the error occurs. In your code it was an access out of range from the array, because the data was not read in at this point of execution.
You are starting sorting before completing the input of the words. Your second for (int i=0... loop is inside your first one.
I'm writing a program which is intended to compare the numbers in 2 arrays and output the number of matches that there are.
RandomNumber.h
#pragma once
#include <iostream>
#include <cstdlib>
#include <ctime>
class RandomNumber
{
public:
void randomNumber();
int actualRandomNumber;
};
RandomNumber.cpp
#include "RandomNumberGenerator.h"
void RandomNumber::randomNumber()
{
actualRandomNumber = rand() % 66 + 1;
}
Game.h
#include "RandomNumberGenerator.h"
class Game
{
private:
int randomNumbers[6];
public:
void generateRandomNumbers();
void compareNumbers2();
};
Game.cpp
void Game::generateRandomNumbers()
{
RandomNumber create;
for (int i = 0; i < 6; i++)
{
create.randomNumber();
randomNumbers[i] = create.actualRandomNumber;
}
for (int i = 0; i < 6; i++)
{
std::cout << randomNumbers[i] << " ";
}
}
void Game::compareNumbers2()
{
int k = 0;
for (int i = 0; i < 6; ++i)
{
for (int j = 0; j < 6; ++j)
{
if (randomNumbers[i] == randomNumbers[j])
{
k++;
}
}
}
if (k > 0)
{
std::cout << "Congratulations you matched: " << k << " number(s)";
}
if (k == 0)
{
std::cout << "Unfortunatly you matched: " << k << " numbers";
}
}
Main.cpp
#include "Game.h"
#include "RandomNumberGenerator.h"
int main()
{
Game play;
srand (time(NULL));
play.generateRandomNumbers();
std::cout << std::endl << std::endl;
play.generateRandomNumbers();
std::cout << std::endl << std::endl;
play.compareNumbers2();
system("pause");
return 0;
}
The problem I'm having isn't in creating the arrays and filling them, I get two filled arrays with 2 different sets of random numbers, but for some reason when comparing them the number of matches it tells me I have is always about 6 or 8 when I in fact rarely have more than one or two if that.
The most obvious problem is that you only have one array.
class Game
{
...
int randomNumbers[6];
Where did you think the second array was?
Based on your code, I saw only 1 array. And in the function compareNumber2(), you compare each number with it once. Therefore, the result is the number of elements (e.g, 6).
Looking at code, I can say you will be getting 6 matches all the time, since you randomNumbers array will be overwritten in second step (when you try to generate random numbers second time)
There are actually two problems bigger and smaller:
You're comparing your array int randomNumbers[6] with itself.
Please don't call the object create. Its very wrong habit. Call the object of class RandomNumber i.e a randomNumber and take your random number from it like:
randomNumber.getValue()
Usually try to call the methods with verbs and objects with nouns it will be more natural don't you think?
You do no not compare two arrays. You compare one array, data member of class Game, with itself. You simply fill it two times.