How I can sort an ArrayList of int arrays? - arraylist

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();

Related

What is the Time Complexity and Space complexity of the following codes?

Here are the codes attached below. I have done these problems in one of the FAANG companies. I am open to have a discussion on time complexity and space complexity of these codes.
Code1:
public static void main(String[] args) {
int[] arr = {4,5,6,7};
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < arr.length; i++) {
queue.add(arr[i]);
}
System.out.println(queue);
while (queue.size() > 2) {
int first = queue.poll();
for (int i = 0; i < queue.size(); i++) {
int second = queue.poll();
queue.add(first % 10 + second % 10);
first = second;
}
}
int first = queue.poll() % 10;
int second = queue.poll() % 10;
int res = first + second;
System.out.println(res);
}
Time Complexity: ?
Space Complexity: ?
and Code 2:
public static void main(String[] args) {
String input = "aabbcaac";
HashMap<Character, Integer> map1 = new HashMap<>();
HashMap<Character, Integer> map2 = new HashMap<>();
char[] ip = input.toCharArray();
for (int i = 0; i < ip.length; i++) {
map2.put(ip[i], map2.getOrDefault(ip[i] , 0)+1);
}
System.out.println (map2);
int currVal = 0;
int result = 0;
int k = 1;
for (char str : ip) {
map2.put(str, map2.get(str) - 1);
if (map2.get(str) > 0) {
currVal += 1;
}
if(map1.get(str) == null) {
map1.put(str, 0);
}
if (map1.get(str) > 0) {
currVal -= 1;
}
map1.put(str, map1.get(str) + 1);
if (currVal > k) {
result += 1;
}
System.out.println(currVal);
}
System.out.println(result);
}
Time Complexity: ?
Space Complexity: ?

How to access the values of a dictionary property in a grid using Ocean for Petrel?

I'm tring to access the values of a dictionary property in a grid,such as Fluvial facies or lithologies etc.I have read the coursebook and help docs, but didn't find anything relevant.The coursebook only has examples of creating properties, but not accessing properties.Below is the code I tried:
Grid grid = arguments.Input_Grid;
if (grid == null)
{
PetrelLogger.ErrorStatus("HelloGrid: Arguments cannot be empty.");
return;
}
Index3 currentCell = new Index3();
int maxI = grid.NumCellsIJK.I;
int maxJ = grid.NumCellsIJK.J;
int maxK = grid.NumCellsIJK.K;
for (int i = 0; i < maxI; i++)
{
for (int j = 0; j < maxJ; j++)
{
for (int k = 0; k < maxK; k++)
{
currentCell.I = i; currentCell.J = j; currentCell.K = k;
if (grid.IsCellDefined(currentCell) && grid.HasCellVolume(currentCell))
{
//DictionaryProperty p = ???
//int val = p[currentCell] ???
}
}
}
}
You need to use the "FastDictionaryPropertyIndexer" or "FastPropertyIndexer" for regular properties.
foreach (var dictProp in grid.DictionaryProperties)
{
int numCellsI = dictProp.NumCellsIJK[0];
int numCellsJ = dictProp.NumCellsIJK[1];
int numCellsK = dictProp.NumCellsIJK[2];
float[] values = new float[dictProp.NumCells];
var dpsa = dictProp.SpecializedAccess;
using (var fdpi = dpsa.OpenFastDictionaryPropertyIndexer())
{
int index = 0;
for (int k = 0; k < numCellsK; k++)
{
for (int j = 0; j < numCellsJ; j++)
{
for (int i = 0; i < numCellsI; i++)
{
values[index] = fdpi[i, j, k];
index++;
}
}
}
}
}
You also need to be careful about the indexing since it varies by project. For instance, you may need to reverse the order of traversal in the J direction or you could end up with some strange results.

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.

Retrieving and manipulating data from file

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 :)

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;
}
}