JAVA MODBUS error - java

I am trying to run below code. I have a MODBUS transmitter connected at COM1 with Baud rate of 9600, transmitting data via USB cable. I want to collect that data.
public static void main(String[] args) {
SerialConnection con = null;
ModbusSerialTransaction trans = null;
ReadInputRegistersRequest req = null;
ReadInputRegistersResponse res = null;
String portname = null;
int unitid = 0;
int ref = 0;
int count = 0;
int repeat = 1;
try {
portname = "COM1";
unitid = 2;
ref = 0;
count = 8;
}
catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
ModbusCoupler.getReference().setUnitID(1);
SerialParameters params = new SerialParameters();
params.setPortName(portname);
params.setBaudRate(9600);
params.setDatabits(8);
params.setParity("None");
params.setStopbits(2);
params.setEncoding("rtu");
params.setEcho(false);
con = new SerialConnection(params);
con.open();
req = new ReadInputRegistersRequest(ref, count);
req.setUnitID(unitid);
req.setHeadless();
trans = new ModbusSerialTransaction(con);
trans.setRequest(req);
int k = 0;
do {
trans.execute();
res = (ReadInputRegistersResponse) trans.getResponse();
for (int n = 0; n < res.getWordCount(); n++) {
System.out.println("Word " + n + "=" + res.getRegisterValue(n));
}
k++;
}
while (k < repeat);
con.close();
}
While running the code, I am getting below error.
java.lang.Exception
at net.wimpi.modbus.net.SerialConnection.open(SerialConnection.java:91)
at Main.main(Main.java:50)
Exception in thread "main" java.lang.NullPointerException
at net.wimpi.modbus.io.ModbusSerialTransaction.execute(ModbusSerialTransaction.java:168)
at Main.main(Main.java:66)
While running,
Please help me out in this, as i am not able to figure out the error.

Related

how to give chance to all clients one by one to send a number and block a client to send number if its not his chance in socket programming in java

