iterate on sets of string in java [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
i have program that makes operations on string and this is the principal function of one of those operations,this works perfectly,but it is not efficient:
private void printString(ArrayList<String> operations, ArrayList<String> set) {
int numerOfStrings = 0;
int numberOfletters = 0;
String toPrint = operations.get(1);
outOfLoop: for (int i = 0; i < set.size(); i++) {
String[] toFind = set.get(i).split(" ");
for (int k = 0; k < toFind.length; k++) {
if (toPrint.equals(toFind[k])) {
String[] splited = set.get(i).split(" ");
for (int j = 0; j < splited.length; j++) {
numberOfletters += splited[j].length();
}
numerOfStrings = splited.length;
break outOfLoop;
}
}
}
System.out.println(numerOfStrings + " " + numberOfletters);
}
explanation:
this function takes as parameter a an arrayList of operations, and an arraylist of set:
for the arraylist of operations i get always a specific position so,i don't iterate , it is always O(1)
for the arrayList of set i have to iterate,or rather, as I think of that to proceed:
so , for example, if have as operation print foo i have to do these steps:
first of all i have to find where foo is :
inside set i can have this situation:
position 1 : {car tree hotel}
...
position n : {foo lemon coffee}
when i find the string foo i have to print the number of strings inside that position and the number of letters of each string,so in this case i will print :
3(number of strings) 14(number of letters)
my program works,and also this function works, but it is a nasty solution,and not efficent,what do you think, how can I improve in efficiency in my program?
question inserted on code Review

try this version:
private void printString(ArrayList<String> operations, ArrayList<String> set) {
int numerOfStrings = 0;
int numberOfletters = 0;
String toPrint = operations.get(1);
for (String s : set) {
if (s.contains(toPrint)) {
String[] arr = s.split(" ");
numerOfStrings = arr.length;
numberOfletters = s.length() - (numerOfStrings - 1);
break;
}
}
System.out.println(numerOfStrings + " " + numberOfletters);
}
The 'worst' case here would be O(n2), because of for loop O(n) and contains O(n).
hope it helps.

Related

Creating a two dimensional string array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
For the question below use 2d array greetings seen below:
![image of 2D array][1]
"bob"
"joe"
"billy"
"george"
"janise"
"dell"
The code that I wrote is:
public class c
{
// instance variables - replace the example
below with your own
private int columns; int rows;
/**
* Constructor for objects of class c
*/
public c()
{
int columns = 2;
int rows = 3;
String[][] newArray = new String[columns][rows];
newArray[0][0] = "bob";
newArray[0][1] = "joe";
newArray[1][0] = "billy";
newArray[1][1] = "george";
newArray[1][2] = "janise";
newArray[2][2] = "dell";
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
System.out.println(newArray[i][j]);
}
}
}
}
When creating the array, you need to use new String[rows][columns], not new String[columns][rows].
The third row should then be assigned using newArray[2][0] and newArray[2][1].
You can use an array initializer to create the array in a much easier way:
String[][] newArray = { { "hello", "ni hao" },
{ "konnichiwa", "hola" },
{ "guten tag", "bonjour" } };
So... your code is close to being correct.
The first mistake is that you mixed the columns and rows: You are defining your array to have two columns, but in the end, you are using three (0, 1, 2).
The second mistake is in the last two assignments: You really did confuse the numbering here.
Your finished constructor should look like this:
int columns = 2;
int rows = 3;
String[][] newArray = new String[rows][columns];
newArray[0][0] = "hello";
newArray[0][1] = "ni hao";
newArray[1][0] = "konnichiwa";
newArray[1][1] = "hola";
newArray[2][0] = "guten tag";
newArray[2][1] = "bonjur";
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
System.out.println(newArray[i][j]);
}
}

