java boolean array and turning every third value to false [closed] - java

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 8 years ago.
Improve this question
The Boolean array is initialized to true. I need to know how to turn every third value to false and also going through the array over and over. It is essentially duck duck goose without the randomness.

This sounds like a beginners programming exercise, so I'm going to just give you a hint or two:
Go back to your textbook, lecture notes, tutorial and reread the stuff on for loops. Focus on the old style ones.
Think about how to write a for loop that steps through integer index values in the pattern that you require.
Re "... going through the array over and over" - not sure what you mean, but maybe the hint for this is to think about using nested loops; i.e. a loop inside another loop.
But the most important advice is to try and work this out for yourself.

Well I'm really not sure what you mean by going through the array over and over but the following code will turn every third value to false.
for (int i = 0; i < myVar.length; i++) {
if (i % 3 == 0) {
myVar[i] = false;
}
}
Edit: Oops someone beat me to it while I was typing lol.

Related

Optimization of java code for reducing complexity [closed]

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 5 years ago.
Improve this question
I am actually new to java libraries. I dont know what this code is doing.
I have been given a task to optimize this. Any help will be useful.
I mean to ask whether str.equals(local) checks for entire string aur for particular index value in the for loop.
public void fnc(String str, int[] ar1)
{
String local = "findnumber";
for(int i=0; i<ar1.length; i++)
{
if(str.equals(local) && ar1[i] * 2 > 10)
{
Integer ip = new Integer(ar1[i]);
ip = ip * 2;
System.out.print(ip.toString());
}
}
}
The big O complexity of the algorithm is O(N) where N is the array size. You cannot improve on that ... for the arguments provided and producing the same output.
There are some things that can be done to improve efficiency though.
Hint: look for a computation that is performed on each loop iteration that could be performed once.
Hint: look for some unnecessary object creation1
Hint: unnecessary use of a reference type.
There are one or two other questionable micro-optimizations, but see if you can spot them without any hints. (I say "questionable" because I suspect that the JIT compiler would do the same optimization itself.)
One final note: the actual speed of the code will be dominated by the print statement, and its ability of the OS to write stuff to (for example) the console. And probably by JVM startup / warmup effects ... unless the fnc method is called many times.
1 - Notwithstanding anything else, new Integer(...) is the wrong way to convert an int to an Integer.

Struggling to fix infinite loop [closed]

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 6 years ago.
Improve this question
I'm new to JUnit testing and I'm struggling to test a method that will search for a specific vehicle registration and output it that it is found
System.out.println("getSpecificVehicle");
CVMQueue instance = new CVMQueue();
VehicleNode newVehicle = new VehicleNode("YBZ5484", "Car", "Ire", 3, 2.2);
instance.enqueue(newVehicle);
String expResult = "YBZ5484";
String result = instance.getSpecificVehicle("YBZ5484");
assertEquals(expResult, result);
This is my code, It keeps looping in the Console.
How can I fix this?
Check your code; if you improve the formatting you find
while (temp != null) {
...
if (reg.equalsIgnoreCase(temp.getRegNum())) {
...
}
}
Your loop is never changing temp. So, why should it ever stop looping upon being entered? So, obviously your problem is that you missed that loop-closing brace; as you put that assignment to temp after that brace.
But the real take-aways here:
Formatting matters. Maybe, if you had put more diligence in writing down your code, you would have spotted this yourself much earlier. And as Gaket points out correctly: any sane IDE (or coding editor) probably has some "auto format" functionality, that well, formats your source code automatically.
Leading to: code readability matters even more. For example, there is the "Single layer of abstraction" principle; which would have told you to not just put that complete if into that loop; instead you would have created a method to do that work. And again, it would have been so much easier to spot this simple problem.
Learn about using a debugger. You see, the real power of unit tests is that they make it also so easy to isolate bugs: you put a breakpoint somewhere; and run your test in the debugger; and you can directly observe what is going on.

