I am new to JAVA. Below is my code of NQueens problem. The results are [[Ljava.lang.String;#123a439b, [Ljava.lang.String;#7de26db8].
Can anyone please help? Thank you very much! I copyied the code from other's blog. The code should be correct. I just don't know how to print out the results. I think this should be not very hard. My background is not computer science, that's maybe why I have the trouble. Thank you!
import java.util.ArrayList;
public class Solution {
public ArrayList<String[]> solveNQueens(int n) {
ArrayList<String[]> res = new ArrayList<String[]>();
if(n<=0)
return res;
int [] columnVal = new int[n];
DFS_helper(n,res,0,columnVal);
return res;
}
public void DFS_helper(int nQueens, ArrayList<String[]> res, int row, int[] columnVal){
if(row == nQueens){
String[] unit = new String[nQueens];
for(int i = 0; i < nQueens; i++){
StringBuilder s = new StringBuilder();
for(int j = 0; j < nQueens; j++){
if(j == columnVal[i])
s.append("Q ");
else
s.append("+ ");
}
unit[i] = s.toString();
//System.out.println(unit[i]);
}
//System.out.println();
res.add(unit);
// System.out.println(Arrays.toString(res));
//return;
}
else{
for(int i = 0; i < nQueens; i++){
columnVal[row] = i;//(row,columnVal[row)==>(row,i)
if(isValid(row,columnVal))
DFS_helper(nQueens, res, row+1, columnVal);
}
}
}
public boolean isValid(int row, int [] columnVal){
for(int i = 0; i < row; i++){
if(columnVal[row] == columnVal[i]
||Math.abs(columnVal[row]-columnVal[i]) == row-i)
return false;
}
return true;
}
public static void main(String[] args) {
Solution su = new Solution();
int n = 4;
System.out.println(su.solveNQueens(n));
}
}
While you do System.out.println(su.solveNQueens(n)); it prints list contents which are array and it just prints array object, but not it's contents. so, to print array contents you need to iterate through them.
Arrays.toString Returns a string representation of the contents of the specified array.
https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#toString(java.lang.Object[])
get result into a list and then print it:
List<String[]> res = su.solveNQueens(n);
for(String strs[] : res) {
System.out.println(Arrays.toString(strs));
}
You can do like this too as the above prints with ,. Here iterating through the list and then array.
List<String[]> res = su.solveNQueens(n);
for(String strs[] : res) {
for(String s: strs) {
System.out.print(s+ " ");
}
System.out.println();
}
in java 8, you can make use of stream and lambda:
ArrayList<String[]> result = su.solveNQueens(n)
result.stream().forEach(i->System.out.println(Arrays.toString(i)));
Related
New to java programming and I am currently trying to create a class similar to ArrayList using Arrays.
Am trying to add elements to an array and expand the array by copying them to a new array of bigger size.
I am getting an out of index error at 20.
Code may be messy but currently really stuck.
public class MyArrayList{
private String[] strings;
private int arraySize;
private int storedStrings;
public MyArrayList(int arraySize){
this.arraySize = arraySize;
this.strings = new String[arraySize];
}
public void addString(String string){
storedStrings = 0;
for (int i = 0; i < this.arraySize;i ++){
if (strings[i] != null){
storedStrings = storedStrings +1;
}
}
if (storedStrings == this.arraySize){
String[] newArray = new String[this.arraySize+10];
for (int i = 0; i < this.strings.length; i++){
strings[i] = newArray[i];
}
this.strings = newArray;
newArray[storedStrings] = string;
this.arraySize = this.arraySize +10;
}
else{
strings[storedStrings] = string;
}
for(int i = 0; i < strings.length; i++)
{
//System.out.println(strings[i]);
}
}
}
The code is being run in the test class where the error is being generated on line 10 of test class and line 47 of MyArrayList class.
This is the test code
public class TestArrayList{
public static void main(String[] args)
{
MyArrayList a = new MyArrayList(10);
for (int i = 0; i <50; i++){
a.addString("Test" + i);
}
for (int i = 0; i<50;i++){
System.out.println(a.getString(i*5));
}
}
}
you can do it like this:
public void addString(String string){
if (storedStrings == this.arraySize){
this.arraySize += 10;
String[] newArray = new String[this.arraySize];
for (int i = 0; i < this.storedStrings; i++){
newArray[i] = strings[i];
}
this.strings = newArray;
}
if (strings[storedStrings] == null){
strings[storedStrings++] = string;
}
// remove this loop it will show repeating values otherwise
for(int i = 0; i < storedStrings; i++)
{
System.out.println(strings[i]);
}
}
edit: as you are new to java always think about how can you do more with less code, how to avoid repetition of code, how to merge things that do common task. That will help you write better code
edit2 : the problem is with this loop
for (int i = 0; i<50;i++){
System.out.println(a.getString(i*5));
}
if you have 50 elements in array the getString method on (eg) i = 25 will be 25*5 = 125 which is not the index in the array that's why you are getting ArrayIndexOutOfBound Exception.
you can add
public int size(){
return storedStrings;
}
to check the size of your list which is the maximum item that is inside the list
First with your code there is a mistake in this line
strings[i] = newArray[i];
because you arenĀ“t copying the old data to new array but cleaning the strings array, I suppose that you wish do the contrary action.
In other hand you have extra code that you could improve.
public class MyArrayList{
private String[] strings;
private int arraySize;
public MyArrayList(int arraySize){
this.arraySize = arraySize;
this.strings = new String[arraySize];
}
public void addString(String string){
// Since you always do this
// it's better to use a local variale
int storedStrings = 0;
// Use the foreach syntax
// it's less prone to errors
// and easier to read
for (String s : this.strings){
if (s != null){
storedStrings++;
}else{
// since you want to count the strings in your array
// and you put them in this array
// one after the other
// no need to check the whole array
// when you find null you can exit the loop
break;
}
}
if (storedStrings == this.arraySize){
String[] newArray = new String[this.arraySize+10];
for (int i = 0; i < this.strings.length; i++){
// here we need to copy the content of strings in newArray
// NOT the other way
newArray[i] = this.strings[i];
}
this.strings = newArray;
newArray[storedStrings] = string;
this.arraySize += 10;
}else{
this.strings[storedStrings] = string;
}
}
public String[] getStrings(){
return this.strings;
}
}
As for the test class
public static void main(String[] args){
MyArrayList a = new MyArrayList(10);
for (int i = 0; i <50; i++){
a.addString("Test" + i);
}
for (String s : a.getStrings()){
System.out.println(a);
}
}
Given an array of strings, return another array containing all of its longest strings.
For (String [] x = {"serm", "aa", "sazi", "vcd", "aba","kart"};)
output will be
{"serm", "sazi" , "kart"}.
The following code is wrong, What can I do to fix it.
public class Tester {
public static void main(String[] args) {
Tester all = new Tester();
String [] x = {"serm", "aa", "sazi", "vcd", "aba","kart"};
String [] y = all.allLongestStrings(x);
System.out.println(y);
}
String[] allLongestStrings(String[] input) {
ArrayList<String> answer = new ArrayList<String>(
Arrays.asList(input[0]));
for (int i = 1; i < input.length; i++) {
if (input[i].length() == answer.get(0).length()) {
answer.add(input[i]);
}
if (input[i].length() > answer.get(0).length()) {
answer.add(input[i]);
}
}
return answer.toArray(new String[0]);
}
}
I will give you solution, but as it homework, it will be only sudo code
problem with your solution is, you are not finging longest strings, but strings same size or bigger than size of first element
let helper = []
let maxLength = 0;
for each string in array
if (len(string) >maxLength){
maxLength = len(string);
clear(helper)
}
if (len(string) == maxLength)
helper.add(string)
}
return helper;
You can try below code
private static String[] solution(String[] inputArray) {
int longestStrSize = 0;
List<String> longestStringList = new ArrayList<>();
for (int i = 0; i < inputArray.length; i++) {
if (inputArray[i] != null) {
if (longestStrSize <= inputArray[i].length()) {
longestStrSize = inputArray[i].length();
longestStringList.add(inputArray[i]);
}
}
}
final int i = longestStrSize;
return longestStringList.stream().filter(x -> x.length() >= i).collect(Collectors.toList()).stream()
.toArray(String[]::new);
}
I have this String is a result from query
07:40,09:00,10:20,11:40,|08:00,09:00,|
1) i want to eliminate the last ,|
2) convert it to
String[][] matrix ={
{"07:40","08:00"},
{"09:00","09:00"},
{"10:20",null},
{"11:40",null}
};
I would:
1) elimitate the last ",|" using e.g. substring()
2) split the string with string.split("|"), and keep the length as numTimes
3) cycle over the split result and split each substring by substr.split(",")
4) keep the maximum length of the length of the splits in an int called len
5) create the result array String[][] matrix = new String[len][numTimes]
5) create a for loop for (int i = 0; i < len; i++){...
6) within the loop add the correct values into matrix (check for null)
If you are using C++ then you can try this :
#include <bits/stdc++.h>
using namespace std;
vector<string>split(string str,string Separator)
{
vector<string>answer;string temp;
int len=str.size();
for(int i=0;i<len;i++)
{
bool isSeparator=false;
for(int j=0;j<Separator.length();j++)
if(str[i]==Separator[j])
isSeparator=true;
if(!isSeparator)
{
temp+=str[i];continue;
}
if(temp!="")
answer.push_back(temp);temp="";
}
if(temp!="")
answer.push_back(temp);
return answer;
}
int main()
{
int i,j;
string str="07:40,09:00,10:20,11:40,|08:00,09:00,|";
vector<string>v=split(str,"|"); // First split with respect to '|'
vector<string>matrix[100]; // Maximum row of time
for(i=0;i<v.size();i++)
{
vector<string>temp;
temp=split(v[i],","); // Now split with respect to ','
for(j=0;j<temp.size();j++)
{
matrix[j].push_back(temp[j]);
}
}
for(i=0;;i++)
{
if(matrix[i].size()==0) // Break the loop, because no time will be on below
break;
for(j=0;j<matrix[i].size();j++)
cout<<matrix[i][j]<<" ";
cout<<"\n";
}
return 0;
}
Try this:
public static void main(String ars[]) {
String string = "11:40,|08:00,09:00,|";
String[] str1 = string.split("\\|");
if (str1.length != 2) {
throw new IllegalArgumentException("I dont see a seperator | in your String");
}
String[] rows = str1[0].split(",");
String[] cols = str1[1].split(",");
int maxLength = rows.length > cols.length ? rows.length : cols.length;
String matrix[][] = new String[maxLength][2];
for (int row=0; row<rows.length; row++) {
matrix[row][0] = rows[row];
}
for (int col=0; col<cols.length; col++) {
matrix[col][1] = cols[col];
}
for (int i=0; i<maxLength; i++) {
System.out.println(Arrays.toString(matrix[i]));
}
}
hi try this solution it works and not only in a perfect way but it take care of null strings ans malformed strings enjoy
public static String[][] getModel(String answer){
try {
System.out.println(answer);
if(answer.contains("|")){
String[] cols=answer.split(",\\|");
System.out.println("case found");
System.out.println("size 1:"+cols.length);
int dimensionCol=cols.length;
int dimensionRow=cols[0].split(",").length;
System.out.println(dimensionCol+" "+dimensionRow);
String[][] result=new String[dimensionRow][dimensionCol];
int i=0,j=0;
for(String colElement:cols){
i=0;
String[] datas = colElement.split(",");
for (String data : datas) {
result[i][j]=(!data.equals(""))?data:null;
System.out.print(result[i][j]);
i++;
}
System.out.println("");
j++;
}
return result;
}else{
System.out.println("empty String return by null");
return null;
}
}catch(Exception e){e.printStackTrace();}
return null;
}
here is the main test methode
public static void main(String[] args) {
// String model = "07:40,09:00,10:20,11:40,|08:00,09:00,|";
String model = "";
String[][] model1 = getModel(model);
if (model1!=null) {
for (String[] model11 : model1) {
for (String model111 : model11) {
System.out.print(model111+" ");
}
System.out.println("");
}
}
}
public boolean makeReservation(int id, AvilaNatalyPassenger request) {
boolean status = true;
ArrayList<Integer> inputValues = new ArrayList<Integer>();
for (int i = 0; i < 22; i++) {
for (int j = 0; j < 5; j++) {
id = seats[i][j];
if (id != -1) {
if (inputValues.contains(id)) {
status = false;
break;
}
else {
inputValues.add(id);
for(int a = 0; a < inputValues.size; a++)
seats[a] = inputValues[a];
}
}
}
}
return status;
}
This is what I have but its not correct. I need to add what I have in inputVaule arrayList into the array seats.
You can also look at the Java API: http://docs.oracle.com/javase/7/docs/api/index.html?java/util/ArrayList.html
public Object[] toArray()
Returns an array containing all of the elements in this list in proper sequence (from first to last element).
So this is what you could do:
seats[a] = inputValues.toArray();
Furthermore you cannot use inputValues[a] since it is not an array. What you probably could do is
seats[a] = (inputValues.toArray())[a];
To answer your question, here is an example:
ArrayList<String> stock_list = new ArrayList<String>();
stock_list.add("stock1");
stock_list.add("stock2");
String[] stockArr = new String[stock_list.size()];
stockArr = stock_list.toArray(stockArr);
for(String s : stockArr)
System.out.println(s);
Example is taken from here
I want to sort my String[][] with respect to second column. I tried this
public static String[][] sorting_minn(String[][] list){
double[] temp = new double[list.length];
String[][] tempf = list;
if(list[1][1]!=null){
for(int i = 0; i<list.length; i++){
if(list[i][2]==null){
break;
} else {
temp[i]=Double.parseDouble(list[i][2]);
}
}
Arrays.sort(temp);
for(int f = 0; f<list.length-1;f++){
for(int m = 0; m<list.length;m++){
if(list[m][2]!=null && Double.parseDouble(list[m][2])==temp[f]){
for(int n = 0; n<4; n++){
tempf[list.length-f-1][n]=list[m][n];
}
m = list.length;
}
}
}
}
return tempf;
}
As an output I get this: . I need suggestion on how to improve this code.
try something like:
Arrays.sort(list, new Comparator<String[]>() {
#Override
public int compare(String[] o1, String[] o2) {
String left = o1[1]!=null ? o1[1] : "";
String right = o2[1]!=null ? o2[1] : "";
return left.compareTo(right);
}
});
this treats nulls as empty strings, and exploits the fact that strings are comparable, although lexicographic. if you want the reverse order just do this instead:
right.compareTo(left)
if you want integer ordering you could parse an Integer out of both sides (Integer.MIN for null) and compare 2 Integers