I have to use multiple nested loops in jGRASP to get the desired output. When I put this:
SQUARE
I have to get this:
SQUARE
Q R
U A
A U
R Q
ERAUQS
My code so far:
String output="";
output+= word;
for (int i = 1; i < word.length()-1; i++)
{
output+= word.charAt(i)+"\n";
for (int j = 0; j < word.length() - 2; j++)
{
output += " ";
}
output += (word.length() - i - 1);
}
StringBuffer s = new StringBuffer(word);
output+= s.reverse();
but my output is:
squareq
4u
3a
2r
1erauqs
How to fix the inner region?
It is the inner for-loop that needs help.
Should I define the StringBuffer before and reverse it and use charAt()?
I tried that and I keep getting the "cannot find symbol" error.
I am new to this site and I apologize for any inconsistencies.
It took me only to modify 2 lines of your code, so it was pretty good.
Here is your commented solution:
String output="";
output+= word+"\n";
for (int i = 1; i < word.length()-1; i++)
{
output+= word.charAt(i); //removed new line
for (int j = 0; j < word.length() - 2; j++)
{
output += " ";
}
output += word.charAt(word.length() - i - 1)+"\n"; //added charAt and new line at the end
}
StringBuffer s = new StringBuffer(word);
output+= s.reverse();
The result looks like expected:
SQUARE
Q R
U A
A U
R Q
ERAUQS
Related
I'm trying to find the time complexity for 3 nested for loops. I'm a little lost on how to do this because the the first and third are dependent. From what I did I found that the pattern is n(1 + 2 + 3) so O(n^2) but I'm unsure if that's right. I'm also unsure if this includes the j loop or would I have to multiply a n to my current answer. Any help is much appreciated.
for (int i = 0; i < n*n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < i; k++) {
// print some statement here
}
}
}
Short Answer:
Assuming the innermost loop operation is O(1), the time compexity of your code is O(n^5).
Longer Answer:
Let's start with a simpler example of 2 dependent loops:
for (int i=0; i<n; ++i) {
for (int j=0; j<i; ++j) {
// Some O(1) operation
}
}
The outer loop will run n times and the inner loop will run 1...n times, and on average:
(1 + 2 + ... + n)/n = n(n+1)/2/n = O(n)
So the overall complexity for this simpler example is O(n^2).
Now to your case:
Note that I assumed the operation in the innermost loop is done in O(1).
for (int i=0; i< n*n; i++){
for (int j=0; j<n; j++){
for (int k=0; k<i; k++){
// Some O(1) operation
}
}
}
The 1st outer loop will run n^2 times.
The 2nd outer loop (i.e. the middle loop) will run n times.
So the 2 outer loop together will run in O(n^3).
The number of times the inner loop will run on average is now O(n^2) because the number of iterations will now be 1..n^2 (instead of 1..n):
(1 + 2 + ... n^2)/n^2 = (n^2)(n^2+1)/2/(n^2) = O(n^2).
Therefore the overall time complexity is O(n^5).
Addendum:
The code below is not in any case a proof regarding the complexity, since measuring for specific values of n does not prove anything about the asymptotic behavior of the time function, but it can give you a "feel" about the number of operations that are done.
#include <iostream>
#include <ctype.h>
void test(int n)
{
int64_t counter = 0;
for (int i = 0; i < n * n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < i; k++) {
counter++;
}
}
}
std::cout << "n:" << n << ", counter:" << counter << std::endl;
}
int main()
{
test(10);
test(100);
test(1000);
}
Output:
n:10, counter:49500
n:100, counter:4999500000
n:1000, counter:499999500000000
I believe it is quite clear that the number of operations is close to n^5/2, and since constants like 1/2 do not apply: O(n^5).
I'm referring to the leetcode question: Kth Smallest Element in a Sorted Matrix
There are two well-known solutions to the problem. One using Heap/PriorityQueue and other is using Binary Search. The Binary Search solution goes like this (top post):
public class Solution {
public int kthSmallest(int[][] matrix, int k) {
int lo = matrix[0][0], hi = matrix[matrix.length - 1][matrix[0].length - 1] + 1;//[lo, hi)
while(lo < hi) {
int mid = lo + (hi - lo) / 2;
int count = 0, j = matrix[0].length - 1;
for(int i = 0; i < matrix.length; i++) {
while(j >= 0 && matrix[i][j] > mid) j--;
count += (j + 1);
}
if(count < k) lo = mid + 1;
else hi = mid;
}
return lo;
}
}
While I understand how this works, I have trouble figuring out one issue.
How can we be sure that the returned lo is always in the matrix?
Since the search space is min and max value of the array, the mid need NOT be a value that is in the array. However, the returned lo always is.
Why is this happening?
For the sake of argument, we can move the calculation of count to a separate function like the following:
bool valid(int mid, int[][] matrix, int k) {
int count = 0, m = matrix.length;
for (int i = 0; i < m; i++) {
int j = 0;
while (j < m && matrix[i][j] <= mid) j++;
count += j;
}
return (count < k);
}
This predicate will do exactly same as your specified operation. Here, the loop invariant is that, the range [lo, hi] always contains the kth smallest number of the 2D array.
In other words, lo <= solution <= hi
Now, when the loop terminates, it is evident that lo >= hi
Merging those two properties, we get, lo = solution = hi, since solution is a member of array, it can be said that, lo is always in the array after loop termination and will rightly point to the kth smallest element.
Because We are finding the lower_bound using binary search and there cannot be any number smaller than the number(lo) in the array which could be the kth smallest element.
I want to know how this while loop exits? Because i and j are not incremented anywhere except at s.charAt(j++) and s.charAt(i++) which is to find char at j or ith position. Does that also increment j and i? In my opinion it should only give you the character code at j++ or i++ th position isn't it so?
public class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
Set<Character> set = new HashSet<>();
int ans = 0, i = 0, j = 0;
while (i < n && j < n) {
// try to extend the range [i, j]
if (!set.contains(s.charAt(j))){
set.add(s.charAt(j++));
ans = Math.max(ans, j - i);
}
else {
set.remove(s.charAt(i++));
}
}
return ans;
}
}
Yes using i++ increments the value of i.
If you want to find character at next position than i, then you can simply use another variable and store i+1 value in it and use that to access character. Like this:
z = i+1;
set.add(s.charAt(z));
using post-increment or pre-increment always changes the value of increment variable and only differ as to when they increment the increment variable's value.
I'm trying to find a solution to this coding problem:
Create a for loop that will begin with a value of 5 and end with a value of 25. In each iteration, add the incrementing value to mathTotal. (HINT: the last value used INSIDE the loop should be 25)
But the way I can think of doing it returns with a final number for mathTotal of 26. I'm not sure how to manipulate the code to stop at 25 without actually doing the math to figure out what number to make the condition for the program to stop running.
This is what I have:
int mathTotal;
for(int i = 5; mathTotal <=25; i++) {
mathTotal = mathTotal + i;
}
I know this is a simple problem, but I'm learning how to code and don't want to move on without fully understanding something.
Thank you!
There are two major issues:
mathTotal is not initialized. You have to set an initial value.
int mathTotal = 0;
The upper border (the second parameter of the for loop) is defined as mathTotal <= 25 – rather than i <= 25 – which will be reached when i is 8.
for (int i = 5; i <=25; i++) {
mathTotal = mathTotal + i;
}
The traditional for loop in Objective-C is inherited from standard C and takes the following form:
for (/* Instantiate local variables*/ ; /* Condition to keep looping. */ ; /* End of loop expressions */)
{
// Do something.
}
For example, to print the numbers from 1 to 10, you could use the for loop:
for (int i = 1; i <= 10; i++)
{
NSLog(#"%d", i); //do something
}
This is logically equivilant to the following traditional for loop:
for (int i = 0; i < [yourArray count]; i++)
{
NSLog([myArrayOfStrings objectAtIndex:i]);
}
Your Doubt
int mathTotal = 0;
for (i = 5 = 0; i <=25 ; i++)
{
mathTotal = mathTotal + i;
}
Can anyone tell me the most efficient/performant method to access 2D seismic data using Ocean?
For example, if I need to perform a calculation using data from 3x2D seismic lines (all with the same geometry) is this the most efficient way?
for (int j = 0; j < seismicLine1.NumSamplesJK.I; j++)
{
ITrace trace1 = seismicLine1.GetTrace(j);
ITrace trace2 = seismicLine2.GetTrace(j);
ITrace trace3 = seismicLine3.GetTrace(j);
for (int k = 0; k < seismicLine1.NumSamplesJK.J; k++)
{
double sum = trace1[k] + trace2[k] + trace3[k];
}
}
Thanks
A followup to #Keith's suggestion - with .NET4 his code could be refactored to a generic:
public static IEnumerable<Tuple<T1, T2, T3>> TuplesFrom<T1,T2,T3>(IEnumerable<T1> s1, IEnumerable<T2> s2, IEnumerable<T3> s3)
{
bool m1, m2, m3; // "more" flags
using (var e1 = s1.GetEnumerator())
using (var e2 = s2.GetEnumerator())
using (var e3 = s3.GetEnumerator())
while ((m1 = e1.MoveNext()) &&
(m2 = e2.MoveNext()) &&
(m3 = e3.MoveNext()))
yield return Tuple.Create(e1.Current, e2.Current, e3.Current);
if (m1 || m2 || m3)
throw new ArgumentException(); // sequences of unequal lengths
}
Which gives:
foreach (var traceTuple in TuplesFrom(seismicLine1.Traces, seismicLine2.Traces, seismicLine3.Traces))
for (int k = 0; k < maxK; ++k)
sum = traceTuple.Item1[k] + traceTuple.Item2[k] + traceTuple.Item3[k];
What you have will work except for the two bugs I see, but it can also be made slightly faster. First the bugs. Your loops should be testing NumSamplesIJK.J not .I for the outer loop and .K, not .J for the inner loop. The .I is always 0 for 2D lines.
You can get a slight performance lift by minimizing the dereference of the NumSamplesIJK properties. Since the geometries are the same you should create a pair of variables for the J and K properties and use them.
int maxJ = seismicLine1.NumSamplesIJK.J;
int maxK = seismicLine1.NumsamplesIJK.K;
for (int j = 0; j < maxJ; j++)
...
for (int k = 0; k < maxK; k++)
...
You might also consider using the Traces enumerator instead of calling GetTrace. It will process the data in trace ascending order. Unfortunatley with three lines the code is a bit harder to read.
int maxK = SeismicLine1.NumSamplesIJK.K;
IEnumerator line2Traces = seismicLine2.Traces.GetEnumerator();
ITrace line2Trace = line2Traces.MoveNext();
IEnumerator line3Traces = seismicLine3.Traces.GetEnumerator();
ITrace line3Trace = line3Traces.MoveNext();
foreach (ITrace line1Trace in seismicLine1.Traces)
{
for (int k = 0; k < maxK; k++)
{
double sum = line1Trace[k] + line2Trace[k] + line3Trace[k];
}
line2Trace = line2Traces.MoveNext();
line3Trace = line3Traces.MoveNext();
}
I don't know what, if any, performance lift this might provide. You'll have to profile it to find out.
Good luck.