How to collect all data from first column in table into array? - netbeans

I using netbeans 8.
I need to loop to collect all employee ID from first column of jtable and store those IDs into an arraylist.
if (jTabledetail.getRowCount() > 0) {
String ecode = "";
int ishasRow = jTabledetail.getRowCount();// total 1 row
for (int r = 0; r <= ishasRow; r++) {// loop twice. First loop is gone, return to second loop or final loop for 1 row exists giving error bellow.
ecode = jTabledetail.getValueAt(r, 0).toString();
arrempcode.add(ecode);
}
}
I also tried changing to ==>> for (int r = 0; r < ishasRow; r++) but not worked.
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1 >= 1
at java.util.Vector.elementAt(Vector.java:474)
at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:648)
at javax.swing.JTable.getValueAt(JTable.java:2717)
I don't understand the error. I known that the error comes from loop expression. I am not sure for this error.
Now my jtable named "jTabledetail" has 1 row exists.
Do I need to change something for this case of error? I am not sure that the loop expression is wrong.
Thank you very much.

DefaultTableModel tableModel = (DefaultTableModel) TableName.getModel();
Get the row count of the table
int rowCount = tableModel.getRowCount();
Declare ArrayList
ArrayList<Object> list = new ArrayList<Object>();
Traversing table and adding values into arraylist
for(int i=0; i<rowCount; i++){
for(int j=0; j<tableModel.getColumnCount(); j++){
if(j==0){
list.add(tableModel.getValueAt(i,j));
}
}
}

Related

Is there a better way to calculate the moving sum of a list in flutter

Is there a better way to calculate a moving sum of a list?
List<double?> rollingSum({int window = 3, List data = const []}) {
List<double?> sum = [];
int i = 0;
int maxLength = data.length - window + 1;
while (i < maxLength) {
List tmpData = data.getRange(i, i + window).toList();
double tmpSum = tmpData.reduce((a, b) => a + b);
sum.add(tmpSum);
i++;
}
// filling the first n values with null
i = 0;
while (i < window - 1) {
sum.insert(0, null);
i++;
}
return sum;
}
Well, the code is already clean for what you need. Maybe just some improvements like:
Use a for loop
You can use the method sublist which creates a "view" of a list, which is more efficient
To insert some values in the left/right of a list, there is a specific Dart method called padLeft, where you specify the lenght of the list which you want it to become (first parameter), then the value you want to use to fill it (second parameter). For example, if you have an array of N elements, and you want to fill it with X "null"s to the left, use padLeft(N+X, null).
List<double?> rollingSum({int window = 3, List data = const []}) {
List<double?> sum = [];
for (int i = 0; i < data.length - window + 1; i++) {
List tmpData = data.sublist(i, i + window);
double tmpSum = tmpData.reduce((a, b) => a + b);
sum.add(tmpSum);
}
sum.padLeft(window - 1, null);
return sum;
}
if I understand your problem correctly you can just calculate the window one time and in one loop you can for each iteration you can add the current element to the sum and subtract i - (window - 1)
so for an input like this
data = [1,2,3,4,5,6]
window = 3
the below code will result in [6,9,12,15]
int sum = 0;
List<double> res = [];
for (int i = 0;i<data.length;i++) {
sum += data[i];
if (i < window - 1) {
continue;
}
res.add(sum);
sum -= data[i - (window - 1)]; // remove element that got out of the window size
}
this way you won't have to use getRange nor sublist nor reduce as all of those are expensive functions in terms of time and space complexity

Insert failed on table with 300 integers and 300 char(20)

I've tried to test TOAST functionality and created the code:
int length = 20;
using (NpgsqlConnection conn = new NpgsqlConnection(""))
{
conn.Open();
StringBuilder ct = new StringBuilder();
ct.Append("CREATE TABLE t300 (");
for (int i = 0; i < 300; i++)
{
ct.Append("i").Append(i).Append(" int not null, n").Append(i).Append(" varchar(").Append(length).Append(") not null, ");
}
ct.Remove(ct.Length - 2, 2).Append(");");
using (NpgsqlCommand cmd = new NpgsqlCommand(ct.ToString(), conn))
{
cmd.ExecuteNonQuery();
}
StringBuilder isql = new StringBuilder();
isql.Append("INSERT INTO t300 (");
StringBuilder vsql = new StringBuilder();
vsql.Append("VALUES (");
for (int i = 0; i < 300; i++)
{
isql.Append("i").Append(i).Append(", n").Append(i).Append(", ");
vsql.Append(":i").Append(i).Append(", :n").Append(i).Append(", ");
}
isql.Remove(isql.Length - 2, 2).Append(") ").Append(vsql).Remove(isql.Length - 2, 2).Append(");");
using (NpgsqlCommand cmd = new NpgsqlCommand(isql.ToString(), conn))
{
for (int i = 0; i < 300; i++)
{
cmd.Parameters.AddWithValue("i" + i.ToString(), NpgsqlDbType.Integer, i);
cmd.Parameters.AddWithValue("n" + i.ToString(), NpgsqlDbType.Varchar, length, i.ToString() + new string('n', length - i.ToString().Length));
}
for (int i = 0; i < 10000; i++)
{
cmd.ExecuteNonQuery();
}
}
}
This code fails on INSERT with exception '54000, row size (8424) exceeds limit (8160)'.
When I set 'length' variable to 26, the code works fine. Please tell me the workaround to eliminate this situation.
Postgres 12, Npgsql 4.1.5
Perhaps you have a misconception of how TOAST storage works. PostgreSQL does not compress the whole row and store it in the TOAST table, but each column of a varying length data type independently.
So after toasting, the row still consists of 600 columns, 300 of which (the integers) won't be toasted (4 bytes), and the other 300 toasted columns (the varchars) will now contain a TOAST header and a TOAST pointer.
Together this happens to be more than fits into a single block, and rows cannot span more than a single block. That causes the error.
The solution is not to use tables with so many columns. You should split the data in several tables (normalization usually takes care of that). If there are truly very many attributes to a single entity, chances are that not all of these attributes will get used in join or WHERE conditions. You could consider storing such attributes in a single jsonb column, where TOASTing will be much more efficient.

