Retrieving and manipulating data from file - file-io

The following code is supposed to retrieve the data related to the players info, sort it out and then rewrite the file now organized. Going to give an example of the files.
Original layout:
3
2 2
John 33 M 5
Anna 20 F 2
Rody 23 M 1
What it has to look like after the code:
3
2 2
Rody 23 M 1
Anna 20 F 2
John 33 M 5
I made the following code:
vector<string> playerScoresFromFile(const string filename) //Gets each one of those lines with the name, ..., and score of the person
{
int dim = filename[7] - '0'; // char to integer
vector<string> vec;
string line;
ifstream fin (filename.c_str());
for (int i = 0; i < dim + 1; i++)
{
getline(fin, line);
}
while(! fin.eof())
{
getline(fin, line);
vec.push_back(line);
}
return vec;
}
vector< vector<int> > readBoardFromFile(const string filename) //gets the board from the file (first 3 numbers)
{
int dim = filename[7] - '0'; // char to integer
string line;
vector< vector<int> >vec(dim, vector<int>(dim));
ifstream fin (filename.c_str());
int i = 0;
int j, k;
while(i < dim)
{
getline(fin, line);
int sizeOfLine = line.length();
if (line[0] == '\0')
{
break;
}
else
{
for (j = 0, k = 0; j < (sizeOfLine / 3); j++, k += 3)
{
string elementOfVectorStr = (line.substr(k,3));
int elementOfVectorInt = stringToInt(elementOfVectorStr);
if (abs(elementOfVectorInt) > 100) // when the element is a " ", the corresponding integer is always
{ // a very large number, positive or negative
elementOfVectorInt = 0;
}
vec[i][j] = elementOfVectorInt;
}
}
i++;
}
return vec;
}
vector<string> sortPlayersByTime (vector<string> &vec) // Creates a substring of the string extracted by "playerScoresFromFile" and analyses the times (Which are the last numbers to the right)
{
vector<int> timesInt(vec.size());
for (size_t i = 0; i < vec.size(); i++)
{
string str = vec[i];
timesInt[i] = stringToInt(str.substr(26));
}
for (size_t i = 0; i < vec.size() - 1; i++)
{
if(timesInt[i] > timesInt[i+1])
{
swap(vec[i], vec[i+1]);
}
}
return vec;
}
bool isOrdered (const vector<string> vec) //Checks if the vector is ordered
{
vector<int> timesInt(vec.size());
for (size_t i = 0; i < vec.size(); i++)
{
string str = vec[i];
timesInt[i] = stringToInt(str.substr(26));
}
for (size_t i = 0; i < vec.size() - 1; i++)
{
if(timesInt[i] > timesInt[i+1])
{
return false;
}
}
return true;
}
void writeBoardToFile(vector< vector<int> >&vec, string filename) //Rewrites the board to the file (Those first 3 numbers of the file)
{
ofstream fout(filename.c_str());
for (size_t i = 0; i < vec.size(); i++)
{
for (size_t j = 0; j < vec.size(); j++)
{
if(vec[i][j] != 0)
{
fout << setw(3) << vec[i][j];
}
else
{
fout << setw(3) << " ";
}
}
fout << endl;
}
fout << endl;
}
void vec_to_file(vector<string> vec, string filename) //Rewrites the vector to the file
{
ofstream fout(filename, ios::app);
for (int i = 0; i < vec.size(); i++)
{
fout << vec[i] <<endl;
}
}
void displayFile (string filename) //Displays the final board to check if it worked
{
vector<string> vec;
string line;
ifstream myfile (filename);
while ( ! myfile.eof() )
{
getline (myfile, line);
vec.push_back(line);
}
for (size_t i = 0; i < vec.size(); i++)
{
cout << vec[i] <<endl;
}
}
int main()
{
vector< vector<int> > vec = readBoardFromFile("puzzle_2x2_001.txt");
vector<string> vecxz = playerScoresFromFile("puzzle_2x2_001.txt");
writeBoardToFile(vec, "puzzle_2x2_001.txt"); //Writes the board to the file
while (! isOrdered(vecxz)) //This loop should run while they haven't been sorted out, but the program crashes here and I have no idea why.
{
sortPlayersByTime(vecxz);
}
//vec_to_file(vecxy, "puzzle_2x2_001.txt"); //Should write the vector to the file upon sorting them out successfully.
cin.get();
}
My problem is the program crashes everytime it gets to the while(! isOrdered(vecxz)) loop but I have no idea why. Can anyone give me a hand? I'd be thankful :)

