How can I print consecutive integers greater than 0, three per line? - java

How to loop this?
I'm trying to loop this:
0-> 1,2,3
1-> 4,5,6
2-> 7,8,9
3-> 10,11,12
4->.....
......
I don't know how to write this algorithm.
I tried below, it doesn't work.
public class gYie {
public static void main(String[] args) {
int current = 0;
int death = 0;
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
for (int j = 0; j < 3; j++) {
System.out.print(death+j +" ");
current += j;
}
death += current;
System.out.println("");
}
}
}
Its Output is:
run:
0 0 1 2
1 3 4 5
2 9 10 11
3 18 19 20
4 30 31 32
5 45 46 47
6 63 64 65
7 84 85 86
8 108 109 110
9 135 136 137
How to solve this? I can't think how to write it.
3 becomes 18,19,20 instead of 12,13,14.

Looks suspiciously like homework, so here's some pseudo-code (actually Python) that will do the trick for you:
for outer in range (10):
print "%d ->"%(outer),
for inner in range (3):
print "%2d"%(outer * 3 + inner + 1),
print
The basic idea is to simply have an inner loop of 0 through 2 inclusive and an outer loop that increases by one each time. Then the formula:
outer * 3 + inner + 1
gives you the values you want:
0 -> 1 2 3
1 -> 4 5 6
2 -> 7 8 9
3 -> 10 11 12
4 -> 13 14 15
5 -> 16 17 18
6 -> 19 20 21
7 -> 22 23 24
8 -> 25 26 27
9 -> 28 29 30

You're overthinking it. For the left-hand side, all you need to print is i. For the right-hand side , you just need a single variable current that gets incremented every time its printed:
int current = 1;
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
for (int j = 0; j < 3; j++) {
System.out.print(current + " ");
current ++;
}
System.out.println();
}
}

Try this
int loopCount = 1;
for(int a = 1; a < 21; a++){
System.out.println(a);
for(int b = 0; b < 3; b++){
System.out.print((loopCount++) + " ");
}
System.out.println();
}
Edit: But I guess I found a more efficient way by using a single loop
int x = 1;
for(int a = 0; a < 21; a++){
System.out.println(a + " -> " + (x) + " " + (x + 1) + " " + (x + 2));
x = x + 3;
}
now you can merge it with your variables and logic

Here is a solution with a single loop:
int n = 15;
for (int i = 0; i < n; i++) {
if (i % 3 == 0) {
System.out.println();
}
System.out.print(i + " ");
}

You need to do something like this. Just keep printing the current.
int current = 1;
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
for (int j = 0; j < 3; j++) {
System.out.print(current +" ");
current ++;
}
System.out.println();
}

this should do the job...
public class gYie {
public static void main(String[] args) {
for (int i = 0, j = 1; i < 10; i++) {
System.out.print(i + " ");
for (int h = 0; h < 3; h++, j++) {
System.out.print(j +" ");
}
System.out.println("");
}
}
}

You can just simplify your code as follows :
public static void main(String[] args) {
int death = 3;
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
death = 3*i;
for (int j = 1; j <= 3; j++) {
System.out.print(death+j +" ");
}
System.out.println("");
}
}
}
You will now get the output as :-
0 1 2 3
1 4 5 6
2 7 8 9
3 10 11 12
4 13 14 15
5 16 17 18
6 19 20 21
7 22 23 24
8 25 26 27
9 28 29 30

Use a simple counter:
int j = 0;
for (int i = 0; i < 10; i++)
System.out.println(i + " " + ++j + " " + ++j + " " + ++j + " ");

There is a lot of nested loops above. Here's a scalable solution within a single for loop.
public static void main(String[] args) {
int numbersPerLine = 3;
int finalNumber = 12;
int startingRowNumber = 0;
System.out.print(startingRowNumber + " -> ");
for(int i = 0; i < finalNumber; i++) {
if(i > 0 && (i % numbersPerLine) == 0) {
System.out.print("\n" + ((i / numbersPerLine) + startingRowNumber) + " -> ");
} else if(i > 0) {
System.out.print(",");
}
System.out.print((i + 1));
}
}

Change your code like this.
int death = 1;
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
for (int j = 0; j < 3; j++) {
System.out.print(death++ +" ");
//current += j;
}
//death += current;
System.out.println("");
}

