I am currently trying to create a program in c++ that will allow a user to fill in a text file to define variables for a graph, these variables define the distance between nodes in the graph. The format is as follows:
int numberOfNodes
//node 0, node 1 , node 2
float distance1, distance2, distance3 //node 0
float distance1, distance2, distance3 //node 1
float distance1, distance2, distance3 //node 2
(number of nodes being 3) which is why there is a 3x3 grid, which would specify the distance between each node.
for contect:
filedata.txt
3
0 1 2
1 0 3
2 3 0
I understand that to use file input you use fstream, along with ifstream to select the file to open. What I dont understand is how to put this data into context.
How do i tell c++ that the first line will always be how many nodes there are in the list, then how would I tell c++ that anything under that first line is the data I want to fill into their own lists?
while (infile >> size)
{
cout <<"Total number of Verticies in Graph = "<< size << endl;
}
With input like that:
3
First read the number of rows, and go into a for loop:
infile >> numrows;
for(int row = 0; i < numrows; ++i) {
}
The subsequent input can be read as
0 1 2
1 0 3
2 3 0
infile >> distance1 >> distance2 >> distance3;
inside of the loop.
Related
I am currently trying to solve this kattis problem in C++:
Ecape Wall Maria
Wall Maria has been broken! Eren must evacuate as soon as possible from his house. He must find the fastest route to escape within Wall Maria before the titans rush in. Wall Maria is represented as a N×M grid in which Eren can move horizontally or vertically.
There are burning houses and buildings which prevent Eren from passing through them. The burning houses and buildings are represented as ‘1’. Unburned or safe areas are represented as ‘0’. There are some areas which can be entered but only from a specific direction. These areas can be represented by either ‘U’, ‘D’, ‘L’, or ‘R’. For example, if there is an ‘R’ that means that area can only be entered from the right neighboring tile within Wall Maria’s grid. Similarly, ‘U’ tiles can only be entered from above, ‘D’ tiles can only be entered from below, and ‘L’ tiles can only be entered from the left.
Eren knows the time t at which the titans will rush in. It takes 1 unit of time to traverse 1 zone (which corresponds to 1 tile in the grid). Once he reaches any border of Wall Maria he is safe.
Eren’s starting position is represented by the letter ‘S’. If Eren escapes at or before time t, he is safe. Given his position within Wall Maria determine if it is possible to escape. If it is possible determine the number of zones that must be traversed to lead to the quickest escape.
Input
The input consists of a single test case. The first line contains three integers t (1≤t≤200) , N (1≤N≤100) and M (1≤M≤100). The rest of N lines will be Wall Maria’s grid containing characters ‘1‘, ‘0‘, ‘S‘, ‘U‘, ‘D‘, ‘L‘, or ‘R‘. There is exactly one ‘S‘ in the input.
Output
If it is possible to escape Wall Maria, output the minimum number of zones that must be traversed to escape. If it is not possible to escape, print “NOT POSSIBLE”!
I am having some issues with finding the character "S" in the matrix on input.
I am thinking that once we have the input of the matrix, we find the character "S" and then look to the right, left, up and down of that character. If the character is not = 1 then you repeat the process from that character until you have "left" the matrix.
However, I have tried writing code to look for the starting point (the character "S) but I have been unsuccessful in doing that.
Furthermore, I am not sure how to look around the character once I have found it. I have only gotten to the point where I can accept input, not much further. Help would be appreciated
This is my code so far:
int main(){
int M;
int N;
int t;
string wall;
cin >> t >> N >> M;
//Takes the matrix input
for (int i = 0; i < N; i++)
{
cin >> wall;
}
}
The two steps are:
Decide what data structure you want to use to represent the grid you're about to traverse. std::vector<std::string> is a standard choice here.
Read the grid into the vector line by line, storing the row and column for 'S' as you go.
Here's one approach:
#include <iostream>
#include <string>
#include <vector>
int main() {
int M;
int N;
int t;
int sx = 0;
int sy = 0;
std::cin >> t >> N >> M;
std::vector<std::string> grid(N);
for (int i = 0; i < N; i++) {
std::cin >> grid[i];
size_t pos = grid[i].find("S");
if (pos != std::string::npos) {
sx = pos;
sy = i;
}
}
// show the position; remove when you're ready to solve the problem
std::cout << sx << ", " << sy << "\n";
}
Here's the output on two of the samples:
$ ./a
1 4 4
1S01
1001
1011
0U11
1, 0
$ ./a
2 4 4
1111
1S01
1011
0U11
1, 1
Problem
Finally, progress reached the Madoka family and she decided to play with her little sister in the sensational game Space Arrays.
The rules of the game are as follows:
Initially, a sequence a1,a2,…,aN is given.
The players alternate turns.
In each turn, the current player must choose an index i and increment ai, i.e. change ai to ai+1.
Afterwards, if there is no permutation p1,p2,…,pN of the integers 1
through N such that ai≤pi holds for each valid i, the current player
loses.
Otherwise, the game continues with the next turn.
Madoka is asking you to help her ― tell her if the first player (the player that plays in the first turn) or second player wins this game if both play optimally.
Input
The first line of the input contains a single integer T denoting the
number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N.
The second line contains N space-separated integers a1,a2,…,aN.
Output
For each test case, print a single line containing the string "First" if the first player wins or "Second" if the second player wins (without quotes).
Constraints
1≤T≤2⋅10^4
1≤N≤2⋅10^5
The sum of N over all test cases doesn't exceed 2⋅10^5
1≤ai≤N for each valid i
Subtasks
Subtask #1 (100 points): Original constraints
Example Input
4
4
1 2 3 3
4
1 1 3 3
5
1 2 2 1 5
3
2 2 3
Example Output
First
Second
Second
Second
Explanation
Example case 1:
If the first player increases the fourth element, the resulting sequence is (1,2,3,4).The second player loses after increasing any of the elements.
If the first player increases the second element, the resulting
sequence is (1,3,3,3) ,and he loses because there is no valid
permutation. For example if p=(2,1,4,3), the second element of a is
greater than the second element of p.
Time Limit : 1 Secs
Source limit : 50000 byte
Here is my code
#include <bits/stdc++.h>
using namespace std;
#define lli long long int
int main() {
// your code goes here
lli t;
cin >> t;
while(t--){
lli n;
cin >> n;
int arr;
int arrSum = 0;
for(lli i=0; i<n ;i++){
cin >> arr;
arrSum += arr;
}
lli turn = 0;
lli sum = (n*(n+1))/2;
turn = sum-arrSum;
if(turn < 0){
turn = 0;
}
if(turn%2 == 1){
cout << "First" << endl;
}
else{
cout << "Second" << endl;
}
}
return 0;
}
In your algorithm you don't check if first player initially loses without making a turn but the sum is lower than n*(n+1)/2, e.g. for input
1
5
1 1 2 5 5
The sum is 13.
5 * (5 + 1) / 2 - (1 + 1 + 2 + 5 + 5) == 1
But first player can't do anything and has lost before the first turn. Ssecond player wins.
Actual output from your code: First.
Expected output: Second
Another example is
1
5
1 1 4 4 4
with
5 * (5 + 1) / 2 - (1 + 1 + 4 + 4 + 4) == 1
In both cases your code returns that first player wins but actually second player wins without the game even starting.
I am writing a program which is reading in an array from a text file which has both normal integers, and also multiple numbers that are in scientific notation, of the form: #.#####E##. Here is a few sample lines of the input .txt file:
21 -1 0 0 501 502 0.00000000000E+00 0.00000000000E+00 0.17700026409E+03 0.17700026409E+03 0.00000000000E+00 0. -1.
21 -1 0 0 502 503 0.00000000000E+00 0.00000000000E+00 -0.45779372796E+03 0.45779372796E+03 0.00000000000E+00 0. 1.
6 1 1 2 501 0 -0.13244216743E+03 -0.16326397666E+03 -0.47746002227E+02 0.27641406353E+03 0.17300000000E+03 0. -1.
-6 1 1 2 0 503 0.13244216743E+03 0.16326397666E+03 -0.23304746164E+03 0.35837992852E+03 0.17300000000E+03 0. 1.
And here is my program which simply reads in the text file and puts it into an array (or more specifically, a vector of vectors):
vector <float> vec; //define vector for final table for histogram.
string lines;
vector<vector<float> > data; //define data "array" (vector of vectors)
ifstream infile("final.txt"); //read in text file
while (getline(infile, lines))
{
data.push_back(vector<float>());
istringstream ss(lines);
int value;
while (ss >> value)
{
data.back().push_back(value); //enter data from text file into array
}
}
for (int y = 0; y < data.size(); y++)
{
for (int x = 0; x < data[y].size(); x++)
{
cout<<data[y][x]<< " ";
}
cout << endl;
}
// Outputs the array to make sure it works.
Now, this code works beautifully for the first 6 columns of the text file (these columns are entirely integers), but then it completely ignores every column 6 and higher (these are the columns containing scientific notation numbers).
I have tried redefining the vectors as both types double and float, but it still does the same thing. How can I get C++ to recognize scientific notation?
Thanks in advance!
Change int value; to double value; and also change your vector to double instead of int.
Better yet, since you have three declarations that must all be synchronized to the correct type, make an alias to that type like this: using DATA_TYPE = double; then declare your vectors and such like this: vector<vector<DATA_TYPE> > data;, DATA_TYPE value;, etc. That way if you change the type of the data for whatever reason, all your vector and variable declarations will update automatically, thus avoiding these kinds of bugs.
**EDIT: I got it to work by changing the 'inStream >> next' to 'inStream >> skipws >> next'. In one of my earlier functions (to pull the last and first name) I had toggled noskipws. Apparently that toggle lasts between functions?
I have a program that is part of an assignment that is supposed to read a text file that is set up in the format of: "lastname firstname 1 2 3 4 5 6 7 8 9 10" (where each of the 10 numbers are integer scores).
I am able to read in the lastname and firstname fine, but when I go to start reading in the numbers, I am only able to read in the first one and then all the rest get set to 0.
Below is the function that is supposed to read the scores in. inStream has already had the lastname and firstname taken off. The textfile I am using has one line:
Tosis Halley 85 23 10 95 43 12 59 43 20 77
When run the program and print out the student.score values from 0 to 9, the first one displays correctly as '85' but all the reset show as '0'. Thoughts?
void GetScores (ifstream& inStream, record& student)
{
int score[10] = {-1, -1, -1, -1 ,-1 ,-1 ,-1 ,-1 ,-1 ,-1};
int next;
int counter = 0;
string test;
for (int i = 0; i < 10; i++)
{
inStream >> next;
student.score[i] = next;
}
}
Assuming the input is indeed all numbers, the function should actually work. However, you should always verify that inputs were indeed read correctly:
for (int i = 0; i != 10 && inStream >> next; ++i) {
student.score[i] = next;
}
if (!inStream) {
std::cout << "an input error occured\n";
}
I am trying to write data from a 2D array into a binary file. I am only writing the data that has a value greater than 0. Therefore, if the data is is 0, it will not be written to the file. The data is as follows:
Level 0 1 2 3 4 5
Row 0 4 3 1 0 2 4
Row 1 0 2 4 5 0 0
Row 2 3 2 1 5 2 0
Row 3 1 3 0 1 2 0
void {
// This is what i have for writing to file.
ofstream outBinFile;
ifstream inBinFile;
int row;
int column;
outBinFile.open("BINFILE.BIN", ios::out | ios::binary);
for (row = 0; row < MAX_ROW; row++){
for (column = 0; column < MAX_LEVEL; column++){
if (Array[row][column] != 0){
outBinFile.write (reinterpret_cast<char*> (&Array[row][column]), sizeof(int)
}
}
}
outBinFile.close();
// Reading to file.
inBinFile.open("BINFILE.BIN", ios::in | ios::binary);
for (row = 0; row < MAX_ROW; row++){
for (column = 0; column < MAX_LEVEL; column++){
if (Array[row][column] != 0){
inBinFile.read (reinterpret_cast<char*> (&Array[row][column]), sizeof(int)
}
}
}
inBinFile.close();
}
All the data being read is being inserted into the first row, how can i get the data to load as i exited the program?
You are reading only when data is not equal zero, means that it gets locked with first zero. Once it reaches zero it stops reading.
Before "if command" read file to some other varaible then in if (variable != 0) Array[row][column] = variable.
If your Array is initialized with data, maybe take a look into setting position of your reading. So to set ok I have zero, I should read from another position next.
Binary files take a simple memory dump. I'm on a mac so I had to find a way to calculate the size of the array since sizeof(array name) doesn't return the memory size of the array for some reason (macintosh, netbeans IDE, xCode compiler). The workaround I had to use was:
to write the file:
fstream fil;
fil.open("filename.xxx", ios::out | ios::binary);
fil.write(reinterpret_cast<char *>(&name), (rows*COLS)*sizeof(int));
fil.close();
//note: since using a 2D array &name can be replaced with just the array name
//this will write the entire array to the file at once
Reading was the same. Since the examples from the Gaddis book I was using did not work correctly on Macintosh I had to find a different way to accomplish this. Had to use the following code snippet
fstream fil;
fil.open("filename.xxx", ios::in | ios::binary);
fil.read(reinterpret_cast<char *>(&name), (rows*COLS)*sizeof(int));
fil.close();
//note: since using a 2D array &name can be replaced with just the array name
//this will write the entire array to the file at once
Instead of just getting the size of the entire array you need to calculate the size of the entire array by multiplying the rows*columns for a 2d array then multiplying it by the size of the data type (since I used integer array it was int in this case).