How to create a layout that all its cells are initially empty and accessible by moving agents (such as equipment)?

In Copper Nickel Mine (Cloud) Simulation, In MinePanel Agent, there is a function Called setupTunnelLayout.
The original code in the above function is as following:
//create corridor of already empty rooms
`RoomBlock emptyRoom;
for ( int j = 0; j < nColumns; j++ ) {
emptyRoom = add_roomBlocks();
emptyRoom.jumpToCell( 0, j );
if ( j == nColumns - 1 )
emptyRoom.isStartBlock = true;
emptyRoom.isTunnel = true;
}`
But in my scenario all the cells are accessible initially, so all can be tunnel (path to move), not only the (0, j) row as the above example!
I was thinking I can change it as the followings; (1) or (2);
(1)
//create corridor of already empty rooms
RoomBlock emptyRoom;
for ( int j = 0; j < nColumns; j++ )
for (int i = 0; i < nRows; i++){
emptyRoom = add_roomBlocks();
emptyRoom.jumpToCell( 0, j );
emptyRoom.jumpToCell( i, 0 );
if ( j == nColumns - 1 )
emptyRoom.isStartBlock = true;
emptyRoom.isTunnel = true;
}
Or it can be like this;
(2)
//create corridor of already empty rooms
`RoomBlock emptyRoom;
for ( int j = 0; j < nColumns; j++ )
for (int i = 0; i < nRows; i++){
emptyRoom = add_roomBlocks();
emptyRoom.jumpToCell( i, j );
if ( j == nColumns - 1 )
emptyRoom.isStartBlock = true;
emptyRoom.isTunnel = true;
}`
'Can you please let me know if (1) or (2) are correct? Which one is preferred?
Thank you so much,
Neda.'
The second is preferable; there is no point jumping the agent to the column and then the row when you can directly move it to the exact cell coordinates.
In both cases though you are missing a closing } for your extra i loop (and you're missing an opening one in your second case).
//create corridor of already empty rooms
RoomBlock emptyRoom;
for (int j = 0; j < nColumns; j++) {
for (int i = 0; i < nRows; i++) {
emptyRoom = add_roomBlocks();
emptyRoom.jumpToCell(i, j);
if (j == nColumns - 1) {
emptyRoom.isStartBlock = true;
}
emptyRoom.isTunnel = true;
}
}
[I used the StackOverflow formatting to mark the full block as Java code. It's also best-practice (although AnyLogic doesn't do it many of their example models) to always use curly brackets for loops, etc. even if their body only has one line.]
Plus whether the change will do what you want or not obviously depends on the rest of the model and how it handles the grid of cells and tunnels.

Peculiar issue with quicksort partition

Today, when trying quicksort, instead of taking last element as pivot and partitioning,i took the first element as pivot, But it is not producing the correct partitioned output.
int pivot = ar[0];
int pindex = 0;
for(int i = 0;i < ar.size();i++)
{
if(ar[i] <= pivot)
{
swap(ar[i],ar[pindex]);
pindex++;
}
}
swap(ar[pindex],ar[ar.size()-1]);
I could not understand why, i always use this for partition, but this is not working when i take first element as partition.
But this worked even if i took first element as partition
int i, j, pivot, temp;
pivot = ar[0];
i = 0;
j = ar.size()-1;
while(1)
{
while(ar[i] < pivot && ar[i] != pivot)
i++;
while(ar[j] > pivot && ar[j] != pivot)
j--;
if(i < j)
{
temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
else
{
break;
}
}
What are the differences between them.
At last found that, this method is Hoare's partition method, where as the typical quick sort method we all follow is lomuto's partition.
See this wiki page, it has all details https://en.wikipedia.org/wiki/Quicksort

Printing the values from the corresponding array

Suppose:
1 A
2 B
3 C
I need to print the value corresponding to 1-> A. I have put each in an array:
d1[1,2,3] and s1[A,B,C]. Now I need to print the value in the form shown in the above:
d1[0] s1[0]
1 A
How can I do this using UnityScript? In the program, I did id printing in this format:
1 A
1 B
1 C
2 A
2 B
2 C
What you have probably done, and I'm guessing without seeing the code is something along that you have a for loop within a for loop which means you're processing the first item in the first array and then all items in the second:
for (var i = 0; i < d1.Length; i++) {
for(var j = 0; j < s1.length; j++ {
Debug.log(d1[i] + " " + s1[j])
}
}
Your options depend on the array sizes and how you want to handle them. For example if you know they're the same size consistently then
for(var i = 0; i < d1.Length; i++) {
Debug.log(d1[i] + " " + s1[i])
}
should work. I would wonder if what you're trying to achieve could be done with a different data structure such as a dictionary, etc.