How to reason about the complexity of my code [closed] - java

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 8 years ago.
Improve this question
i did some coding in java to find a missing number know my code is working. i have basic knowledge about how to check the complexity of the program and i have keen interest to learn about how can i do that please any one help me or suggest me to read some good tutorial. or help me to know somthing about asymptotic complexity related to my code. Thank You.
here is my code
Scanner s1=new Scanner(System.in);
System.out.println("Enter No:");
int length=s1.nextInt();
boolean isExit=false;
int []a=new int[length-1];
System.out.println("Enter all no");
for(int i=0;i<length-1;i++){
a[i]=s1.nextInt();
}
for (int i = 1; i<=length; i++) {
for (int j = 0; j < a.length; j++) {
if(i==a[j]){
isExit =true;
break;
}
}
if (!isExit) {
System.out.println(i);
//break;
}
isExit = false;
}
}
}

I'm not sure if you're specifically trying to learn to do it all by hand? If not it's relatively easy to use streams to find the missing number:
Arrays.sort(array);
IntStream.range(0, array.length).filter(n -> !n.equals(array[n])).findAny();
That returns an Optional<Integer> which can then be tested to see if any missing number is present.

Read this : http://en.wikipedia.org/wiki/Big_O_notation
What you are looking to learn for is called asymptotic complexity.
A good video : Youtube
Also check out this answer
What is a plain English explanation of "Big O" notation?
In relation to your post :
for (int i = 1; i<=length; i++) {
for (int j = 0; j < a.length; j++) {
if(i==a[j]){
isExit =true;
break;
}
}
if (!isExit) {
System.out.println(i);
//break;
}
isExit = false;
}
Assuming that the operations inside your inner loop take constant time O(1).
If you think about this chunk of code in terms of code complexity you can notice that the outer loop will execute at most N(length) times and you can notice that the inner loop will execute N times too.Thus at most N^2 operations will be executed thus the upper bound of your algorithm is O(N^2) which means that the function N^2 will always be above the operations you make.

Related

The code showing Time Limit Exceed erroe, could some one explain, where is problem in this code [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 last year.
Improve this question
LeetCode 485
Given a binary array nums, return the maximum number of consecutive 1's in the array.
Example 1:
Input: nums = [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
---------Solution:-------
public int findMaxConsecutiveOnes(int[] nums) {
int maxConsSize = Integer.MIN_VALUE;
int i = -1, j=-1, k=0;
while(k<nums.length){
while(k<nums.length && nums[k] == 1){
k++;
i++;
}
if(nums[k] == 0){
maxConsSize = Math.max(maxConsSize,i-j);
j = i;
}
}
maxConsSize = Math.max(maxConsSize,i-j);
return maxConsSize;
}
Warning: This is not direct answer (for this "do my homework" question)
You should use (or learn to use) debugger in your IDE (trust me, IDE, e.g. Eclipse will help you a lot in your beginnings).
The easiest (I'm not saying smartest) way, how to know what the program is doing (when you need to know, like in this case) is to add some print statements, e.g. add System.out.println("k=" + k) into your program (in a while loop).
You might want to watch this youtube video.
You have an infinity loop. Try run this:
public class Test {
public static void main(String[] args) {
int maxConsSize = Integer.MIN_VALUE;
int[] nums = {1,1,0,1,1,1};
int i = -1, j=-1, k=0;
System.out.println(nums.length);
while(k<nums.length){
while(k<nums.length && nums[k] == 1){
k++;
i++;
System.out.println("k = " + k);
}
if(nums[k] == 0){
maxConsSize = Math.max(maxConsSize,i-j);
j = i;
}
}
maxConsSize = Math.max(maxConsSize,i-j);
System.out.println(maxConsSize);
}
}
Output:
6
k = 1
k = 2
After reading the first 0 you are in infinite loop. You have made this task very complicated :)
It's probably not the best solution, but it should be faster
public int findMaxConsecutiveOnes(int[] nums) {
int maxCons = 0;
int currentCons = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
if (currentCons > maxCons) {
maxCons = currentCons;
}
currentCons = 0;
} else {
currentCons++;
}
}
if (currentCons > maxCons) {
maxCons = currentCons;
}
return maxCons;
}
}
There are two basic forms of loops:
for-each, for-i or sometimes called ranged for
Use that for a countable number of iterations.
For example having an array or collection to loop through.
while and do-while (like until-loops in other programming languages)
Use that for something that has a dynamic exit-condition. Bears the risk for infinite-loops!
Your issue: infinite loop
You used the second form of a while for a typical use-case of the first. When iterating over an array, you would be better to use any kind of for loop.
The second bears always the risk of infinite-loops, without having a proper exit-condition, or when the exit-condition is not fulfilled (logical bug). The first is risk-free in that regard.
Recommendation to solve
Would recommend to start with a for-i here:
// called for-i because the first iterator-variable is usually i
for(int i=0; i < nums.length, i++) {
// do something with num[i]
System.out.println(num[i]):
}
because:
it is safer, no risk of infinite-loop
the iterations can be recognized from the first line (better readability)
no counting, etc. inside the loop-body
Even simpler and idiomatic pattern is actually to use a for each:
for(int n : nums) {
// do something with n
System.out.println(n):
}
because:
it is safer, no risk of infinite-loop
the iterations can be recognized from the first line (better readability)
no index required, suitable for arrays or lists
no counting at all
See also:
Java For Loop, For-Each Loop, While, Do-While Loop (ULTIMATE GUIDE), an in-depth tutorial covering all about loops in Java, including concepts, terminology, examples, risks