What is difference between below Code 1 & Code 2? [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 6 years ago.
Improve this question
Code 1
String ccMailAddresses="abc#co.in,xyz#co.in";
String ccMailAddressArray[]=ccMailAddresses.split(",");
for (int index = 0; index < ccMailAddressArray.length; index++) {
System.out.println(ccMailAddressArray[index]);
}
Code 2
String ccMailAddresses="abc#co.in,xy";
for (String ccMailAddress : ccMailAddresses.split(",")){
System.out.println(ccMailAddress );
}
Which is best practice ? Is any performance hit in any one of them ?
Obviously, the second piece of code is shorter and working on a higher level of abstraction - as it is using a for-each loop; instead of that counting-for loop.
In that sense: code2 requires less efforts for the reader to grasp what is going on. So, from that perspective, it is definitely "better" than code1.
Performance wise, there shouldn't be any different between the two.
The code does nearly the same thing. The if-statement in Code1 is useless. In my opinion this is alway true.
The difference is betweeen those two line:
for (int index = 0; index < ccMailAddressArray.length; index++)
Here your code will be executed until your index is bigger than the lenght of your array.
for (String ccMailAddress : ccMailAddresses.split(","))
The code in this loop is executed for every element in your array.
But keep in mind the result is the same!
hope that helps!
No difference between both code:
code1 is traditional for loop , and code2 is for each loop introduced for java collection to iterate.
Code 1
String ccMailAddresses="abc#co.in,xyz#co.in";
String ccMailAddressArray[]=ccMailAddresses.split(",");
if(ccMailAddressArray!=null){
for (int index = 0; index < ccMailAddressArray.length; index++) {
System.out.println(ccMailAddressArray[index]);
}
}
In this example you make an unnecessary check against ccMailAddressArray because split() will never return null. The for loop here provides you an index. This can be useful sometimes e.g. if you have a color array that has a color stored for each element. Then you could use color[index] to select the color for each element and draw it somewhere. Please now, that this is a bit more complex than just iterating over all items. So you use this version whenever you need the index.
Code 2
String ccMailAddresses="abc#co.in,xy";
for (String ccMailAddress : ccMailAddresses.split(",")){
System.out.println(ccMailAddress );
}
In this example you do essentially the same. The for-each loop you're using here does the same for you. The only difference is that you don't have the index here. It's just a bit shorter and simpler which makes it also easier to read.
So: Use for-each (Code 2) whenever you can because it is a bit simpler to understand what you are dong. If you use the index based for loop (Code 1) I assume you want to do something with index which also implies that some more complicated things may be involved.
Thanks for an answer stackoverflowgigs.
My question is solved now!. As one of my senior gave me the review comment about code 2 is performance hit by repeatedly calling ccMailAddresses.split(",") in for each loop.

How can I go through several possibilities without exhausting loops? [closed]

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
How can I go through several possibilities without exhausting loops in a program that sum of the proper divisors(divisors including 1 but not itself) of the number is greater than the number, but no subset of those divisors sums to the number itself.
For Example:
12=(factors sum)1+2+3+4+6
Atleast Any Subset Sum should be equal to the number i.e 12 in this case.
Question link
:http://www.practice.geeksforgeeks.org/problem-page.php?pid=301
Approach:
Step1 (Doubt)
By looking at the problem I found that its optimal solution will be Dynamic Programming.(Since I don't know that).
Apart from that I thought of the solution like this
For Example 12=1,2,3,4,6(divisors)
So,Solving it through like this with 1 starting having all permutations: 1+2+3+4+6 or 1+3+4+6 or 1+4+6 or 1+6(checking at each step whether it is <=12.
Similarly,I checked starting with 2: 2+3+4+6 or 2+4+6(I got and moved out of the loop)
The solution I am thinking here is very long.I have to put seperate loop for each number and also I am saving the divisors in a string.
Can anyone give me "Hint" how to start the problem without the Dynamic Programming(Dp) approach as I am learning Dp these days.
I assume you have a method
int[] getDivisors(int number)
the hard task here is to evaluate the possible sums.
An easy but long way would be, to iterate over all of those like that.
Think of such a sum as a binary code, 1 if its in sum, 0 if its not.
Now you can write a for-loop which, from 0...0 to 1...1 (in binary) with #1s = divisors.length;
Maybe a better way would be recursion methods. Like:
boolean hasSameSum(int number, Stack<Integer> divisors, int sum){
if(sum==number)
return false;
if(divisors.isEmpty())
return true;
int div = divisor.pop();
return hasSameSum(number, divisors, sum)&&hasSameSum(number, divisors, sum+div);
}
But honestly, that's not a programming problem, but more a mathematical approach problem :-)

At what point does writing, maintaining and most importantly the overhead of a function become a viable alternative to repeated code? [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've been wondering this for a while, and thought I'd pose the question today.
Example code:
private void createLinks(int numUsers) {
for (int i = 1; i <= numUsers; i++) {
String userId = "ID-" + i;
String randomId;
// Generate an ID to link to.
do {
randomId = "ID-" + random.nextInt(i);
} while (randomId.equals(iUserId));
link(userId, randomId); //links the first argument to the second,
//links are not bi-directional.
// Generate 4 more ID's to link to.
for (int j = 1; j <= 4; j++) {
do {
randomId = "ID-" + random.nextInt(i);
} while (randomId.equals(iUserId));
link(userId, randomId);
link(randomId, userId);
}
// Generate another ID to link
do {
randomId = "ID-" + random.nextInt(i);
} while (randomId.equals(iUserId));
link(randomId, userId)
}
}
#createLinks is invoked a lot, and the do...while code snippet is being repeated in the method. Does it make sense to extract these 3 lines of code out to a method called generateRandomId(int i) and incur the function overhead to avoid this repetition? If createLinks gets invoked a 100 times, generateRandomId would get invoked 100*6 = 600 times.
This is more a language agnostic question rather than one specific to java, but it'd be interesting to know if some languages handle function overhead better than others. E.g. JVM does function inlining to optimize function calls, which might mean that a developer need not wonder about things that I mentioned above.
This is definitely opinion-based question, and I expect it will be closed. But I'll try to answer it anyway, because it's quite frequently asked.
If you want simple answer – don't bother about it. It's probably too soon. Really, the manner you ask a question tells me that you have a lack of information about how frequently this code will be called and how slow it really is. And it's ok. We all face this situation when there are just a lot of unknowns in the context of development. The trick is – those unknown will become knowns in operation context (when your code is actually running). You'll get a feedback about performance issues if any. It should be said, getting this feedback is not so simple task by itself and requires some skills and mature toolchain. But it's not the question you asked.
Does I advocate skip any performance optimization while developing? Of course no, it's silly. There are issues which could and should be solved early. I'm just advising to follow simple and straightforward principle:
If you're in doubt – wait for reality to show you the right way.
This principle could be misused as any other. But I hope you get my point – premature optimization is the root of all evil, right?
My opinionated answer is "always." Whenever I find myself writing the same code twice, I make it a function.
The point where this practice ceases to be opinion-based is when two pieces of code doing exactly the same thing is important to the proper operation of the program.

Categories