Array's methods and comands [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I was trying to obtain the minimun value and its index between an array of int.
I can't understand why if I use the for-loop inside the main method it doesn't work, but if I use the same code in an aux method it works. The code should be right.
The part of the code that is commented is the for-loop that doesn't work.
package minimoArray;
import java.util.Scanner;
public class minimoArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Inserisci 10 numeri interi: ");
int [] Arr = new int [10];
//int a = Arr[0];
int b = 0;
for (int i = 0; i < Arr.length; i++) { //NON si può riempire l'array con for-each
Arr[i] = scanner.nextInt();
}
/*
for (int i = 0; i < Arr.length; i++) {
if (Arr[i] < a) {
a = Arr[i];
b = i;
}
}*/
int minimo = minimo(Arr);
for (int i = 0; i < Arr.length; i++) {
if (Arr[i] == minimo) {
b = i;
}
}
System.out.println(" il minimo è: " + minimo);
System.out.println(" l'indice del minimo è: " + b);
}
private static int minimo (int [] a) {
var min = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] < min ) {
min = a[i];
}
}
return min;
}
}
Edit: Just saw that the a is commented out too, my mistake. However, here Nicktar's answer applies with the reason why, you set a to the first element of the array, whose numbers weren't even set yet. The solution stays the same though.
First of all, stick to the naming convention of Java. Classes start with an uppercase letter, variables start with a lowercase letter.
Your mistake in the for loop within your main method is that a isn't even definied there, therefore the whole loop shouldn't even compile.
Simply add the var a = Arr[0]; before the loop and start the loop at the index 1.
The initialization of a in your main method is to early. You set a to Arr[0] before the array is written which sets it to 0 because primitive int is initalized to 0. So your code in the main methods compares all your array to 0.... This would find a minimum that is negative only.

How to stop for loops from overwritng variables in nested ArrayLists [duplicate]