Create bubble sort code, but facing some errors [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 6 years ago.
Improve this question
Had a problem with compilation, getting error
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at practise.code.main(code.java:11)
Here is my code:
package practise;
public class code {
static int number[]={1,8,5,9,4,7};
static int c[] = new int[number.length];
static int p=0;
static int q;
public static void main(String[] args){
change(number);
System.out.println("Array Before Bubble Sort");
for(int y: c){
System.out.print(y + "\t");
}
}
public static void change (int x[]){
for(int a: x){
for(int i=0; i<=x.length; i++){
if(a > x[i]){
continue;}
else {
p++;}
q = x.length - p - 1;
c[q] = a;
}
}
}
}
}
Some meta-help for future reference:
Compiler errors: these are when you experience an error that occurs at compile time. For Java, this is when you use javac, and your Java code is being turned into bytecode files for interpretation later.
Runtime errors: this is when you experience an error that occurs when you run your code. For Java, this is when you use java, and your Java code is being run.
If you find the two confusing, add into your question the thing you typed in order to experience the error. Specify all the flags and options you used, and format it with a code block, for example like this:
java -jar code.jar
When asking questions here - or indeed anywhere on the web where you can get technical help - try to ask yourself what clarifications you would need if you saw your question for the first time. Your first edit did not include your code, so ask yourself: would you be able to ascertain someone else's similar problem without code? Broadly here the answer is "no", and thus the moral of this story is: always include your code.
Also, do spend a moment to learn the code formatting tools. To use them, paste your block of code into the question, select it, and click the "code" button. It will apply a four-space Markdown indent, which you can now see in the question.
If you need to add clarifications to your post, it is OK to add them as comments, but do also edit the body of the question so that new readers can understand the question. It is well worth spending time making it as readable and clear as possible, so you can get the best possible help, and so that people do not take a look and decide that another question is a better use of their time.
Since you are using an IDE, do you get any warnings/errors in the editor, to help you identify potential problems in you code? If so, and you do not understand them, then paste them into your question, in order to clarify it.
Thanks for your advices... Finally made it working..
thank you once again
package practise;
public class code{
public static void main(String[] args){
int[] Array = {5,8,6,4};
int[] newArray = new int[Array.length];
int a, b, c, d, e, f =1;
for(int z : Array ){
d=0;
for(int i=0; i<Array.length; i++){
a = z; b = Array[i];
if( a >= b){
continue;}
else{
d++;}
}
c = Math.subtractExact(Array.length , d);
e = Math.subtractExact(c, f);
for(int j=0; j< Array.length; j++){
while( j == e){
newArray[j] = z;
break;
}
}
}
System.out.println("Here is your old Array :");
for(int k : Array){
System.out.println(k);
System.out.println("Here is your new Bubble Sort Array :");
for(int q : newArray){
System.out.println(q);
}
}
}
}