Multiple clients and one server for bingo game
Server.java
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.*;
import java.util.ArrayList;
public class Server {
int[][] card = new int[5][5];
int[][] bingo = new int[5][5];
public int[][] bingoCard() {
ArrayList<Integer> alreadyUsed = new ArrayList<>();
boolean valid = false;
int tmp = 0;
for (int i = 0; i <= 4; i++) {
for (int row = 0; row < card.length; row++) {
while (!valid) {
tmp = (int) (Math.random() * 25) + 1;
if (!alreadyUsed.contains(tmp)) {
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][i] = tmp;
bingo[row][i] = tmp;
valid = false;
}
}
//create array to make title.
String title[] = {"B", "I", "N", "G", "O"};
for (int i = 0; i < title.length; i++) {
System.out.print(title[i] + "\t");
}
System.out.println();
for (int row = 0; row < card.length; row++) {
for (int col = 0; col < card[row].length; col++) {
System.out.print(card[row][col] + "\t");
}
System.out.println();
}
return bingo;
}
public static void main(String args[]) {
try {
ServerSocket serversct = new ServerSocket(1000);
int counter = 0;
System.out.println("Server Started ....");
while (counter <= 2) {
counter++;
Socket serverClient = serversct.accept(); //server accept the client connection request
System.out.println(" >> " + "Client No:" + counter + " started!");
DataInputStream inStream = new DataInputStream(serverClient.getInputStream());
DataOutputStream outStream = new DataOutputStream(serverClient.getOutputStream());
//bingo=Server.bingoCard();
ObjectOutputStream os = new ObjectOutputStream(serverClient.getOutputStream());
ServerClientThread sct = new ServerClientThread(serverClient, counter, inStream, outStream, os, new Server().bingoCard()); //send the request to a separate thread
ServerClientThread.sockets.add(sct);
if (counter == 1) {
ServerClientThread.chance.add(1);
} else {
ServerClientThread.chance.add(0);
}
}
ServerClientThread.distribute();
//ServerClientThread.sockets.get(1).start();
ServerClientThread.transferring();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ServerClientThread extends Thread {
Socket serverClient;
int clientNo;
DataInputStream inStream;
DataOutputStream outStream;
ObjectOutputStream oos;
static ArrayList<ServerClientThread> sockets = new ArrayList<>();
static ArrayList<Integer> chance = new ArrayList<>();
static ArrayList<ObjectOutputStream> oosal = new ArrayList<>();
static ArrayList<DataInputStream> datainputal = new ArrayList<>();
static ArrayList<DataOutputStream> dataoutputal = new ArrayList<>();
static int received;
int[][] card = new int[5][5];
int[][] bingo = new int[5][5];
ServerClientThread(Socket inSocket, int counter, DataInputStream dis, DataOutputStream dos, ObjectOutputStream oos, int abc[][]) {//,int abc[][]) {
this.serverClient = inSocket;
this.clientNo = counter;
this.oos = oos;
oosal.add(oos);
this.inStream = dis;
this.outStream = dos;
ServerClientThread.datainputal.add(dis);
ServerClientThread.dataoutputal.add(dos);
this.bingo = abc;
}
//i will use this run method later for checking winner of bingo card
#Override
public void run() {
try {
System.out.println("thread is running");
} catch (Exception ex) {
System.out.println(ex);
} finally {
System.out.println("Client :" + clientNo + " exit!! ");
}
}
public static void distribute() throws Exception {
System.out.println("distributing");
for (int i = 0; i <= ServerClientThread.sockets.size() - 1; i++) {
oosal.get(i).writeObject(ServerClientThread.sockets.get(i).bingo);
System.out.println("i is +" + i);
}
}
public static synchronized void transferring() throws Exception {
while (true) {
int chance = 1;
int received = 10000;
for (int i = 0; i <= ServerClientThread.datainputal.size() - 1; i++) {
ServerClientThread.dataoutputal.get(i).writeInt(chance);
ServerClientThread.dataoutputal.get(i).flush();
for (int l = 0; l <= ServerClientThread.chance.size() - 1; l++) {
if (ServerClientThread.chance.get(l) == 1)
{
received = ServerClientThread.datainputal.get(i).readInt();
}
if (l == i + 1)
{
ServerClientThread.chance.set(l, 1);
}
else if (i == ServerClientThread.chance.size() - 1) {
ServerClientThread.chance.set(l, 0);
ServerClientThread.chance.set(0, 1);
} else {
ServerClientThread.chance.set(l, 0);
}
}
for (int n = 0; n< ServerClientThread.datainputal.size(); n++)
{
for (int j = 0; j< ServerClientThread.datainputal.size(); j++)
if(ServerClientThread.chance.get(n)==1 && ServerClientThread.datainputal.get(j).available()>0)
{
received=ServerClientThread.datainputal.get(j).read();
}}
System.out.println("this is received" + received);
chance = 0;
for (int j = 0; j <= ServerClientThread.dataoutputal.size() - 1; j++) {
ServerClientThread.dataoutputal.get(j).writeInt(chance);
ServerClientThread.dataoutputal.get(j).writeInt(received);
}
chance = 1;
for (int k = 0; k <= ServerClientThread.chance.size() - 1; k++) {
System.out.println("here is given chance" + ServerClientThread.chance.get(k));
}
}
}
}
}
}
Client.java
import java.io.*;
import java.net.*;
import java.util.Scanner;
class Client {
static String completed[] = new String[5];
static int tosend;
static int received1;
public static void main(String args[]) throws Exception {
try {
// Scanner scn = new Scanner(System.in);
// getting localhost ip
InetAddress ip = InetAddress.getByName("localhost");
int flag = 1;
// establish the connection with server port 9999
Socket s = new Socket(ip, 1000);
DataInputStream discl = new DataInputStream(s.getInputStream());
DataOutputStream doscl = new DataOutputStream(s.getOutputStream());
ObjectInputStream is = new ObjectInputStream(s.getInputStream());
int[][] array = (int[][]) is.readObject();
//create array to make title.
String title[] = {"B", "I", "N", "G", "O"};
for (int i = 0; i < title.length; i++) {
System.out.print(title[i] + "\t");
}
System.out.println();
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++) {
System.out.print(array[row][col] + "\t");
}
System.out.println();
}
while (true) {
int i = discl.readInt();
if (i == 1 )
{
System.out.println("inside i==1");
System.out.println("in if condition 1");
System.out.println("opening scanner");
tosend = new Scanner(System.in).nextInt();
doscl.writeInt(tosend);
} else if (i == 0) {
//sendComplete();
System.out.println("closing scanner");
System.out.println("inside i==2");
//completed = Bingo;
System.out.println("in if condition 0");
received1 = discl.readInt();
System.out.println(received1);
}
}
} catch (IOException | ClassNotFoundException e) {
}
}
}
Aactually i am developing Bingo card game, after distributing bingo card to each client, game begins and each client will play one by one and send a number to server and then server will send that number to all clients this is the repeatedly process,
as i said all client will send number one by one if client follow this flow then the execution of the program is as i want i am stucked on a situation that is if client enters two numbers at a time **then after completing all other clients chance ,when chance comes to that particular client who entered two numbers will not get chance and the second number entered by this client will be considered as his played number. i want to stop listening from server side to accept numbers if a client enters more than one number at a time.

How to speed up reading in input in Java

I am attempting to read in info from files to implement Dijkstra's algorithm. I believe that the double for loop is causing this to drastically slow down, is there anyway around this?
Edge[] edge = new Edge[127807];
int indexEdge = 0;
String line2 = "";
BufferedReader fileReader2 = new BufferedReader(new FileReader("Road.txt"));
String valueString = null;
String vertex1IDName = null;
String vertex2IDName = null;
String extra = null;
float value = 0;
int vertex1ID = 0;
int vertex2ID = 0;
//Read the file line by line
while ((line2 = fileReader2.readLine()) != null)
{
//Get all tokens available in line
String[] tokens2 = line2.split(DELIMITER);
for(String token1 : tokens2)
{
vertex1IDName = tokens2[0];
vertex2IDName = tokens2[1];
valueString = tokens2[2];
if(tokens2.length - 1 == 3) {
extra = tokens2[tokens2.length - 1];
}
else {
extra = "";
}
vertex1ID = Integer.parseInt(vertex1IDName);
vertex2ID = Integer.parseInt(vertex2IDName);
value = Float.parseFloat(valueString);
}
System.out.println("value: "+ value + " vertex1ID:"+ vertex1ID +" vertex2ID:"+ vertex2ID+ " extra:" + extra);
//if vertex 1 name or vertex 2 name in vertex.getID()
for(int i = 0; i< indexVertex; i++) {
for(int j = 0; j< indexVertex; j++) {
if(vertex1ID == vertex[i].getID() && vertex2ID == vertex[j].getID()) {
vertex[i].addNeighbour(edge[indexEdge] = new Edge(value,vertex[i],vertex[j],extra));
indexEdge++;
}
}
}
}

list.isEmpty() or list.size() not working in an if loop in java

I am using java for sending streams at given rate(say 100 events/sec) via UDP to another receiver program. The receiver program has 2 threads. Thread 1 appends the values to List and another thread is checking is the list has some element and perform some action on it.
Earlier, I have been using a queue instead of a list. I was having issues with Iterator thread while checking if the queue has some element or not. It's a wired problem, I may be making some silly mistake. For this reason, I decided to use List, but I am having same issues now.
Can someone please tell me what am I doing wrong?
Code of Sender Program is
public class simpleGen {
public static void main(String[] args) throws IOException, InterruptedException {
Integer arrival_rate = 1;
Integer sleep_time = 1000/arrival_rate;
Long currentTime;
Integer value = null;
Integer Sensor_id;
Integer Patient_id;
Integer uid = 0;
Long count = 0L;
Integer time_in_sec = 60*2 ;
Integer lower_bound = 10;
Integer upper_bound = 20;
Long start_time = System.currentTimeMillis();
Long end_time = start_time + (1000 * time_in_sec);
int server_port = 8000;
DatagramSocket s = new DatagramSocket();
s.setSendBufferSize(2147483647);
InetAddress local = InetAddress.getByName("172.17.195.107");
while (System.currentTimeMillis() < end_time) {
uid = 1;
count += 1;
Random random = new Random(System.currentTimeMillis());
Patient_id = 1;
Sensor_id = 1;
currentTime = System.nanoTime();
value = lower_bound + random.nextInt((upper_bound - lower_bound) + 1);
Event event = new Event(Patient_id, Sensor_id, uid, currentTime, value);
String messageStr = event.toString();
// System.out.println(messageStr);
int msg_length = messageStr.length();
byte[] message = messageStr.getBytes();
DatagramPacket p = new DatagramPacket(message, msg_length, local, server_port);
s.send(p);
System.out.print(" \r Sensor 1 count = " + count );
System.out.flush();
Thread.sleep(sleep_time );
}
Float inpt_rate = Float.valueOf(count)/time_in_sec;
System.out.println(" \n Average output rate = " + inpt_rate + " events/second" );
}
}
Code of Receiver Program is
public class Simplereceiver {
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_PURPLE = "\u001B[35m";
public static void main(String args[]) throws Exception
{
Queue<String> queue = new LinkedList<String>();
List<String> list = new ArrayList<String>();
Thread iterating_thread = new Thread(){
#Override
public void run() {
System.out.println( ANSI_BLUE + " iterating_thread started");
Boolean running = true ;
while(running){
if(list.size() > 0){
System.out.println("has element ----");
System.out.println(list.size());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}};
Thread receiving_thread = new Thread(){
#Override
public void run() {
Integer total_re_ECG = 0;
String[] sensor_value = new String[10];
String[] parsed_tuple = new String[10];
boolean run = true;
DatagramSocket udpSocket = null;
DatagramPacket packet = null;
try {
udpSocket = new DatagramSocket(8000);
udpSocket.setReceiveBufferSize(2147483647);
} catch (SocketException e) {
e.printStackTrace();
}
byte[] message = new byte[8000];
packet = new DatagramPacket(message, message.length);
System.out.println( ANSI_RED + " receiving_thread started");
while (run) {
try {
// Block until the host receives a UDP packet.
udpSocket.receive(packet);
String text = new String(message, 0, packet.getLength());
String[] tupleData = text.split(",");
int i = 0;
for (String tuple : tupleData) {
String[] tupleValue = tuple.split("=");
sensor_value[i] = tupleValue[1];
i += 1;
}// key pair of tuple ends
total_re_ECG += 1;
Integer patient_id = Integer.valueOf(sensor_value[0]);
Integer sensor_id = Integer.valueOf(sensor_value[1]);
Integer tuple_id = Integer.valueOf(sensor_value[2]);
Long generation_time = Long.valueOf(sensor_value[3]);
Float sensor1_data = Float.valueOf(sensor_value[4]);
Long event_arrival_time = System.nanoTime();
// System.out.println(event_arrival_time);
parsed_tuple[0] = total_re_ECG + "," + event_arrival_time ;
// queue.add(String.valueOf(sensor1_data));
list.add(String.valueOf(sensor1_data));
System.out.println("packet added is = " + parsed_tuple[0]);
} catch (IOException e) {
run = false;
}//catch
}//while
}
};
receiving_thread.start();
iterating_thread.start();
}//main
}//class
Using LinkedBlockingQueue solved my issue
Updated code for Iterator Thread is
Thread iterating_thread = new Thread(){
#Override
public void run() {
System.out.println( ANSI_BLUE + " iterating_thread started");
Boolean running = true ;
while(running){
if(!linkedBlockingQueue.isEmpty()){
System.out.println(linkedBlockingQueue.element());
linkedBlockingQueue.remove();
}
}
}};

Thread automatically stop (freeze) in Eclipse

I am running a thread in eclipse to get data from mysql server. Thread works fine. The problem is after bit of time thread stop running(withing 6 to 8 hours). Thread get freeze. After that I have to manually close and re-run the program. Eclipse runs in a windows server 2012 r2 machine. No error or exception is shown.
Main class.
public class Main {
private final static int fONE_DAY = 1;
private final static int fZERO_MINUTES = 0;
public static void main(String[] argv) {
Timer timer1 = new Timer();
Timer timer4 = new Timer();
try {
timer1.scheduleAtFixedRate(new CearteSDQuatation(),500 , 1000*60*4);// 4min
System.out.println("timer 1 : createSDQuotation");
} catch (Exception e) {
e.printStackTrace();
}
try {
timer4.schedule(new GarbageCol(), 5000, 1000 * 60 * 60);// 60mins
System.out.println("timer 2 : garbageCollector");
} catch (Exception e) {
e.printStackTrace();
}
}
private static Date getTomorrowRunningTime(int Ftime){
Calendar tomorrow = new GregorianCalendar();
tomorrow.add(Calendar.DATE, fONE_DAY);
Calendar result = new GregorianCalendar(
tomorrow.get(Calendar.YEAR),
tomorrow.get(Calendar.MONTH),
tomorrow.get(Calendar.DATE),
Ftime,
fZERO_MINUTES
);
return result.getTime();
}
}
CearteSDQuatation class.
public class CearteSDQuatation extends TimerTask {
DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");;
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
Date date = new Date();
DBPool_SF pooler;
DataSource dataSource;
DataSource dataSource1;
DBTableQueryExcecutre qex = null;
DBTableQueryExcecutre qex3 = null;
DBTableQueryExcecutre qex1 = null;
DBTableQueryExcecutre qex2 = null;
ArrayList<String> dates = null;
HashSet<String> dateSet = null;
Iterator<String> itr = null;
StringBuilder inClause;
int rcount = 0;
StringBuilder sbDel = null;
int delStatus = 0;
ArrayList<String> elements = new ArrayList<String>();// for update query
int queryStatus = 0;
String delete_query1 = " ";
String strDate = "";
String strMatnr = "";
String strkunnr = "";
// Object for table data
private Object[][] itemData;
RFCHandler handler;
public CearteSDQuatation(){
handler = new RFCHandler();
}
#Override
public void run() {
// TODO Auto-generated method stub
try{
CallItem_ListCreate();
CallRFC_CreateSDQuata();
System.out.println("Thread Run");
}
catch (Exception e){
e.printStackTrace();
}
}
private void CallItem_ListCreate() {
// TODO Auto-generated method stub
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
System.out.println("Create Quotation : Started sub excecutions List create...");
String sbQuery3 = "SELECT d.plant, h.dis_channel, h.order_no, h.Rep_no," +
"h.dealer_no,h.order_date,h.last_date, d.items_no," +
"d.quantity " +
"FROM tbl_item_list as d, " +
"tbl_items_header_t as h " +
"where d.order_no = h.order_no " +
"and h.status <> 'X'" ;
try {
pooler = DBPool_SF.getInstance();
dataSource1 = pooler.getDataSource();
System.out.println("pooler");
} catch (Exception e1)
{
e1.printStackTrace();
}
try {
Connection con3 = dataSource1.getConnection();
con3.setAutoCommit(false);
Statement st = con3.createStatement();
ResultSet rs = st.executeQuery(sbQuery3);
int lineitem = 0;
try {
rs.last();
rcount = rs.getRow();
rs.beforeFirst();
}
catch(Exception ex) {
ex.printStackTrace();
}
System.out.println("while loop");
itemData = new Object[9][rcount];
while(rs.next())
{
itemData[0][lineitem] = rs.getString("plant");
lineitem = lineitem + 1;
}
} catch (SQLException e)
{
e.printStackTrace();
}
}
public void CallRFC_CreateSDQuata()
{
System.out.println("Create Quotation : Started sub excecutions");
JCO.Table IT_LIST = null;
JCO.Table IT_LIST1 = null;
JCO.Table IT_REF = null;
JCO.Table IT_Msg = null;
try {
if(rcount > 0)
{
handler.createRFCFunction("ZSL");
IT_LIST = handler.getTablePara("IT_LIST");
IT_LIST1 = handler.getTablePara("IT_LIST1");
for(int x = 0; x < rcount; x++ )
{
IT_LIST.appendRow();
IT_LIST1.appendRow();
IT_LIST.setValue( itemData[0][x].toString().trim(), "SAL_ORG");
}
handler.excFunction();
IT_REF = handler.getTablePara("IT_REF");
IT_Msg = handler.getTablePara("IT_MSG");
handler.releaseClient();
int int_row = IT_REF.getNumRows();
if (int_row > 0) {
this.tableOparator(IT_REF , IT_Msg);
}
}
} catch (Exception ex) {
handler.releaseClient();
ex.printStackTrace();
}
finally {
// Release the client to the pool
//handler.releaseClient();
rcount = 0;
}
}
public String leadingZeros(String s, int length) {
if (s.length() >= length) return s;
else return String.format("%0" + (length-s.length()) + "d%s", 0, s);
}
public void tableOparator(JCO.Table table , JCO.Table table1 ) throws Exception {
pooler = DBPool_SF.getInstance();
dataSource = pooler.getDataSource();
Connection con = dataSource.getConnection();
con.setAutoCommit(false);
qex = new DBTableQueryExcecutre(con);
StringBuilder sbQuery = new StringBuilder(
"INSERT INTO tbl_RefQut (QuatationNo,RefOrderNumber) VALUES");
System.out.println("COL -->"+table.getNumRows()
+ " records to insert for tbl_RefQut");
// --- create query ---------------------------------
for (int i = 0; i < table.getNumRows(); i++) {
// table.setRow(i);
sbQuery.append("(?,?),");
}
sbQuery.deleteCharAt(sbQuery.length() - 1);
sbQuery.append(";");
qex.setUpdateQuery(sbQuery.toString());// *****************
elements.clear();
for (int i = 0; i < table.getNumRows(); i++) {
table.setRow(i);
elements.add(table.getString("SDOCUMENT").trim());
elements.add(table.getString("ONUMBER").trim());
}
qex.updateInsertQuery(elements);
con.commit();
StringBuilder sbQuery1 = new StringBuilder(
"INSERT INTO tbl_item_order_msg (order_no,msg) VALUES");
System.out.println("COL -->"+table1.getNumRows()
+ " records to insert for tbl_item_order_msg");
// --- create query ---------------------------------
for (int i = 0; i < table1.getNumRows(); i++) {
// table.setRow(i);
sbQuery1.append("(?,?),");
}
sbQuery1.deleteCharAt(sbQuery1.length() - 1);
sbQuery1.append(";");
qex.setUpdateQuery(sbQuery1.toString());// *****************
elements.clear();
for (int i = 0; i < table1.getNumRows(); i++) {
table1.setRow(i);
elements.add(table1.getString("ORDER_NUMBER").trim());
elements.add(table1.getString("MESSAGE").trim());
}
qex.updateInsertQuery(elements);
con.commit();
for (int i = 0; i < table.getNumRows(); i++) {
table.setRow(i);
String sbQuery2 = "update tbl_items_header_t set status = 'X' where order_no = '" + table.getString("ORDER_NUMBER").trim() + "';";
int rcount = qex.runQuery(sbQuery2);
System.out.println("tbl_items_header_t Rows -->"+rcount + "Status Updated");
con.commit();
}
qex.closeConnections();
System.out.println("COL --> Cycle Finished....");
}
}
a possible reason to this situation is, you are hitting mysql's max open connections error, because you are not closing connections in method CallItem_ListCreate. it seems mysql default max connection count is 151. you are openning 15 connections per hour and after 10 hour you will hit that mentiooned error.
p.s. : you should try running your code in debug mode (or using tools like visualvm, jstack) and view thread dumps as #saurav commented.

SPOJ Time Limit Exceeded - GENERAL

I'm trying to solve this problem of SPOJ: http://br.spoj.com/problems/GENERAL/
My solution works in Ideone (http://ideone.com/Xj2B9Y), but when I put the same solution in SPOJ, it reports that TLE - Time Limit Exceeded.
I have searched in the Internet to find a solution to improve my code. I replaced the "Scanner" by "BufferedReader", but I keep getting the message TLE.
Please could someone tell me where I am going wrong?
public static void main(String[] args) throws java.lang.Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
//Scanner scan = new Scanner(System.in);
int instancias = Integer.parseInt(br.readLine());
int count = 0;
while(instancias != 0)
{
count = 0;
boolean possible = true;
boolean impossible = false;
st = new StringTokenizer(br.readLine());
int numSoldados = Integer.parseInt(st.nextToken());
int distancia = Integer.parseInt(st.nextToken());
int[] listaSoldados = new int[numSoldados];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < numSoldados; i++)
{
listaSoldados[i] = Integer.parseInt(st.nextToken());
}
while(possible)
{
possible = false;
for (int i = 0; i < numSoldados; i++)
{
if(numSoldados - (i + distancia) >= 1)
{
int alturaPS = listaSoldados[i];
int alturaSS = listaSoldados[i + distancia];
if(alturaPS > alturaSS)
{
listaSoldados[i] = alturaSS;
listaSoldados[i + distancia] = alturaPS;
count = count + 1;
possible = true;
}
}
else
{
if(!possible)
{
for (int j = 0; j < numSoldados - 1; j++)
{
if(listaSoldados[j] > listaSoldados[j+1])
{
impossible = true;
break;
}
}
break;
}
break;
}
}
}
if(impossible)
System.out.println("impossivel");
else
System.out.println(count);
instancias--;
}
}

Categories