finding time complexity for the below java code - java

I have tried to find the time complexity for the below code but I am not sure whether it is right or not. can anyone help me on finding the time complexity for the below code. the code language is JAVA.
code:
// importing the necessary header files for the program
// header files are imported using the keyword import
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
//creating a class called "Partone". class can be created using the keyword class
public class Partone
{
public static void main(String[] args) throws IOException
{
// opening a file named "hikernet1"
File inputFile = new File("hikernet1.txt");
int maxTransmission = 0; //declaring maxTransmission as Integer data type and setting as 0
//reading the content of the file
Scanner reader = new Scanner(inputFile);
// inputCoordinatedAndTransmissionRange
String[] iCATR = reader.useDelimiter("\\A").next().replaceAll("\n", ",").replace("\r", "").split(",");
for (int i = 0; i < Integer.parseInt(iCATR[0]); i++)
{
int transmissions = 0; //declaring transmissions as integer data type and setting is as 0
String[] thisHiker = iCATR[i+1].split(" ");
int transMissionRange = Integer.parseInt(thisHiker[2]);
for (int j = 0; j < Integer.parseInt(iCATR[0]); j++)
{
int distance = (int) Math.sqrt(
Math.pow(Integer.parseInt(thisHiker[0])-Integer.parseInt(iCATR[j+1].split(" ")[0]), 2) + //x2-x1
Math.pow(Integer.parseInt(thisHiker[1])-Integer.parseInt(iCATR[j+1].split(" ")[1]), 2)); //y2-y1
if (distance<=transMissionRange)
{
transmissions++;
}
}
if (transmissions>maxTransmission) //checking the condition
{
maxTransmission = transmissions;
}
}
System.out.println(" The Maximum Transmission: "+maxTransmission);
//the outpit will be displayed in the hikernet1out file
FileWriter fw = new FileWriter("hikernet1out.txt"); //hikernet1out is the name of the output file
fw.write(""+maxTransmission);
fw.close(); //closing the file
reader.close(); //closing all the files
}
} //end of the program
any help would be appreciated much . thanks in advance.

Integer.parseInt(iCATR[0]); retruning any value let consider n.
The inner loop is running n times for every iteration of the outer loop.
The total number of nested loop itration = total number of iteration of outer loop . total number of iteration of inner loop = n * n = n^2
For each iteration nested loop doing O(1) operation.
Total time complexity = O(n^2)*O(1) = O(n^2).

Related

Creating triple-ended queue with efficient random access

I have been tasked to solve a question concerning the creation of a triple-ended queue with efficient random access, as outlined in this: https://open.kattis.com/problems/teque. I created a program based around using 2 very large arrays, one containing the front half of all stored integers so far and the other the back half, with both being of the same size or the front half containing at most 1 more element than the back half after every insertion operation. This should allow all insertion and retrieval operations to be of O(1) time complexity, but the code just keeps exceeding the given time limit. Can anyone tell me what is wrong with my code? Here it is:
import java.util.*;
import java.io.*;
public class Teque3 {
static int[] front = new int[1_000_000];
static int[] back = new int[1_000_000];
static int frontHead = 499_999;
static int backHead = 499_999;
static int frontSize = 0;
static int backSize = 0;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
for (int i = 0; i < n; i++) {
String[] line = br.readLine().split(" ");
if (line[0].equals("get")) {
int index = Integer.parseInt(line[1]);
if (index >= frontSize) System.out.println(back[backHead + index - frontSize]);
else System.out.println(front[frontHead + index]);
continue;
}
if (frontSize == backSize) {
if (line[0].equals("push_front")) {
frontHead--;
front[frontHead] = Integer.parseInt(line[1]);
frontSize++;
} else if (line[0].equals("push_back")) {
back[backHead + backSize] = Integer.parseInt(line[1]);
front[frontHead + frontSize] = back[backHead];
frontSize++;
backHead++;
} else if (line[0].equals("push_middle")) {
front[frontHead + frontSize] = Integer.parseInt(line[1]);
frontSize++;
}
} else {
if (line[0].equals("push_front")) {
frontHead--;
front[frontHead] = Integer.parseInt(line[1]);
backHead--;
back[backHead] = front[frontHead + frontSize];
backSize++;
} else if (line[0].equals("push_back")) {
back[backHead + backSize] = Integer.parseInt(line[1]);
backSize++;
} else if (line[0].equals("push_middle")) {
backHead--;
back[backHead] = Integer.parseInt(line[1]);
backSize++;
}
}
}
}
}
You could try to minimze IO-Operations: Collect your programm output. Instead of writing System.out.println better create a new StringBuilder to collect everything. In the end write all at once.
static StringBuilder result = new StringBuilder();
...
private static void result(int value) {
result.append(value).append("\n");
}
...
if (index >= frontSize) result(back[backHead + index - frontSize]);
else result(front[frontHead + index]);
...
System.out.println(result);
Decouple read from parse and process: Create one thread for reading the operations. But the operations in a Queue. Start another thread for the process.