This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 5 years ago.
Recently I've been slamming by head against this piece of code:
for(int i = 0; i < cols; i++) {
for(int j = 0; j < rows; j++) {
SqrTileNormal temp = new SqrTileNormal(i, j, this, ID.Tile);
setTile(temp);
}
}
//additional info
public void setTile(Tile tile) {
int xPosGrid = tile.getXPosGrid();
int yPosGrid = tile.getYPosGrid();
System.out.println("Coords: (" + xPosGrid + ", " + yPosGrid + ")");
this.tiles.get(xPosGrid).set(yPosGrid, tile);
}
//how the nested array looks like.
protected List<ArrayList<Tile>> tiles;
It's part of a constructor which is supposed to fill a two-dimensional array with SqrTileNormal. I have found what the issue is: Every iteration of the for loop keeps rewriting the previous iterations, so they all end up whit the same xPosGrid and you see this:
I have been trying some things but I usually keep the overwriting issue and I don't want to make it unnecessarily complicated and long. Does anyone know of a solution to this problem? Any help would be appreciated!
Edit:
What I had:
[[null, null, null...][null, null, null...][(null, null, null...]
What I want:
What I get:
[[(10, 0),(10, 1),(10, 2)...][(10, 0),(10, 1),(10, 2)...][(10, 0),(10, 1),(10, 2)]...]
The problem is in how you initialize this.tiles, you are not showing how you do it but possibly you are setting just 1 array list, so in fact you have ten times the same value list.
Your this.tiles init should look like:
private static List<List<Tile>> getListOfLists() {
int numcol = 5;
int numrow = 5;
List<List<Tile>> bidiArray = new ArrayList<>();
for (int i = 0; i < numcol; i++) {
List<String> sublist = new ArrayList<>();
bidiArray.add(sublist);
for (int j = 0; j < numrow; j++) {
sublist.add(null);
}
}
return bidiArray;
}
But in fact, dealing with a fixed number of columns and rows I would rather use arrays such as :
Tile[][] bidiArray = new Tile[numcol][numrow];
And then set it like this:
this.tiles[xPosGrid][yPosGrid]= tile;

Adding Elements in an array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
items_arr = 4;
System.out.println("The elements in the array are: ");
for (int x = 0; x < items_arr; x++)
System.out.println("Array[" + x + "]=" + array[x]);
System.out.print("\n");
Scanner insert = new Scanner(System.in);
System.out.print("Enter an Element to Insert: ");
int input = insert.nextInt();
for (s = 0; s < items_arr; s++)
if (array[s] == input)
break;
items_arr++;
for (s = 0; s < items_arr; s++)
System.out.println("Array[" + s + "]=" + array[s]);
break;
The output is. The elements are
Array [0]= 1
Array [1]= 2
Array [2]= 3
Array [3]= 4
Enter an element to Insert: 5
Array [0]= 1
Array [1]= 2
Array [2]= 3
Array [3]= 4
Array [4]= 0
when I insert 5 it posts 0
any suggestions please.. thanks!
To insert in to the array you shuould be doing follwoing operation
array[s]=input
Two notes here
Arrays are fixed length, and you should be checking the array length before inserting values in to that,other wise you will get ArrayIndexOBException. Safer to sue List/Set
As better coding practise, and to improve the readablity, you should be enclosing the conditional/loop statements (such as if or for) - see eg below
eg: 1
for (int x = 0;x<items_arr;x++) {
System.out.println("Array["+x+"]="+array[x]);
}
eg 2:
for(int s = 0; s < items_arr; s++) {
if (array[s] == input) {
break;
}
}
You have not inserted 5 in your array,
do something after items_arr++
array[ items_arr] = input;
If you do not insert any thing then by default every element is 0
You should be using a Collection type; I would recommend an ArrayList - that is -
List<Integer> al = new ArrayList<Integer>();
for (int i = 1; i < 5; i++) {
al.add(i);
}
Scanner insert = new Scanner(System.in);
System.out.print("Enter an Element to Insert: ");
int input = insert.nextInt();
al.add(input); // And so on...
You are not updating/inserting the array with the new input.
for(s = 0; s < items_arr; s++)
if (array[s] == input)
break;
items_arr++;
just replace the above code with
array[ items_arr] = input;
items_arr++;

List comparison and to get the Index [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm having 2 lists of object, one is UI object and another one is database object,i want to compare both the list of objects(UI & database object) and to get the index of UI Object's list.
List<ObjectVO> listOfVOObj = new ArrayList<ObjectVO>();
List<ObjectDB> listOfDBObj = new ArrayList<ObjectDB>();
ObjectVO{
private String regNo;
private String userId;
private String name;
...
}
ObjectDB{
private String regNo;
private String userId;
..
}
listOfVOObj:
index regNo userId name
1 123 456 name1
2 2233 567 name2
3 2234 568 name3
4 2235 569 name4
5 2236 570 name5
listOfDBObj:
index regNo userId
1 2233 567
2 2234 568
i have to compare both the list and want to get the index of the records in listOfVOObj which are matching to the records in listOfDBObj.
From your description it looks like this should be enough: (in the code I am comparing the objects on regNo)
List<string> indexList = new List<string>();
for (int i = 0; i < listOfVOObj.length(); i++)
{
for (int j = 0; j < listOfDBObj.length(); j++)
{
if (listOfVOObj[i].regNo == listOfDBObj[j].regNo && listOfVOObj[i].userId == listOfDBObj[j].userId)
{
int index = i + 1;
indexList.Add(index);
}
}
}
If you would like to store indexes of both objects first you have to create new class like this:
public class MyClass
{
string indexVOObj;
string indexDBObj;
public MyClass(string index1, string index2)
{
indexVOObj = index1;
indexDBObj = index2;
}
}
Then you have to use this:
List<MyClass> indexList = new List<MyClass>();
for (int i = 0; i < listOfVOObj.length(); i++)
{
for (int j = 0; j < listOfDBObj.length(); j++)
{
if (listOfVOObj[i].regNo == listOfDBObj[j].regNo && listOfVOObj[i].userId == listOfDBObj[j].userId)
{
int index1 = i + 1;
int index2 = j + 1;
indexList.Add(new MyClass(index1, index2));
}
}
}

Categories

Resources