Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I've been trying to write a simple program in java to find time complexity of a program.A program whih just searches for "for" loop or "while" loop and prints the no of iteration such as O(n) or O(2n) etc.
I got the i/p program in textarea.Is there any way by which i could do the opertaion?
Please any one help me.
This is not full proof, but would work for you
import java.util.StringTokenizer;
public class Complexity {
public static void main(String[] args) {
String input = "for(i=0;i<10;i++)\n{\nfor(i=0;i<10;i++)\n{\nfor(i=0;i<10;i++)\n{\n}\n}\n}\nfor(i=0;i<10;i++)\n{\n}\nfor(i=0;i<10;i++)\n{\nfor(i=0;i<10;i++)\n{\n}\n}";
int open_bracket=0;
StringTokenizer t = new StringTokenizer(input);
String result = "";
String token="";
int current = 0;
System.out.println("CODE \n"+input);
while(t.hasMoreTokens())
{
token = t.nextToken();
if(token.equals("{")) open_bracket++;
if(token.equals("}")) open_bracket--;
if(token.length()>=3) if(token.substring(0, 3).equals("for")) current++;
if(open_bracket==0&&token.equals("}"))
{
result += " n^"+current+" +";
current = 0;
}
}
if(result.length()>0) result = result.substring(0, result.length()-1);
result = "O( "+result+")";
System.out.println("RESULT = "+result);
}
}
OUTPUT
CODE
for(i=0;i<10;i++)
{
for(i=0;i<10;i++)
{
for(i=0;i<10;i++)
{
}
}
}
for(i=0;i<10;i++)
{
}
for(i=0;i<10;i++)
{
for(i=0;i<10;i++)
{
}
}
RESULT = O( n^3 + n^1 + n^2 )
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
public static void deleteEntry(String title, ArrayList<String> myLines, ArrayList<Movie> myMovieList) {
boolean isMatch = false;
boolean titleHasMovie = false;
String realTitle = title;
for (int i = 0; i < myMovieList.size(); i++) {
String tempTitle = myMovieList.get(i).getTitle();
isMatch = realTitle.equalsIgnoreCase(tempTitle);
if (isMatch) {
fileWrite myWriteFile = new fileWrite("src/Main/db.txt");
myWriteFile.setWriteBuffer(myLines);
myWriteFile.deleteLine(i);
myWriteFile.saveFile();
titleHasMovie = true;
}
}
if (!titleHasMovie)
p("Title not found");
p("");
}
myLines is and ArrayList which contains
movieTitle*year*runtime(in minutes)*actor1*actor2*director
Iron Man*2008*126*Robert Downey Jr.*Gwyneth Paltrow*Jon Favreau
This is the exception thrown when I try to or successfully manage to delete a line
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:359)
at java.base/java.util.ArrayList.get(ArrayList.java:427)
at Main.Database.deleteEntry(Database.java:95)
at Main.Main.main(Main.java:89)```
I'm pretty sure it is throwing an out of bounds error because you are deleting entries as you are iterating. You should trying running the loop in reverse: for(int i = myLines.size() - 1; i >= 0; i--)
Also I'm not sure why your for loops' upper bound is i < myLines.size() + 2; instead just .size()
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 need to find the maximum and minimum statistics for the student marks from a list. The list contains the student ID and the student Mark. Im not too sure how to do this.
This is the code for reading in the file and creating the list:
public void readFile(Scanner in)
{
inputStudentID = null;
inputMark = 0;
try
{
File file = new File("Marks.txt");
in = new Scanner(file);
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
System.out.println("in " + System.getProperty("user.dir"));
System.exit(1);
}
while (in.hasNextLine())
{
String studentRecord = in.nextLine();
List<String> values = Arrays.asList(studentRecord.split(","));
String inputStudentID = values.get(0);
String sInputMark;
sInputMark = values.get(1);
int inputMark = Integer.parseInt(sInputMark);
addStudent(inputStudentID, inputMark);
}
in.close();
}
Assuming you have some indexed list since addStudent doesn't really tell me much (else just apply the logic to whatever you have):
private int getMax(ArrayList<Integer> marks) {
int max = marks.get(0);
int index = 0;
for(int x = 1; x < marks.size(); x++) {
if(max < marks.get(x)) {
max = marks.get(x);
index = x;
}
}
return index;
}
Better solution:
You could simply do Collections.max(list) – Imaginary Pumpkin
Yet I'll still leave mine to show the logic of how to find a max.
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 7 years ago.
Improve this question
class Que{
char q[];
int front , rear ;
Que(int size){
q = new char[size];
front = rear =0;
}
void push(char ch){
if(rear == q.length){
System.out.println("Que is Full");
}
else{
q[rear++]=ch;
System.out.println(ch + " Added");
}
}
void pop(){
if(front==rear){
System.out.println("Que is Empty");
}
else{
System.out.println(q[front] + " Is being popped ");
front++;
}
}
void disp(){
char temp = q[front];
for(int i = front;i<rear ; i++)
{
System.out.println(q[i]);
}
}
}
class Example{
public static void main(String args[])
throws java.io.IOException{
Que Sample1 = new Que(10);
int opt = 1;
char j,k;
while(opt!=0){
System.out.println("1-Add , 2 - Pop , 3 - Display");
j = (char) System.in.read();
if(j=='1'){
System.out.println("What to push ?");
k = (char)System.in.read();
Sample1.push(k);
}
else if(j=='2'){
Sample1.pop();
}
else if(j=='3'){
Sample1.disp();
}
else if(j=='4'){
opt = 0;
}
else{ System.out.println("Try Again");}
}
}
}
This is not working . When I compile and run it it show me the main menu and as soon as I press 1)ADD - it skips displaying 'Added' msg from the function .
What am I doing wrong?
When I press 1 (Add) it should ask me "what To Push " which it does, but then does not wait for my input and plays loop again .
So this is what displays --
1)ADD
2)Pop
3)Display
1
What to push ( takes no input)
Added (automatically displayed)
1)ADD
2)Pop
3)Display
What are you typing in your terminal ?
If you type more than one character for example 11 or even 1<Enter>, your second call to System.in.read() will immediatly return with this second character: 1 or <Enter>.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have one input String to the program and I need to execute this String into my method, but I want to execute it if the character String is less than or equal to 20 characters, so I want to split this String into multiple Strings if the string is longer than 20 characters.
That is, the number of characters input String is 90 characters then become a 5 String 20 + 20 + 20 + 20 + 10 = 90.
I need each 20 characters String and last String do this code:
try {
enMessage = AES.encrypt(key, message);
sendSMS(contact, enMessage);
} catch (Exception e)
so its could make each 20 characters is one message.
You can use String's substring method to split the strings you want to.
You can read about how to use it here
Java String Documentation
The best example of such code I have seen so far on this site is:
public class StringSplitter {
/* regex was stolen from other stackoverflow answer*/
public static void main(String[] args) {
for (String str : "123a4567a8sdfsdfsdgasfsdfsdgsdcvsdfdgdfsdf9".split("(?<=\\G.{20})"))
System.out.format("\'%s\'%n", str);
}
}
You can try doing this:
package com.me;
import java.util.*;
import java.lang.*;
import java.io.*;
public class Test
{
public static List<String> splitMyString(String textValue, int textSize) {
ArrayList<String> myNewList= new ArrayList<String>((textValue.length() + textSize- 1) / textSize);
for (int start = 0; start < textValue.length(); start += textSize) {
myNewList.add(textValue.substring(start, Math.min(textValue.length(), start + textSize)));
}
System.out.println(myNewList.toString());
return myNewList;
}
public static void main(String[] args) {
Test.splitMyString("1234546512312312312312365", 5);
}
}
Output:
Success time: 0.1 memory: [12345, 46512, 31231, 23123,
12365]
Try this:
ArrayList<String> allstrings = new ArrayList<>();
if(inputstring.length() < 20) {
//no spliting
} else {
//if 90 char than 90/20=4.5
float numberOfspliting = inputstring.length / 20f;
for(int i = 0; i < numberofspliting; i++){
String split = inputstring.substring(i * 20, i * 20 + 20);
allstrings.add(split);
}
//like 4.5-4=0.5
float leftcharacters = numberofspliting - (int)numberofspliting;
String lastsplit = inputstring.substring((int)numberofspliting * 20, (int)numberofspliting * 20 + leftcharacters * 20f);
allstrings.add(lastsplit);
}//end if
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm a beginner in Java. I have the following situation:
The ArrayList contains {10234, 20233, 34546, 43546, 59865, 70002, 92435, 200354}
And the user inputs 20000 and 50000
And I want to get values from the ArrayList between 20000 and 50000, in this case I expect 20233, 34546, 43546 as answer.
How do I do this?
This is the code I have so far:
int t1 = 20233, t2 = 59865;
int i = 0;
boolean foundt1, foundt2;
foundt1 = false;
found20 = false;
while (i < a.size && (!foundt2)) {
if (a.get(i) == 10) {
foundt1 = true;
}
if (foundt1) {
System.out.println(a.get(i));
}
if (a.get(i) == 20) {
foundt2 = true;
}
i++;
}
Here is an example of what you are trying to do.
import java.util.ArrayList;
import java.util.Arrays;
public class Test{
public static void main(String[] args) {
ArrayList<Integer> numberList = Arrays.asList(10234, 20233, 34546, 43546, 59865, 70002, 92435, 200354);
for(int nbr : numberList){ //goes through the list
if( nbr > 20000 && nbr < 50000){
System.out.println(nbr);
}
}
}
}
Hope this helps!
Best Regards, Goatcat
You can use the Guava library.
The Iterables and Range classes can solve your task.
The sample:
public static void main(String[] args) {
List<Integer> values = Arrays.asList(10234, 20233, 34546, 43546, 59865, 70002, 92435, 200354);
Iterable<Integer> filteredValues = Iterables.filter(values, Range.closed(20000, 50000));
for (Integer val : filteredValues) {
System.out.println(val);
}
}
The output is:
20233
34546
43546
You cand find more info here