Got exact solution for it ...
class Alok{
public static void main(String[] args){
int i = 0,j=0;
for(i=0;i<10;i++){
System.out.print(""+i+"->");
for(j=(i*3)+1;j<(i*3)+4;j++){
System.out.print(""+j+" ");
}System.out.println();
}
}
}

Related

Java Pattern of 1 row odd and 1 row even

I want to print a pattern like :
Till now i have been able to achieve only for odd numbers like :
1
3 5 7
-
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
while (num % 2 == 0 || num < 0) {
num = kb.nextInt();
}
int odd = 1;
for (int i = 1; i <= num; i += 2) {
String a = "";
for (int j = 1; j <= i; j++) {
a = odd + " ";
odd += 2;
System.out.print(a);
}
System.out.println();
}
I am a beginner and new learner. please help
I'm not sure what's the expected result since that pattern is not clear, however this might be what you're looking for:
int evenCounter = 1;
int oddCounter = 2;
for (int i = 1; i <= 10; i++) {
boolean even = (i % 2 == 0);
for (int j = 1; j < i; j++) {
System.out.print((even ? evenCounter : oddCounter) + " ");
evenCounter += even ? 2 : 0;
oddCounter += even ? 0 : 2;
}
System.out.println();
}
Result:
1
2 4
3 5 7
6 8 10 12
9 11 13 15 17
14 16 18 20 22 24
19 21 23 25 27 29 31
26 28 30 32 34 36 38 40
33 35 37 39 41 43 45 47 49
If the length of each row matters, then the second for loop should have a different exit condition I suppose
To get the pattern from 3 5 7, this code would do, where MAX_PATTERN_NUM is the first number of the last line of the pattern (in your example's case, MAX_PATTERN_NUM = 15)
for(int i = 3; i <= MAX_PATTERN_NUM ; i+=3)
for(int j = i; j <= (i + 4); j+=2)
System.out.print(j + " ");
System.out.println();
However, I see no logical way of getting the entire pattern using the same nested for loops, so I hope this helps
How about this:
public void printPattern(){
int evenCounter = 2;
int oddCounter = 1; //counters
Scanner kb = new Scanner(System.in);
int num = kb.nextInt();
while (num % 2 == 0 || num < 0) {
num = kb.nextInt(); //input
}
for(int i = 1; i <= num ; ++i){
if(i % 2 == 0)
evenCounter = addNumbers(i, evenCounter); //print line with evenCounter
else
oddCounter = addNumbers(i, oddCounter); //print line with oddCounter
}
}
private int addNumbers(int i, int counter){
for(int j = 0; j < i;){
if(getIntLength(counter) + j > i) //if the number to long
System.out.print(cut(counter, getIntLength(counter) + j - i) + " "); //output the cut version
else
System.out.print(counter + " ");
j += getIntLength(counter);
counter += 2;
}
System.out.println();
return counter;
}
private String cut(int i, int length){
return Integer.toString(i).substring(0,length); //get substring of int
}
private int getIntLength(int i){
return Integer.toString(i).length(); //get the length of int value
}
It's not so simple, but I don't see an easier way
My answer is based on the assumption that the last 2 is a cut off 21
int n,i,j,o=1,e=2;
System.out.println("enter n:");
n=sc.nextInt();
for(i=1;i<=n;i++){
for(j=1;j<=i;j++){
if(i%2!=0){
System.out.print(o);
o+=2;
}
if(i%2==0){
System.out.print(e);
e+=2;
}
}
System.out.println();
}

Finding the Last 10 Elements in a Array

Hey guys so I have to find the last 10 elements in my array in my .txt file filled with unsorted primes. The problem I'm having is the code I'm using to get the last 10 elements is just returning the same number instead of the last ten digits. If anyone can help me figure it out that would be great.
Also i have looked through some other code to figure it out, but i had no luck. If you do answer please don't just answer with a link to someone else code. Thanks
Heres my code so far:
public class BubbleSort {
static long BubbleSortCount = 0;
public static void main(String[] args) throws IOException {
System.out.print("This program compares the bubble, selection, merge sorts.\n"
+ "The data set is 78498 unsorted integers (prime numbers less than 1,000,000)\n\n");
File file = new File("primes1.txt");
Scanner infile = new Scanner(file);
ArrayList<Integer> Primes1 = new ArrayList<Integer>();
int temp;
long startTime, endTime;
int n;
while (infile.hasNextInt()) {
n = infile.nextInt();
Primes1.add(n);
}
// bubble
System.out.print("BUBBLE SORT\n");
System.out.println("\nPrimes Read : " + Primes1.size());
startTime = System.currentTimeMillis();
Primes1 = Bubble(Primes1);
endTime = System.currentTimeMillis();
System.out.println("Elapsed Seconds = "
+ (double) ((endTime - startTime) / 1000.0));
System.out.println("iterations = " + BubbleSortCount++);
System.out.print("First 10 sorted : ");
for (int i = 0; i < 10; i++) {
System.out.print(Primes1.get(i) + " ");
}
System.out.println();
System.out.print("Last 10 sorted : ");
for (int i = 0; i < 10; i++) {
System.out.print(Primes1.get(Primes1.size() - 1) + " ");
}
}
// Bubble sort Method
public static ArrayList<Integer> Bubble(ArrayList<Integer> Primes1) {
int temp;
for (int i = 0; i < Primes1.size() - 1; i++) {
for (int j = 0; j < Primes1.size() - 1; j++) {
BubbleSortCount++;
if (Primes1.get(j) > Primes1.get(j + 1)) {
temp = Primes1.get(j);
Primes1.set(j, Primes1.get(j + 1));
Primes1.set(j + 1, temp);
}
}
}
return Primes1;
}
}
Here are the numbers in my .txt file.
7
2
47
13
11
59
17
41
37
23
29
31
19
53
43
241
251
257
263
269
271
277
281
283
293
System.out.print(Primes1.get(Primes1.size() - 1) + " ");
With the 1 it will always take the same number, should be fixed
System.out.print(Primes1.get(Primes1.size() - i) + " ");
Change:
for (int i = 0; i < 10; i++) {
System.out.print(Primes1.get(Primes1.size() - 1) + " ");
}
To:
for (int i = 0; i < 10; i++) {
System.out.print(Primes1.get(Primes1.size() - (i+1)) + " ");
}
Or:
for (int i = 1; i <= 10; i++) {
System.out.print(Primes1.get(Primes1.size() - i) + " ");
}
The reason you get the same number is that you never use the index in the for-loop to get the 10 last.
This:
System.out.print("Last 10 sorted : ");
for (int i = 0; i < 10; i++) {
System.out.print(Primes1.get(Primes1.size() - 1) + " ");
}
must be changed to use the loop index variable. This should do it:
System.out.print("Last 10 sorted : ");
for (int i = 0; i < 10; i++) {
System.out.print(Primes1.get(Primes1.size() - 10 + i) + " ");
}
Another way would be to use the sublist method from the List interface to produce a new list with the 10 last elements, like this:
List<Integer> last10list = Primes1.subList(Primes1.size() - 11, Primes1.size());

Java program finding another technique.print (1 to 50) in 5 rows and 10 column

(1)
public static void main(String[] args)
{
for (int i = 1; i <= 50; i++)
{
System.out.print(i);
if ((i %10=0)
System.out.println();
}
}
***************************************...
(2)
public static void main(String[] args) {
for (int i = 1; i <= 50; i++) {
System.out.print(i);
if ((i == 10) || (i == 20) || (i == 30) || (i == 40) || (i==50) {
System.out.println();
}
}
In (2) program i want to use loop or something else where (i==j),.where j contains values 10,20,30,40,50.
if(i==j){
System.out.println();
}
I want to do such because if i want to print from 1 to 100
then i have to type(i==10)(i==20)(i==30) .. till(i==100).
so I want to use loop in if boolean statement if(i==j) where j can be a loop having values of j=j+10
I hope you understand my question.
Here are 4 ways of doing it.
All 4 versions use printf("%2d ", i) to print result nicely aligned, like this:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
First, a corrected version of your #1, where comparison was fixed to use ==.
for (int i = 1; i <= 50; i++) {
System.out.printf("%2d ", i);
if (i % 10 == 0)
System.out.println();
}
Second, a version that will use i == j for ending the lines, which I believe is what you were looking for.
for (int i = 1, j = 10; i <= 50; i++) {
System.out.printf("%2d ", i);
if (i == j) {
System.out.println();
j += 10;
}
}
Third, a way to do it using two nested loops, using a separate num variable for the value to be printed.
for (int i = 1, num = 1; i <= 5; i++) {
for (int j = 1; j <= 10; j++, num++)
System.out.printf("%2d ", num);
System.out.println();
}
Fourth, another way to do the two nested loops, without a separate variable for the value to be printed.
for (int i = 1; i <= 50; i += 10) {
for (int j = i; j <= i + 9; j++)
System.out.printf("%2d ", j);
System.out.println();
}
Try this snippet:
StringBuilder builder = new StringBuilder();
for (int i = 1; i <= 50; i++) {
char c = i % 10 == 0 ? '\n' : '\t';
builder.append(i + String.valueOf(c));
}
System.out.println(builder.toString());
This way you don't have to write all the conditions (i == 10, i == 20 ...):
public static void main(String[] args) {
for (int i = 1, j = 10; i <= 50; i++) {
System.out.print(i);
if (i == j) {
j += 10;
System.out.println();
}
}
}

Using of 2 while to get this

I have 2 questions:
1: How can get the result below using two while loops?
2
4 2
6 4 2
8 6 4 2
10 8 6 4 2
12 10 8 6 4 2
14 12 10 8 6 4 2
16 14 12 10 8 6 4 2
2: How would I do it using two for loops?
It's basic algorithm, you should find some tutorials if you don't know loops in Java
With while:
int i = 2;
while (i <= 16) {
int j = i;
while (j > 0) {
System.out.print(j + " ");
j -= 2;
}
System.out.println();
i += 2;
}
With for:
for (int i = 2; i <= 16; i += 2) {
for (int j = i; j > 0; j -= 2) {
System.out.print(j + " ");
}
System.out.println();
}
I would use code (two for loops example):
for(int i = 0; i < 8; i++) {
for(int k = (i+1); k > 0; --k) {
System.out.print(k*2+" ");
}
System.out.println();
}
and two while loops:
int i = 0, j;
while(i < 8) {
j = (i+1);
while(j > 0) {
System.out.print(j*2+" ");
j--;
}
System.out.println();
i++;
}
for and while loops are similar, they are differ only by construction.

Pascal's triangle positioning

I made a Java program that prints out a pascal triangle, however I can't figure out how to correctly position it.
Program 1
public class Triangle {
public static void main() {
System.out.println("\nTriangle: ");
int row = 11;
long[][] triangle = new long[row][row];
triangle[1][1] = 1;
System.out.print(triangle[1][1] + "\n");
for (int i = 2; i < row; i++) {
for (int n = 1; n < row; n++) {
triangle[i][n] = triangle[i-1][n-1] + triangle[i-1][n];
if (triangle[i][n] > 0) {
System.out.print(triangle[i][n] + " ");
}
}
System.out.println();
}
}
}
Output:
1
1 1
1 2 1
1 3 3 1
Program 2
public class Triangle {
public static void main() {
System.out.println("\nTriangle: ");
int row = 11;
long[][] triangle = new long[row][row];
int x = 1;
while (x < row - 1) {
System.out.print(" ");
x++;
}
triangle[1][1] = 1;
System.out.print(triangle[1][1] + "\n");
for (int i = 2; i < row; i++) {
x = i;
while (x < row - 1) {
System.out.print(" ");
x++;
}
for (int n = 1; n < row; n++) {
triangle[i][n] = triangle[i-1][n-1] + triangle[i-1][n];
if (triangle[i][n] > 0) {
System.out.print(triangle[i][n] + " ");
}
}
System.out.println();
}
}
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1 //(Notice this line is incorrectly positioned)
When the triangle approaches multiple digit numbers, it starts to break down and makes it ugly. Can someone explain how I can display a normal triangle instead of this ugly one?
Dynamic Pascal Triangle generator is here:
import java.io.IOException;
import java.util.Scanner;
public class Main {
static double fact(int n) {
double result = 1;
for (double i = 1; i <= n; i++)
result *= i;
return result;
}
static double combine(int n, int r) {
return ((fact(n)) / (fact(n - r) * fact(r)));
}
static void pascalTriangle(int n) {
int n2 = n;
for (int i = 0; i < n; i++) {
for (int space = 8 * (n2 - 1); space >= 0; space--) {
System.out.printf(" ");
}
for (int j = 0; j <= i; j++) {
System.out.printf("%14.0f", combine(i, j));
System.out.printf(" ");
}
System.out.println();
n2--;
}
}
public static void main(String[] args)
throws IOException, InterruptedException {
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.print("Enter Number of Lines(n): ");
int n = sc.nextInt();
pascalTriangle(n);
System.out.println("Press any key to exit! ");
sc.nextByte();
}
}
Try this ...
Results:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
import java.util.*;
public class HelloWorld {
static int binCoeff(int n, int k) {
int res = 1;
if (k > n - k)
k = n - k;
for (int i = 0; i < k; ++i) {
res *= (n - i);
res /= (i + 1);
}
return res;
}
static void pascalTriangle(int lines) {
for (int i = 0; i < lines; i++) {
for (int j = 0; j <= i; j++)
System.out.print(HelloWorld.binCoeff(i, j) + " ");
System.out.println();
}
}
public static void main(String[] args) {
System.out.println("Results: ");
HelloWorld.pascalTriangle(8);
}
}
/**
* #author Ranjith
*/
public class JavaApplication2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int i;
int x;
int n = 15; //number of rows
String newLine = System.getProperty("line.separator");
for (i = 0; i < n; i++) { //loop to adjust spacing
x = i;
while (x < n - 1) {
System.out.print(" ");
x++;
}
fib(i); //fibonacci function is called
System.out.print(newLine);
}
}
public static void fib(int num) { //fibonacci function
int[] febo = new int[100];
febo[0] = 0;
febo[1] = 1;
for (int i = 2; i < num; i++) {
febo[i] = febo[i - 1] + febo[i - 2];
}
for (int i = 0; i < num; i++) {
System.out.print(febo[i] + " ");
}
}
}
Output:
0
0 1
0 1 1
0 1 1 2
0 1 1 2 3
0 1 1 2 3 5
0 1 1 2 3 5 8
0 1 1 2 3 5 8 13
0 1 1 2 3 5 8 13 21
0 1 1 2 3 5 8 13 21 34
0 1 1 2 3 5 8 13 21 34 55
0 1 1 2 3 5 8 13 21 34 55 89
0 1 1 2 3 5 8 13 21 34 55 89 144
0 1 1 2 3 5 8 13 21 34 55 89 144 233
You can represent such a triangle as a 2d array, where the elements of the first row and column are equal to one, and all other elements are the sum of the previous element in the row and column.
arr[i][j] = arr[i][j-1] + arr[i-1][j];
Then you can position it in the upper left corner as follows:
1 1 1 1 1 1 1 1 1
1 2 3 4 5 6 7 8
1 3 6 10 15 21 28
1 4 10 20 35 56
1 5 15 35 70
1 6 21 56
1 7 28
1 8
1
Try it online!
public static void main(String[] args) {
int n = 9;
// an array of 'n' rows
int[][] arr = new int[n][];
// iterate over the rows of the array
for (int i = 0; i < n; i++) {
// a row of 'n-i' elements
arr[i] = new int[n - i];
// iterate over the elements of the row
for (int j = 0; j < n - i; j++) {
if (i == 0 || j == 0) {
// elements of the first row
// and column are equal to one
arr[i][j] = 1;
} else {
// all other elements are the sum of the
// previous element in the row and column
arr[i][j] = arr[i][j - 1] + arr[i - 1][j];
}
}
}
// formatted output
for (int[] row : arr) {
for (int el : row) {
// formatting as a number with a trailing space
System.out.printf("%2d ", el); // two-digit number
// System.out.printf("%3d ", el); // three-digit number
// System.out.printf("%4d ", el); // four-digit number
}
System.out.println();
}
}
See also:
• Pascal's triangle 2d array - formatting printed output
• Print Pascal's Triangle
class pascal {
static void main(int n) {
int a[][] = new int[n][n + 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = 0;
}
}
a[0][1] = 1;
int k = 5;
int p = 0;
for (int i = 1; i < n; i++) {
for (int j = 1; j < n + 1; j++) {
a[i][j] = a[i - 1][j] + a[i - 1][j - 1];
}
}
for (int i = 0; i < a.length; i++) {
for (p = n + -i; p > 0; p--) {
System.out.print(" ");
}
for (int j = 0; j < a[i].length; j++) {
if (a[i][j] != 0) {
System.out.print(a[i][j] + " ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}

Categories