In what cases would it be useful to put a command within a Java for-loop update statement? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I found out yesterday that you can make a Java for-loop that looks like this
for (int j = 0; j < myArray.length; System.out.println(j), j++ ) {
/* code */
}
This looks really unusual to me. When is coding like this acceptable/useful?
I would only ever do something like this if I had two loop variables, eg:
for(int i = 0, j = 10; i < 10 && j > 0; i++, j--) {
...
}
Apart from that, I would not recommend doing this as it obscures what the for loop is actually doing. It would be better to place any method calls with side effects inside the actual body.
This is equivalent to:
for (int j = 0; j < myArray.length; j++ ) {
System.out.println(j);
}
I dont see any advantage of using it other than to trick students in the exam. It could be useful to check if student understands the functioning of for loop thoroughly.
You may also do it this way
for (int j = 0; j < myArray.length; System.out.println(j++)) {
}
The official java documentation says the following about for-loops:
The general form of the for statement can be expressed as follows:
for(initialization; termination; increment) {
statement(s)
}
When using this version of the for statement, keep in mind that:
The initialization expression initializes the loop; it's executed once, as the loop begins.
When the termination expression evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment
or decrement a value.
So while it is possible to have something like System.out.println(j) in your increment part, it is against the coding conventions according to the official documentation.
The reason why it is allowed to have multiple comma-separated statements in the increment part is because you may need to adjust the value of multiple variables during the execution of the for loop. So only in this case it is both acceptable and useful to use this syntactic sugar. The following example illustrates this scenario:
for(int i = 0, j = 10; i < 10 && j >= 0; i++, j--) {
// Statements
}
One possible use for the ability to have two operations in the update statement, is that you can manipulate two variables simultaneously. Something like,
for (int i = 0, j = 10; i < 10 && j > 0; i++, j--) {
System.out.printf("i = %d, j = %d%n", i, j);
}
It actually gives the code more sense, makes it more readable. It is useful if you have need more than 1 instruction to be executed at the end of each iteration (like incrementing the loop counter). It is generally used to loop through multidimensional arrays.

OutOfMemoryError when trying to add to ArrayList at specified index [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 8 years ago.
Improve this question
I'm trying to do an insertion sort with an ArrayList of Strings:
private static ArrayList<String> sortList(ArrayList<String> list) {
ArrayList<String> newList = new ArrayList<String>();
String curWord, curOrdered;
int comparison;
for(int i=0; i < list.size(); i++) {
curWord = (String) list.get(i);
if(newList.isEmpty())
newList.add(curWord);
else {
for(int j=0; j < newList.size(); j++) {
curOrdered = (String) newList.get(j);
comparison = curWord.compareTo(curOrdered);
if(comparison < 0)
newList.add(j, curWord); // problem is here, heap runs out
else
newList.add(curWord);
}
}
System.out.println(i);
}
return newList;
}
However, I seem to run out of heap space when I try adding to my sorted ArrayList. My outer loop only seems to run once, but I can't figure out what exactly is going wrong.
Thanks!
Every time you are in the inner for loop you add a new element to newList. Since the loop condition specifies to continue while j < newList.size(), j starts out less than the size, and you add one to both every time, j never reaches newList.size() and you keep adding elements until the heap space runs out.

Out Of Bounds Expeption location (JAVA) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
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.
Closed 9 years ago.
Improve this question
Can someone help me understand where the out of bounds exeption is happening. The compiler said its here if(content[i] == delSub[j]) and out of bounds by 5. is that really where its happening and if so why?
char[] content = new char []{'A','B','C','D','E','F','G'};
//SubString = BCDEF
public int deleteSubString(String delSubString)
{
int count = 0;
char[] delSub = new char[delSubString.length()];
String temp = "";
for(int i = 0; i < content.length;i++)
{
for (int j = 0; i < delSub.length;j++)
{
if(content[i] == delSub[j])
{
temp = temp + content[i];
}
}
}
return 0;
//TODO configure return statement conditions
}
You're probably running out of the boundries of delSub[j] - since your condition in the inner loop checks the value of i instead of j
for (int j = 0; i < delSub.length;j++)
Should be:
for (int j = 0; j < delSub.length;j++)
(note the "j <" instead of "i <")
I guess you need to use j for the for condition match
for (int j = 0; i < delSub.length;j++)
I'm going to address just this part of your Question.
... is that really where its happening ...
Yes. It is. (See other answers for an explanation ...)
But more to the point, there is no good reason to doubt that that is where it is happening unless:
you have stuffed up, and the source code you are looking at doesn't match the code that you are running, or
there is a JVM bug that causes it to get the line number incorrect. And there isn't. Sun / Oracle JVMs give reliable line numbers in stack traces... for as long as I can remember.
In short - trust the evidence in a stacktrace.

Categories