How to generate random numbers with uniform distribution in Java?

So, i'm having trouble generating random numbers with uniform distribution in java, given the maximum and the minimun value of some attributes in some data set (Iris from UCI for machine learning). What i have is iris dataset, in some 2-d-array called samples. I put the random values according to the maximun and the minimun value of each attribute in iris data set (without the class attribute) in a 2-d-array called gworms (which has some extra fields for some other values of the algorithm).
So far, the full algorithm is not working properly, and my thoughts are in the fact that maybe the gworms (the points in 4-d space) are not generating correctly or with a good randomness. I think that the points are to close to each other (this i think because of some results obtained later whose code is not shown here). So, i'm asking for your help to validate this code in which i implement "uniform distribution" for gworms (for de first 4 positions):
/*
* To change this license header, choose License Headers in Project
Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package glowworms;
import java.lang.Math;
import java.util.ArrayList;
import java.util.Random;
import weka.core.AttributeStats;
import weka.core.Instances;
/**
*
* #author oscareduardo937
*/
public class GSO {
/* ************ Initializing parameters of CGSO algorithm ******************** */
int swarmSize = 1000; // Swarm size m
int maxIte = 200;
double stepSize = 0.03; // Step size for the movements
double luciferin = 5.0; // Initial luciferin level
double rho = 0.4; // Luciferin decay parameter
double gamma = 0.6; // Luciferin reinforcement parameter
double rs = 0.38; // Initial radial sensor range. This parameter depends on the data set and needs to be found by running experiments
double gworms[][] = null; // Glowworms of the swarm.
/* ************ Initializing parameters of clustering problem and data set ******************** */
int numAtt; // Dimension of the position vector
int numClasses; // Number of classes
int total_data; //Number of instances
int threshold = 5;
int runtime = 1;
/*Algorithm can be run many times in order to see its robustness*/
double minValuesAtts[] = new double[this.numAtt]; // Minimum values for all attributes
double maxValuesAtts[] = new double[this.numAtt]; // Maximum values for all attributes
double samples[][] = new double[this.total_data][this.numAtt]; //Samples of the selected dataset.
ArrayList<Integer> candidateList;
double r;
/*a random number in the range [0,1)*/
/* *********** Method to put the instances in a matrix and get max and min values for attributes ******************* */
public void instancesToSamples(Instances data) {
this.numAtt = data.numAttributes();
System.out.println("********* NumAttributes: " + this.numAtt);
AttributeStats attStats = new AttributeStats();
if (data.classIndex() == -1) {
//System.out.println("reset index...");
data.setClassIndex(data.numAttributes() - 1);
}
this.numClasses = data.numClasses();
this.minValuesAtts = new double[this.numAtt];
this.maxValuesAtts = new double[this.numAtt];
System.out.println("********* NumClasses: " + this.numClasses);
this.total_data = data.numInstances();
samples = new double[this.total_data][this.numAtt];
double[] values = new double[this.total_data];
for (int j = 0; j < this.numAtt; j++) {
values = data.attributeToDoubleArray(j);
for (int i = 0; i < this.total_data; i++) {
samples[i][j] = values[i];
}
}
for(int j=0; j<this.numAtt-1; j++){
attStats = data.attributeStats(j);
this.maxValuesAtts[j] = attStats.numericStats.max;
this.minValuesAtts[j] = attStats.numericStats.min;
//System.out.println("** Min Value Attribute " + j + ": " + this.minValuesAtts[j]);
//System.out.println("** Max Value Attribute " + j + ": " + this.maxValuesAtts[j]);
}
//Checking
/*for(int i=0; i<this.total_data; i++){
for(int j=0; j<this.numAtt; j++){
System.out.print(samples[i][j] + "** ");
}
System.out.println();
}*/
} // End of method InstancesToSamples
public void initializeSwarm(Instances data) {
this.gworms = new double[this.swarmSize][this.numAtt + 2]; // D-dimensional vector plus luciferin, fitness and intradistance.
double intraDistance = 0;
Random r = new Random(); //Random r;
for (int i = 0; i < this.swarmSize; i++) {
for (int j = 0; j < this.numAtt - 1; j++) {
//Uniform randomization of d-dimensional position vector
this.gworms[i][j] = this.minValuesAtts[j] + (this.maxValuesAtts[j] - this.minValuesAtts[j]) * r.nextDouble();
}
this.gworms[i][this.numAtt - 1] = this.luciferin; // Initial luciferin level for all swarm
this.gworms[i][this.numAtt] = 0; // Initial fitness for all swarm
this.gworms[i][this.numAtt + 1] = intraDistance; // Intra-distance for gworm i
}
//Checking gworms
/*for(int i=0; i<this.swarmSize; i++){
for(int j=0; j<this.numAtt+2; j++){
System.out.print(gworms[i][j] + "** ");
}
System.out.println();
}*/
} // End of method initializeSwarm
}
The main class is this one:
package uniformrandomization;
/**
*
* #author oscareduardo937
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import weka.core.Instances;
import glowworms.GSO;
public class UniformRandomization {
public UniformRandomization(){
super();
}
//Loading the data from the filename file to the program. It can be .arff or .csv
public static BufferedReader readDataFile(String filename) {
BufferedReader inputReader = null;
try {
inputReader = new BufferedReader(new FileReader(filename));
} catch (FileNotFoundException ex) {
System.err.println("File not found: " + filename);
}
return inputReader;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
// TODO code application logic here
BufferedReader datafile1 = readDataFile("src/data/iris.arff");
Instances data = new Instances(datafile1);
GSO gso = new GSO();
gso.instancesToSamples(data);
gso.initializeSwarm(data);
System.out.println("Fin...");
}
}
So i want to know if with this code, the numbers of the position ij of the gworms are generating within the range of max value and min value for attribute j.
Thanks so much in advanced.

Numbers missing from stack and linkedlist JAVA?

I am trying to implement code to convert decimal to binary with a certain precision, for that I use stack and linked list to add the non decimal and decimal parts calculated. I then use Stringbuilder to pop/poll element one by one to ge the final binary number. SOURCE : http://www.geeksforgeeks.org/convert-decimal-fraction-binary-number/
When I push the elements onto stack/list I see they are being pushed(Using o/p stmts for that). For some reason I dont see them when popping out the elements.
Here is my code
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class BinaryToDecimal {
public String toBinary(float n, int p){
int non_dec = (int) Math.floor(n);
Stack<Integer> s_non_dec = new Stack<>();
LinkedList<Integer> q_dec = new LinkedList<>();
float dec = n - non_dec;
int quotient = 1;
while(quotient > 0){
quotient = non_dec/2;
int remainder = non_dec%2;
System.out.println("quotient"+quotient+"non_dec"+non_dec+"remainder"+remainder);
s_non_dec.push(remainder);
non_dec = quotient;
}
while(p>0){
System.out.println("before dec"+dec);
dec = dec*2;
System.out.println("after dec"+dec);
if(dec >=1){
System.out.println("add 1");
q_dec.add(1);
dec = dec - 1;
}
else{
System.out.println("add 0");
q_dec.add(0);
}
p--;
}
StringBuilder sb = new StringBuilder();
for(int i=0;i<s_non_dec.size();i++){
System.out.println("pop"+s_non_dec.peek());
sb.append(s_non_dec.pop());
}
sb.append('.');
for(int i=0;i<q_dec.size();i++){
System.out.println("poll"+q_dec.peek());
sb.append(q_dec.poll());
}
return sb.toString();
}
public static void main (String args[]){
BinaryToDecimal btd = new BinaryToDecimal();
System.out.println(btd.toBinary(2.47f, 5));
}
}
My output :
quotient1non_dec2remainder0
quotient0non_dec1remainder1
before dec0.47000003
after dec0.94000006
add 0
before dec0.94000006
after dec1.8800001
add 1
before dec0.8800001
after dec1.7600002
add 1
before dec0.7600002
after dec1.5200005
add 1
before dec0.52000046
after dec1.0400009
add 1
pop1
poll0
poll1
poll1
1.011
as seen above, even tough I push 1 and 0 into my stack, my output has only 1 for the non decimal part instead of 1 and 0! The same happens for the decimal part!
Ive been looking at this code for hours, any help is appreciated!
Error is with your for loop.
for(int i=0;i<s_non_dec.size();i++){
System.out.println("pop"+s_non_dec.peek());
sb.append(s_non_dec.pop());
}
Here you are looping on stack size s_non_dec.size, which will keep on decreasing after every pop operation and "i" will keep on increasing after every iteration. You can better check if stack is empty or not. Use
while(!s_non_dec.isEmpty()) {
System.out.println("pop"+s_non_dec.peek());
sb.append(s_non_dec.pop());
}

java print to file cuts last digit of number

i try to print values into a file but my results are cutted when longer then 4 digits:
import java.io.FileNotFoundException;
import java.math.BigInteger;
public class create_referencevalues {
/**
* #param args
*/
public static void main(String[] args) {
Long[] list = { 10L, 40L, 90L, 160L, 250L, 350L, 500L, 650L, 800L,
1000L };
try {
java.io.PrintStream p = new java.io.PrintStream(
new java.io.BufferedOutputStream(
new java.io.FileOutputStream(new java.io.File(
"C:/users/djdeejay/listall.csv"), false)));
for (long i = 0; i < 1024; i++) {
//p.print(Long.toBinaryString(i));
Long sum1 = 0L;
for (int j = 0; j < 10; j++) {
if (BigInteger.valueOf(i).testBit(j)) {
sum1 += (list[j]);
}
}
p.println( i + ";"+sum1);
}
p.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Here are the 5 last values as printed:
1018;3750
1019;3760
1020;3800
1021;3810
1022;3840
1023;3850
last should be: 38500
what do I miss here ???
There is nothing wrong with the println. Your code does exactly what I'd expect it to do. Consider the last line, which you claim isn't correct:
1023;3850
The decimal 1023 is 1111111111 in binary. Therefore when i=1023, the inner loop of your program would simply compute the sum of all numbers in list. These numbers add up to 3850, which is what gets printed.
The last one should actually be 3850 and not 38500. When i = 1023 all bits are set and the last line will be the same as if you add all numbers in list[] together.
1000+650+800+500+350+250+160+90+40+10 = 3850

File and Insertion Sort. Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

This program sorts the first n words from a file using insertion sort.
This is not made by me. We were asked to use this program our teacher provided to implement other sorting techniques. I imported the source code and when I run it. It says:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at SortingAnalysis.main(SortingAnalysis.java:26)
But when our teacher demonstrated it in our class, there is no error in it.
I'm also wondering how it sorts the words from a file without even stating the file name (e.g. tobesorted.txt). Maybe as long as it's within the JRE System Library, it will work, won't it?
import java.io.*;
import java.util.*;
/**
* Compares the running times of sorting algorithms
* #author bryann
*
*/
public class SortingAnalysis {
public static void insertionSort(String[] a) {
int n = a.length;
for(int i = 1; i < n; i++) {
String cur = a[i];
int j = i - 1;
while((j >= 0) && (a[j].compareTo(cur) > 0)) {
a[j + 1] = a[j--];
} // end while
a[j + 1] = cur;
} // end for
} // end insertionSort
public static void main(String[] args) {
final int NO_OF_WORDS = 5000;
try {
Scanner file = new Scanner(new File(args[0]));
String[] words = new String[NO_OF_WORDS];
int i = 0;
while(file.hasNext() && i < NO_OF_WORDS) {
words[i] = file.next();
i++;
} // end while
long start = System.currentTimeMillis();
insertionSort(words);
long end = System.currentTimeMillis();
System.out.println("Sorted Words: ");
for(int j = 0; j < words.length; j++) {
System.out.println(words[j]);
} // end for
System.out.print("Running time of insertion sort: " + (end - start) + "ms");
} // end try
catch(SecurityException securityException) {
System.err.println("You do not have proper privilege to access the files.");
System.exit(1);
} // end catch
catch(FileNotFoundException fileNotFoundException) {
System.err.println("Error accessing file");
System.exit(1);
} // end catch
} // end main
} // end class SortingAnalysis
Is the error because of import? Using Eclipse, I just clicked
File > Import > General > File System > From directory (the whole folder he sent to us) > Into folder (I created a new project and there is where I "imported" the code) > Finish
Please help me. I can't start with the assignment (that is, trying other sorting techniques in the same source file) because I can't run it. Thank you very much!
The main function of a program takes arguments :
public static void main(String[] args) {
Those arguments are the ones passed to the program on the command line :
java SortingAnalysis /home/somebody/tobesorted.txt
In this case, args[0] would be "/home/somebody/tobesorted.txt"
This enables the program to know what file to open :
Scanner file = new Scanner(new File(args[0]));
But when you launch your program without providing the path to a file, args is too short and you have this java.lang.ArrayIndexOutOfBoundsException: 0 as args[0] doesn't exist you got.
So give the path to the file to sort to remove this error. For example :
java SortingAnalysis C:\somepath\tobesorted.txt
EDIT:
If you want to hardcode the path, you may do this :
Scanner file = new Scanner(new File("C:\\somepath\\tobesorted.txt"));
(note the double \\).
public static void main(String[] args) {
...
Scanner file = new Scanner(new File(args[0]));
It's looking for the first argument passed in when you run it which is the words file. You need to run it as:
java SortingAnalysis wordsfile.txt

Categories