Related

I get garbage value on this jagged array

I get garbage value on this jagged array, that takes input size from another array's last value which must be -111(if not ten add one index to put in -111).
i know i have missed some cout statements but dont know why i get garbage vals
'''
int jaggedArr(int** arr2, int r, int c)
{
int* numbers = nullptr;
numbers = new int[r]; /// array to store no of columns
int** jagArr = new int* [r]; /// jagged array
for (int i = 0; i < r; i++)
{
int tempNum;
for (int j = 0; j < c; j++)
{ //store size of cols in arr4 to put int new array (arr3)
if (arr2[i][j] == -111)
{
tempNum = j;
numbers[i] = tempNum;//if -111 is present then dont change size just copy
}
else if (arr2[i][j] != -111)
{
tempNum = j + 1;
numbers[i] =tempNum;//else if -111 is not present then dont change size just copy
}
tempNum = 0;
}
}
for (int i = 0; i < r; i++)
{
jagArr[i] = new int[numbers[i]];
}
for (int i = 0; i < r; i++)
{
for (int j = 0; j < 10; j++)//remove 10
{
jagArr[i] = new int[numbers[i]];
}
}
cout << "Showing all the Inputed data in a matrix form" << endl;
for (int i = 0; i < r; i++) {
for (int j = 0; j < numbers[i]; j++)
{
//if (jagArr[i][j] >= 0 && jagArr[i][j] <= 9)
//{
// cout << jagArr[i][j] << " |";
//}
//else if (jagArr[i][j] == -111)
//{
// cout << jagArr[i][j] << "|";
//}
//else
//{
// cout << jagArr[i][j] << " |";
//}
cout << jagArr[i][j];
}
cout << "\n";
}
return **arr2;
}
'''

How I can sort an ArrayList of int arrays?

I have this code. I'm dealing with the N-Queen problem.
The problem is when I wanna show results by screen, the arrays are not ordered. But in this code I can't order them using Comparator. It's very strange because in other Class it works perfectly using Comparator, but here it doesn't work. Hope anyone could help me. Thanks in advance.
import java.util.*;
public class NReinas {
public static void resolverReinas(int n){
String[][] tablero;
tablero = generarTablero(n);
ubicarReina(tablero, 0, n);
}
public static void ubicarReina(String[][] tablero, int etapa, int n){
ArrayList <int[]> resultados = new ArrayList<>();
for(int i = 0; i < tablero.length; i++){
if(isValido(tablero, i, etapa)){
tablero[i][etapa] = "R";
if(etapa < tablero.length - 1){
ubicarReina(tablero, etapa + 1, n); //Recursividad
}else {
resultados.add(devolverSolucion(tablero, n));
}
tablero[i][etapa] = " "; //Backtracking: vaciamos el tablero
}
}
//The ArrayList I want to order by int arrays
for (int[] r : resultados) {
System.out.println(Arrays.toString(r));
}
}
public static boolean isValido(String[][] tablero, int i, int etapa){
for(int x = 0; x < etapa; x++){
if(tablero[i][x].equals("R")){
return false;
}
}
for(int j = 0; j < tablero.length && (i-j) >= 0 && (etapa-j) >=0; j++){
if(tablero[i - j][etapa - j].equals("R")){
return false;
}
}
for(int j = 0; j < tablero.length && (i + j) < tablero.length && etapa - j >= 0; j++){
if(tablero[i + j][etapa - j].equals("R")){
return false;
}
}
return true;
}
public static String[][] generarTablero(int length){
String[][]res = new String[length][length];
for (int i = 0; i < res.length; i++) {
for (int j = 0; j < res.length; j++) {
res[i][j] = " ";
}
}
return res;
}
public static int[] devolverSolucion(String[][] tablero, int n){
int[] solucion = new int[n];
for (int i = 0; i < tablero.length; i++) {
for (int j = 0; j < tablero.length; j++) {
if(tablero[i][j] == "R"){
solucion[i] = j;
}
}
}
return solucion;
}
}
Try Using Integer instead of int and save array values on List instead, so you can use sort them
List<Integer> list = Arrays.asList(solucion);
Collections.sort(list);
If you insist in using and array you can reconverti the list to an array
(Integer[]) list.toArray();

