Single Status Update
So I want the output to be this:
____5 (four spaces)
___45 (three spaces)
__345 (and so on...)
Using without more than 2 loops. Doesn't matter any language, but C or Java works.
int k = 5;
int l = 5;
int j = 5;
for(int i = 1; i <= k; i++)
if(i==l) //Do not need to print any more spaces
while(l<6) //Print all the numbers from l to 5
l=j; //Reduce the value of l to 1 less than its value before the loop
i=0; //Reset i
k--; //Reduce the number of spaces required on the next line
System.out.print(" "); // Print a spacebar
This will be the body of your main function. What the code does is it loops until it prints out 6 things per line. The moment i equals l it stops printing spaces and instead starts printing the numbers. k denotes the number of spaces to print per line. When the value of k becomes too small the loop exits.
This uses a single loop, and you can pass any number (and any output stream) you want into the function. The key is constructing the formatting string on the fly.
This is a simplified version that only write one line so you can more easily see the format string.
Faster version. Common Lisp is slow when working with lists (which I always found funny since "LISP" stands for "LISt Processor"), so I replaced that with just strings, which are vectors internally. Also, I forgot about the implicit loop in my FORMAT statement above, so I took that out. This is truly one loop now.
The number 9999 now takes 4.243 seconds on my Core i7, 0.080 of which went to the garbage collector.
- Show next comments 3 more