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 days ago.
Improve this question
I'm following this code and not understanding my log statements:
public void merge(int[] nums1, int m, int[] nums2, int n) {
int i=0;
int j=0;
int k = 0;
while (i < m || j < n) {
if (i >= m) {
// insert element at j
nums1[k] = nums2[j];
j++;
} else if (j >= n) {
nums1[k] = nums1[i];
i++;
}
else if (nums1[i] <= nums2[j]) {
System.out.println("Inserting " + firstNum + " into nums[" + k + "]");
nums1[k] = nums1[j];
i++;
} else {
System.out.println("Inserting " + secondNum + " into nums[" + k + "]");
nums1[k] = nums2[j];
j++;
}
k++;
for (int count=0; count < nums1.length; count++) {
System.out.print(nums1[count] + " ");
}
System.out.println();
}
}
Prints
firstNum is 1 and secondNum is 2
Inserting 1 into nums[0]
1 2 3 0 0 0
firstNum is 2 and secondNum is 2
Inserting 2 into nums[1]
1 1 3 0 0 0
firstNum is 3 and secondNum is 2
Inserting 2 into nums[2]
1 1 2 0 0 0
firstNum is 2 and secondNum is 5
Inserting 2 into nums[3]
1 1 2 1 0 0
firstNum is 1 and secondNum is 5
1 1 2 1 5 0
firstNum is 1 and secondNum is 6
1 1 2 1 5 6
Printing the array 2 is not inserted into index 1. Comparisons should be
1 and 2
2 and 2
3 and 2
3 and 5 NOT 2 and 5
I'm not able to see the issue so far. Thanks.
Related
I am writing some code that creates a incrementing number right angle triangle that looks something like this:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
I am unsure on how to make my code output a triangle to that shape as my code outputs the same thing except inverted.
This is the code I have:
public class Main {
public static void main(String[] args) {
int rows = 6;
for (int i = 1; i <= rows; ++i) {
for (int j = 1; j <= i; ++j) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
My speculation is that instead of incrementing some of the values I would decrement them however the code would run infinite garbage values and not what I wanted.
It is needed to print some spaces before printing the numbers in each row, and the number of spaces should be decreasing depending on the row:
int rows = 6;
for (int i = 1; i <= rows; ++i) {
for (int j = rows - i; j >= 1; j--) {
System.out.print(" ");
}
for (int j = 1; j <= i; ++j) {
System.out.print(j + " ");
}
System.out.println();
}
This prefix may be build using String::join + Collections::nCopies:
System.out.print(String.join("", Collections.nCopies(rows - i, " ")));
Or since Java 11, this prefix may be replaced using String::repeat:
System.out.print(" ".repeat(rows - i));
Instead of two nested for loops, you can use a single while loop with two incrementing variables. The number of iterations stays the same.
int n = 7, i = 0, j = 0;
while (i < n) {
// element
if (i + j >= n - 1) {
// print an element
System.out.print(i + j + 2 - n);
} else {
// print a whitespace
System.out.print(" ");
}
// suffix
if (j < n - 1) {
// print a delimiter
System.out.print(" ");
j++;
} else {
// print a new line
System.out.println();
j = 0;
i++;
}
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
See also: Optimized Bubble Sort
Your approach is almost correct - use two nested for loops, all that remains is to add one if else statement and calculate the sum of coordinates i and j.
Try it online!
public static void main(String[] args) {
int n = 6;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print(" ");
int sum = i + j;
if (sum > n)
System.out.print(sum - n);
else
System.out.print(" ");
}
System.out.println();
}
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
See also: Printing a squares triangle. How to mirror numbers?
You can print an inverted triangle using two nested for-loops as follows:
// the number of rows and the
// number of elements in each row
int n = 6;
// iterating over rows with elements
for (int i = 0; i < n; i++) {
// iterating over elements in a row
for (int j = 0; j < n; j++) {
// element
if (i + j >= n - 1) {
// print an element
System.out.print(i + j + 2 - n);
} else {
// print a whitespace
System.out.print(" ");
}
// suffix
if (j < n - 1) {
// print a delimiter
System.out.print(" ");
} else {
// print a new line
System.out.println();
}
}
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
See also: How to draw a staircase with Java?
You have to print spaces before printing the numbers to make the triangle look inverted, the number of spaces depends on the amount of numbers you skip which are rows-i, so you can loop from i to rows and print space in each iteration.
int rows = 6;
for (int i = 1; i <= rows; ++i) {
for (int j = i; j < rows; j++) {
System.out.print(" ");
}
for (int j = 1; j <= i; ++j) {
System.out.print(j + " ");
}
System.out.println();
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
You can use the property that for the row containing i as the greatest number of the row the number of the spaces can be calculated as 2*(rows-i). You can rewrite your program like below:
public class Main {
public static void main(String[] args) {
int rows = 6;
for (int i = 1; i <= rows; ++i) {
for (int nspaces = 0; nspaces < 2 * (rows - i); ++nspaces) {
System.out.print(" ");
}
for (int j = i; j > 0; --j) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
I need to know how to print out the following pattern:
5
4 5
3 4 5
2 3 4 5
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
Any and all help is appreciated.
What i have so far is this:
for (int i = 1; i <= num; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(j+" ");
}
System.out.println();
}
for (int i = num-1; i >= 1; i--)
{
for (int j = 1; j <= i; j++)
{
System.out.print(j+" ");
}
System.out.println();
}
and it outputs this:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
So I have the structure of the pattern itself understood, but it seems that I need to reverse the flow somehow. This is what I do not understand.
Change the loop conditions as shown below:
public class Main {
public static void main(String[] args) {
int num = 5;
for (int i = num; i >= 1; i--) {// Start with num and go downwards up to 1
for (int j = i; j <= num; j++) {// Start with i and go upwards up to num
System.out.print(j + " ");
}
System.out.println();
}
for (int i = 2; i <= num; i++) {// Start with 2 and go downwards up to num
for (int j = i; j <= num; j++) {// Start with i and go downwards up to num
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output:
5
4 5
3 4 5
2 3 4 5
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
Accepted answer not output the corrent pattern so... this code works.
Ther are two loops, each one iterate line by line. First from 5 to 1, the second one from 2 to 5.
In every iteration (every line) will print next to the first number the following numbers.
int num = 5;
for(int i = num ; i > 0 ; i--){
System.out.print(i+" "); //Print the first number of the line
for(int j = 1; j <= num-i; j++){
//Print as extra number as line need (first line = 0 extra numbers,
//second line = 1 extra number...)
System.out.print((i+j)+" ");
}
System.out.println(); //New line
}
for (int i = 2; i <= num; i++) { //Print second part starting by 2
for (int j = i; j <= num; j++) { //Print extra numbers
System.out.print(j+" ");
}
System.out.println(); //New line
}
And the output is as expected:
5
4 5
3 4 5
2 3 4 5
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
I did this below but I didn't get it right,
int i = 1;
while(i <= 6){
for(int j = 1;j <= 6-i;j++){
System.out.print(" ");
}
for(int m = 1; m <= i; m++){
System.out.print(m + " ");
}
i++;
System.out.println();
}
I got this instead :
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
But I need guide on how to get this below,
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
while(i <= 6){
for(int j = 1; j <= 6 - i; j++){
System.out.print(" ");
}
for(int m = i-1; m > 1; m--){
System.out.print(m + " ");
}
for(int m = 1; m < i; m++){
System.out.print(m + " ");
}
i++;
System.out.println();
}
This should work for you, i just added / edited this part:
for(int m = i-1; m > 1; m--){
System.out.print(m + " ");
}
for(int m = 1; m < i; m++){
System.out.print(m + " ");
}
To let it count down again, and let it count up afterwards
This should do the trick, but it's important to understand what is going on:
public class Main {
public static void main(String[] args) {
for (int i = 0; i <= 6; i++) {
printRow(6, i);
}
}
public static void printRow(int highestValue, int rowValue) {
for (int i = 0; i < (highestValue - rowValue); i++) {
System.out.print(" ");
}
for (int i = rowValue; i >= 1; i--) {
System.out.print(i + " ");
}
for (int i = 2; i <= rowValue; i++) {
System.out.print(i + " ");
}
System.out.println();
}
}
The first loop pads the left side of the pyramid, as you have already done. The second loop counts down from the value of the row to 1, which is the center of the pyramid. The third loop counts back up from 2 to the value of the row. Note that for the first row, 2 will not be printed, because i = 2 is greater than rowValue, which is 1, so the loop is skipped.
Running this results in the following:
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
Note that a row starting with 6 is printed since I used the bounds you provided. If this is not what should be done (from your example output), I will leave that up to you on how to fix this. Pay attention to the name of the arguments in the printRow method to see why there is an extra row printed.
There you have my solution, little smarty solution with using absolute value, with notes why is what where
public static void printPyramid(int rows) {
// row counter
for (int i = 1; i <= rows; i++) {
// padding- size = rows - i
for (int j = 1; j <= rows - i; j++) {
// 2 spaces - char + space
System.out.print(" ");
}
// print numbers
for (int j = -i; j <= i; j++) {
// we want only once 1, and skip print zero
if (j == 0 || j == 1) {
continue;
}
// print absolute value
System.out.print(Math.abs(j) + " ");
}
// new row- println same as print("\n");
System.out.println();
}
}
With 6 rows, output is
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
Let's break this down into parts. First we need to figure out how to output a single level of the pyramid. Let's start without padding. For the first level it's just "1", for every other level it's the level above it surrounded by the "number" of that level (and the spaces).
private static String buildLevel(int num) {
if (num == 1) return "1";
return Integer.toString(num) + " " + buildLevel(num -1) + " " + Integer.toString(num);
}
We then need to be able to add the padding, so let's create a method that pads to a certain length.
private static String pad(String stringToPad, int padTo) {
return String.join("", Collections.nCopies(padTo - stringToPad.length(), " ")) + stringToPad;
}
Putting this together we can create a method to build a pyramid by looping over the needed levels and concatenating the levels together.
private static String buildPyramid(int height) {
int expectedLength = height * 2 + 1;
String out = "";
for (int i = 1; i <= height; i++) {
out += pad(buildLevel(i), expectedLength) + "\n";
expectedLength += 2;
}
return out;
}
The length of the first line is the height * 2 + 1, derived by counting. (This includes two spaces at the beginning of each line, which is in your examples). Each subsequent line should be 2 longer than the one above it.
Call it like this to produce your example
public static void main(String[] args) {
System.out.println(buildPyramid(5));
}
Outputs:
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
For completeness, here is all the code in one block.
private static String buildLevel(int num) {
if (num == 1) return "1";
return Integer.toString(num) + " " + buildLevel(num -1) + " " + Integer.toString(num);
}
private static String pad(String stringToPad, int padTo) {
return String.join("", Collections.nCopies(padTo - stringToPad.length(), " ")) + stringToPad;
}
private static String buildPyramid(int height) {
int expectedLength = height * 2 + 1;
String out = "";
for (int i = 1; i <= height; i++) {
out += pad(buildLevel(i), expectedLength) + "\n";
expectedLength += 2;
}
return out;
}
public static void main(String[] args) {
System.out.println(buildPyramid(6));
}
I'm supposed to have four patterns in a single program but the program won't output anything past my 2nd for statement. Can someone take a look at this please? Line RIGHT after Pattern C is where it stops outputting.
import java.util.Scanner;
public class Patterns
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a positive maximum integer value: ");
int max = input.nextInt();
//1st Pattern
System.out.println("\nPattern A: ");
for (int i = 1; i <= max; i++){
for (int j = 1; j <= i; j++){
System.out.print(j + " ");
}
System.out.println();
}
//2nd Pattern
System.out.println("\nPattern B:");
for (int i = -5; i <= max; i++, max--){
for (int j = 1; j <= max; j++){
System.out.print(j + " ");
}
System.out.println();
}
// 3rd pattern and WHERE PROBLEM STARTS!!
System.out.println("\nPattern C:");
for (int i = 0; i < max; i++){
for (int j = i; j < 0; j++){
System.out.print(j + " ");
}
System.out.println();
}
}
}
Are my loops nested improperly?
My program asks the user for a max integer and makes a program based on that
here are some sample outputs
Enter a positive maximum integer value: 6
Pattern A:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
Pattern B:
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Pattern C:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
Pattern D:
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
for (int i = 0; i < max; i++){
for (int j = i; j < 0; j++){
i and j both start off at 0. 0 can never be less than 0, so your j loop will never execute.
The other issue is that you're reusing the max variable after Pattern B has altered the value of it. You should copy the value of max into a variable that you can modify within the pattern without affecting the original.
For Pattern C, the loop is not executing because of your conditional and the fact that you've altered max.
Swap B and C with this.
//2nd Pattern
System.out.println("\nPattern B:");
int patternBMax = max;
for (int i = -5; i <= patternBMax; i++, patternBMax--)
{
for (int j = 1; j <= patternBMax; j++)
{
System.out.print(j + " ");
}
System.out.println();
}
// 3rd pattern and WHERE PROBLEM STARTS!!
System.out.println("\nPattern C:");
int patternCMax = max;
for (int i = 1; i <= patternCMax; i++)
{
// Pad the output with the necessary whitespace
for (int j = 0; j < patternCMax - i; j++)
{
System.out.print(" ");
}
for (int k = i; k > 0; k--)
{
System.out.print(k + " ");
}
System.out.println();
}
and you should get this
Pattern B:
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Pattern C:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
import java.util.Scanner;
public class Ex7_3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("This program that reads the integers between 1 and 100 and counts the occurrences of each");
int [] counts = new int [101];
System.out.println("Enter the integers between 1 and 100:");
int next = input.nextInt();
while (next != 0){
if(next >= 1 && next<= 100)
counts [next]++;
next = input.nextInt();
for(int i =0; i< counts.length;i++)
for(int j = 0; j <= 100; j++)
if(counts[next] > 1){
System.out.println(next + "occurs" + j + "times");
}
}
}
}
The solution should be like this?
Enter the integers between 1 and 100: 2 5 6 5 4 3 23 43 2 0
2 occurs 2 times
3 occurs 1 time
4 occurs 1 time
5 occurs 2 times
6 occurs 1 time
23 occurs 1 time
43 occurs 1 time
Your loop at the end doesn't make much sense to me. You probably want something like this
Scanner input = new Scanner(System.in);
System.out.println("This program that reads the integers between 1 and 100 and counts the occurrences of each");
int [] counts = new int [101];
System.out.println("Enter the integers between 1 and 100:");
int next = input.nextInt();
while (next != 0){
if(next >= 1 && next<= 100)
counts [next]++;
next = input.nextInt();
}
// Here's the change
for (int i = 0; i < counts.length; i++) {
if (counts[i] > 0) {
System.out.println(i + " occurs " + counts[i] + " times.");
}
}