How is it possible to randomly remove an element from vector< vector<short> >?

Below is a Sudoku initializer, I am attempting to create a function that based on User input, erases a random element from the the board. The random element can be removed from any part of the board.
class cell{
bool m_occu; //occupied is shown '.'
int m_num;
public:
cell() : m_occu(false), m_num(0) {}
void setMark(const int num){m_num = num; m_occu = true;}
bool isMarked() const { return m_occu; }
int getNum(){ return m_num;}
friend ostream& operator << (ostream& o, const cell& c){
if (!c.m_occu) return o << setw(2) << '-';
return o << setw(2) << c.m_num;
}
};
class board {
vector<vector <cell> >m_map;
bool col_row;
public:
board() {
vector<cell> a_row(9);
col_row = false;
for (int i = 0; i < 9; ++i)
{
for(int j = 0; j < 9; j++)
{
a_row[j].setMark(j+1);
}
random_shuffle(a_row.begin(), a_row.end());
m_map.push_back(a_row);
}
}
void erase(){
}
Here is the code for erase function:
void erase(std::vector your_vector){
your_vector.erase(your_vector.begin() + random(1,your_vector.size()));
}
and this the code for random number generation:
int random(int min, int max) //range(min, max)
{
bool first = true;
if ( first )
{
srand(time(NULL)); //seeding only for the first time
first = false;
}
return min + rand() % (max - min);
}

ArrayList Method Returns a null ArrayList, main program cannot access

I'm trying to create a basic function that calls on a method that creates the 2D ArrayList that will be used further in the main program to do things like calculate the row and column sums as well as print out the triangle.
However, after it runs the ArrayList returns null. What's going on?
Thanks,
public class Trib
{
private ArrayList<ArrayList<Integer>> triangle;
private int Asize;
public Trib (int size)
{
// convert the argument to type 'int' to be used in the program
Asize = size;
// create an ArrayList of ArrayLists, it will have 'size' number ArrayLists contained within
ArrayList<ArrayList<Integer>> triangle = new ArrayList<ArrayList<Integer>>(size);
// create the inner ArrayLists
for (int i = 0; i < size; i++)
{
// add to index 'i' of our ArrayList a new ArrayList of size (i+1)
triangle.add(new ArrayList<Integer>(i+1));
for (int j = 0; j <= i; j++)
{
if (j==0 || j == i)
{
triangle.get(i).add(1);
}
else
triangle.get(i).add(triangle.get(i-1).get(j-1)+triangle.get(i-1).get(j));
System.out.print(triangle.get(i).get(j) + " ");
}
System.out.println();
}
triangle.clone();
}
public void printTriangle()
{
System.out.print(triangle.get(1).get(1));
/*for (int i = 0; i < Asize; i++)
{
for (int j = 0; j <= i; j++)
{
System.out.print(triangle.get(1).get(1) + " ");
}
System.out.println();
}*/
}
/*public Trib()
{
this(5);
}*/
/*public int Psize()
{
return triangle.size();
}
public ArrayList<Integer> sumRows()
{
ArrayList<Integer> row_sum = new ArrayList<Integer>(Asize);
for (int i = 0; i < Asize; i++)
{
for (int j = 0; j < i; j++)
{
row_sum.add(triangle.get(i).get(j));
}
}
return row_sum;
}
public ArrayList<Integer> sumCols()
{
ArrayList<Integer> col_sum = new ArrayList<Integer>(Asize);
for (int i = 0; i < Asize; i++)
{
for (int j = 0; j < i; j++)
{
col_sum.add(triangle.get(i).get(i));
}
}
return col_sum;
}*/
public static void main(String[] args)
{
if(args.length < 1)
{
System.err.println("Sorry, this program needs an integer argument.");
System.exit(1);
}
Trib pt = new Trib(Integer.parseInt(args[0]));
pt.printTriangle();
//ArrayList<Object> sum_rows = new ArrayList<Object>(pt.Psize());
// sum_rows.add;
System.out.println("\nHere are the sum of rows:");
//for (int i = 0; i < pt.Psize(); i++)
//System.out.println(sum_rows.get(i));
//ArrayList<Integer> sum_cols = new ArrayList<Integer>(pt.Psize());
System.out.println("\nHere are the sum of columns:");
//for (int i = 0; i < pt.Psize(); i++)
//System.out.printf("%-5d", sum_cols.get(i));
}
}
Watch out what's what you are doing: Notice that you have TWO variables named "triangle": The first one is an instance variable and the second is a local variable, which is the only one you have initialized.
My suggestion to avoid this common mistake is to pre-pend "this." to any use of what you intend must be an instance variable. And, if in doubt, if you use a development environment as Eclipse, press CTRL and click on your variable to navigate to the point where it is declared.

Finding all cycles in directed graphs of length <= k

Is there a way of modifing the algorithm in
Finding all cycles in undirected graphs
to consider edges as directed and only cycles of length <= k ?
I reply by myself
static void Main(string[] args)
{
int k = 4;
for (int i = 0; i < graph.GetLength(0); i++)
for (int j = 0; j < graph.GetLength(1); j++)
{
findNewCycles(new int[] { graph[i, j] },k);
}
foreach (int[] cy in cycles)
{
string s = "" + cy[0];
for (int i = 1; i < cy.Length; i++)
s += "," + cy[i];
Console.WriteLine(s);
}
}
static void findNewCycles(int[] path, int k)
{
int n = path[0];
int x;
int[] sub = new int[path.Length + 1];
if (path.Length < k + 1)
{
for (int i = 0; i < graph.GetLength(0); i++)
for (int y = 0; y <= 1; y = y + 2)
if (graph[i, y] == n)
// edge referes to our current node
{
x = graph[i, (y + 1) % 2];
if (!visited(x, path))
// neighbor node not on path yet
{
sub[0] = x;
Array.Copy(path, 0, sub, 1, path.Length);
// explore extended path
findNewCycles(sub,k);
}
else if ((path.Length > 2) && (x == path[path.Length - 1]))
// cycle found
{
int[] p = normalize(path);
int[] inv = invert(p);
if (isNew(p) && isNew(inv))
cycles.Add(p);
}
}
}
}
static bool equals(int[] a, int[] b)
{
bool ret = (a[0] == b[0]) && (a.Length == b.Length);
for (int i = 1; ret && (i < a.Length); i++)
if (a[i] != b[i])
{
ret = false;
}
return ret;
}
static int[] invert(int[] path)
{
int[] p = new int[path.Length];
for (int i = 0; i < path.Length; i++)
p[i] = path[path.Length - 1 - i];
return normalize(p);
}
// rotate cycle path such that it begins with the smallest node
static int[] normalize(int[] path)
{
int[] p = new int[path.Length];
int x = smallest(path);
int n;
Array.Copy(path, 0, p, 0, path.Length);
while (p[0] != x)
{
n = p[0];
Array.Copy(p, 1, p, 0, p.Length - 1);
p[p.Length - 1] = n;
}
return p;
}
static bool isNew(int[] path)
{
bool ret = true;
foreach (int[] p in cycles)
if (equals(p, path))
{
ret = false;
break;
}
return ret;
}
static int smallest(int[] path)
{
int min = path[0];
foreach (int p in path)
if (p < min)
min = p;
return min;
}
static bool visited(int n, int[] path)
{
bool ret = false;
foreach (int p in path)
if (p == n)
{
ret = true;
break;
}
return ret;
}
}