I happened to appear for a test and got the following as question. I am unable to figure out how to proceed. The scenario is to write a java program that prints the following with respective N. If suppose N=3, it must have 2*N rows and output must be,
1
2*3
4*5*6
4*5*6
2*3
1
Output must consist only numbers and asterisk. N varies between 0 to 100. Also, given
public static void main(String[] args){
int rows=2;
mirrorTriangle(rows);
}
public void mirrorTriangle(int n){
//Logic
}
I don't understand why is that rows declared as 2 if rows are supposed to be varying with N. Please explain the logic.
Please find the solution to your problem, with explanation comments.
public static void main(String[] args) throws Exception
{
// initialize n
int n = 4;
// initialize x to 1 from where our printing will start.
int x = 1;
/* We will store our generated numbers in an array.
* For example, the array after we generate
* the numbers would look like:
* [1,0,0,
2,3,0,
4,5,6,
4,5,6,
2,3,0,
1,0,0]
*
* When n = 3, there are going to be 3*2 i.e, n*2 rows.
* in our case 6 rows.
* visualize with the above values.
* The first n/2 rows will be the numbers we print,
* the next n/2 will be the mirror image of the first n/2 rows.
* no. of columns in each row will be equal to n, in our example:3
*/
int arr[][] = new int[n*2][n];
/*
* Start populating the matrix
* Each row will contain number of elements eaual to the row number,
* so 1st row -> 1 element, 2nd - > 2,.. and so on.
*/
for(int row=0;row<n;row++)
{
int col = 0;
while(col < row+1)
{
arr[row][col] = arr[n*2-row-1][col] = x++;
col++;
}
}
/*
* Now our task is just to read out the array.
* The tricky part is adding the astricks.
* We notice that row1 will have 1-1 asticks, row2 -> 2-1 astricks ,.. and so on.
* So in between the numbers while reading out,
* for each row we maintain the number of astricks.
*/
for(int i=0;i<arr.length;i++)
{
StringBuilder build = new StringBuilder();
for(int j=0;j<arr[i].length;j++)
{
if(arr[i][j] > 0)
{
build.append((arr[i][j])).append("*");
}
}
System.out.print(build.delete(build.length()-1,build.length()).toString());
System.out.println();
}
}
o:p for n=4:
1
2*3
4*5*6
7*8*9*10
7*8*9*10
4*5*6
2*3
1
def N = 3
def i = 0
def j = 0
int[][] numbers = new int[N][]
// Generate, print, and store numbers
while( i < numbers.length ){
numbers[i] = new int[i+1]
j = 0
while( j < numbers[i].length ){
numbers[i][j] = j+1
++j
print j
}
println ""
i++
}
// Print them again, in reverse order
i = numbers.length - 1
while( i >= 0 ){
j = 0
while( j < numbers[i].length ){
print numbers[i][j]
j++
}
println ""
i--
}
Output:
1
12
123
123
12
1
The code is pretty self-explanatory. You need just N rows but print 2N because, wait for it ... symmetry. If you have 6 rows, first 3 are new while the other 3 are just mirrored images so why waste the memory space when you can just print them again?
Is there an explicit requirement for recursion? It is implied by the structure of the problem not mentioned anywhere.
int rows=2 is an example probably, for the purposes of the problem you can't do anything 'smart' like using pointers ...
I will also assume that you are not permitted to use values '> 100' so that you can overload the meaning of the n value - same goes for 2's complement.
If you allow for looping, as a substitute for recursion you can generate the triangle without having to save state outside of the stack:
public static void main(String[] args){
int rows=3;
mirrorTriangle(rows);
}
public static void mirrorTriangle(int n){
for (int i = 0 ; i < n + 1 ; i++) {
renderLine(i);
}
for (int i = n ; i > 0 ; i--) {
renderLine(i);
}
}
private static void renderLine(int n) {
int j = n * (n - 1) / 2 + 1;
int k = j + n;
while (j < k) {
System.out.print(j);
j++;
if (j < k) System.out.print('*');
}
System.out.println();
}
Try this fresh code:
public class String4 {
public static void main(String[] args) {
int rows = 3;
mirrorTriangle(rows);
}
private static void mirrorTriangle(int rows) {
for(int i=1;i<=rows;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(i);
if(j>0&&j<i)
System.out.print("*");
}
System.out.println();
}
for(int k=rows;k>0;k--)
{
for(int l=1;l<=k;l++)
{
System.out.print(k);
if(l>0&&l<k)
System.out.print("*");
}
System.out.println();
}
}
}
Output:
1
2*2
3*3*3
3*3*3
2*2
1
I think this is a better and simple solution than the chosen one.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter limit");
int limit = s.nextInt();
int start[] = new int[limit];
int v = 1;
for (int i=1; i<=limit; i++) {
start[i-1] = v;
for (int j=1; j<=i; j++) {
System.out.print(v++);
if(j==i)
continue;
System.out.print("*");
}
System.out.print("\n");
}
for (int i=limit-1; i>=0; i--) {
v=start[i];
for (int j=i; j>=0; j--) {
System.out.print(v++);
if(j==0)
continue;
System.out.print("*");
}
System.out.print("\n");
}
}
Related
I have a problem with an exercise trying to solve it. Here is the task:
Write a program that moves that rotates a list several times (the first element becomes last).
list = 1,2,3,4,5 and N = 2 -> result = 3,4,5,1,2
Note that N could be larger than the length of the list, in which case you will rotate the list several times.
list = 1,2,3,4,5 and N = 6 -> result = 2,3,4,5,1
Input
On the first line you will receive the list of numbers.
On the second line you will receive N
Output
On the only line of output, print the numbers separated by a space.
Here are the TEST:
TEST 1:
Input 5,3,2,1 2
Output 2,1,5,3
TEST 2:
Input 2,1,3,4 5
Output 1,3,4,2
Here is my code so far:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String[] elements = input.split(",");
int[] array = new int[elements.length];
for (int i = 0; i < elements.length; i++) {
array[i] = Integer.parseInt(elements[i]);
}
int a = scanner.nextInt();
int[] rotated = new int[elements.length];
for (int x = 0; x <= array.length - 1; x++) {
rotated[(x + a) % array.length] = array[x];
}
for (int i = 0; i < rotated.length; i++) {
if (i > 0) {
System.out.print(",");
}
System.out.print(rotated[i]);
}
}
}
The first TEST is passed. But the second test is not passed and my program gives me wrong output: 4,2,1,3 instead of the right one: 1,3,4,2.
I cant figure it out where is the problem.
Thank you in advance for any help.
Your logic can be simplified to :
public static void shiftLeft(int shiftBy, int arr[]) {
for (int j = 0; j < shiftBy; j++) {
int a = arr[0]; // storing the first index
int i;
for (i = 0; i < arr.length - 1; i++) { // shifting the array left
arr[i] = arr[i + 1];
}
arr[i] = a; // placing first index at the end
}
}
Now call it :
public static void main(String[] args) {
// Fetch all data from user as you have done
int arr[] = { 1, 2, 3, 4, 5 };
shiftLeft(n % arr.length, arr);
// print out the array
}
Notice that if the number n is greater than the length of the array, you don't have to actually shift it that many times. Instead you just need to shift it n % arr.length times.
package javaapplication1;
/**
*
* #author
*/
public class JavaApplication1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int[] scores = {1,2,3,4,5,6};
int[] fin = extractAllEvens(scores);
for(int i =0; i<fin.length; i++) {
System.out.println(fin[i]);
}
}
public static int[] extractAllEvens(int[]scores) {
int evenCount = 0;
for (int i =0; i<scores.length; i++) {
if (scores[i] % 2 ==0) {
evenCount++;
}
}
int[] newScores = new int[evenCount];
int j = 0;
for(int i = 0; i<scores.length; i++) {
if(scores[1] % 2 ==0) {
newScores[1] = scores[i];
j++;
}
}
return newScores;
}
}
I'm trying to output 2, 4, 6.
But I keep getting results such as 0,6,0.
I think I messed up somewhere with the variables with i or j or the number 1 and possibly their locations... can anyone help lead me in the right direction?
scores[1] % 2 == 0 and newScores[1] = scores[i]?
You have hard-coded to use only index 1 (the second element) of newArray.
You probably should be using j as the index instead of 1.
Your last loop uses 1 as fixed loop index.
Change that to i instead.
Change the second for loop like this -
for (int i = 0; i < scores.length; i++) {
if (scores[i] % 2 == 0) {
newScores[j] = scores[i];
j++;
}
}
Cheers!
instead of
if(scores[1] % 2 ==0) {
newScores[1] = scores[i];
It should be
if(scores[i] % 2 ==0) {//← i here
newScores[j] = scores[i];//← j here
O/P : 2 4 6
It sounds a lot easier than it looks. Basically I have my code finished this is my output where the leading number is whatever integer the program receives as input. In this case n = 5:
1
21
321
4321
54321
but this is what it is suppose to look like:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
How should I go about adding spaces in between my numbers while maintaining this pattern? I've tried editing here and there but it keeps coming out like this:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
My code:
import java.util.Scanner;
public class DisplayPattern {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
displayPattern(n);
}
public static void displayPattern(int n) {
final int MAX_ROWS = n;
for (int row = 1; row <= MAX_ROWS; row++) {
for (int space = (n - 1); space >= row; space--) {
System.out.print(" ");
}
for (int number = row; number >= 1; number--) {
System.out.print(number + " "); /*<--- Here is the edit.*/
}
System.out.println();
}
}
Edit:
#weston asked me to display what my code looks like with the second attempt. It wasn't a large change really. All i did was add a space after the print statement of the number. I'll edit the code above to reflect this. Since it seems that might be closer to my result I'll start from there and continue racking my brain about it.
I managed to get the program working, however this only caters to single digit number (i.e. up to 9).
import java.util.Scanner;
public class Play
{
public static class DisplayPattern
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
displayPattern(n);
}
public static void displayPattern(int n)
{
final int MAX_ROWS = n;
final int MAX_COLUMNS = n + (n-1);
String output = "";
for (int row = 1; row <= MAX_ROWS; row++)
{
// Reset string for next row printing
output = "";
for (int space = MAX_COLUMNS; space > (row+1); space--) {
output = output + " ";
}
for (int number = row; number >= 1; number--) {
output = output + " " + number;
}
// Prints up to n (ignore trailing spaces)
output = output.substring(output.length() - MAX_COLUMNS);
System.out.println(output);
}
}
}
}
Works for all n.
In ith row print (n-1 - i) * length(n) spaces, then print i+1 numbers, so it ends with 1 separated with length(n) spaces.
public static void printPiramide(int n) {
int N = String.valueOf(n).length();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1 - i; j++) {
for (int k = 0; k < N; k++)
System.out.print(" ");
}
for (int j = i+1; j > 0; j--) {
int M = String.valueOf(j).length();
for (int k = 0; k < (N - M)/2; k++) {
System.out.print(" ");
}
System.out.print(j);
for (int k = (N - M)/2; k < N +1; k++) {
System.out.print(" ");
}
}
System.out.println();
}
}
public class DisplayPattern{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
List<Integer> indentList = new ArrayList<Integer>();
int maxLength= totalSpace(n) + (n-1);
for(int i = 1; i <= n; i++ ){
int eachDigitSize = totalSpace(i);
int indent = maxLength - (eachDigitSize+i-1);
indentList.add(indent);
}
for(int row = 1; row<=n; row++){
int indentation = indentList.get(row-1);
for(int space=indentation; space>=0; space--){
System.out.print(" ");
}
for(int number = row; number > 0; number--){
System.out.print(number + " ");
}
System.out.println();
}
}
private static int totalSpace(int n) {
int MAX_ROWS = n;
int count = 0;
for(int i = MAX_ROWS; i >= 1; i--){
int currNum = i;
int digit;
while(currNum > 0){
digit=currNum % 10;
if(digit>=0){
count++;
currNum = currNum/10;
}
}
}
return count;
}
}
It works properly for any number of rows(n).
java-8 solution to the problem:
IntStream.rangeClosed(1, MAX)
.forEach(i -> IntStream.range(0, MAX)
.map(j -> MAX - j)
.mapToObj(k -> k == 1 ? k + "\n" : k <= i ? k + " " : " ")
.forEach(System.out::print)
);
Output for MAX = 5:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
For the bottom row, you have the right number of spaces. But for the next row from the bottom, you're missing one space on the left (the 4 is out of line by 1 space). In the next row up, you're missing two spaces on the left (the 3 is out of line by 2 spaces)... and so on.
You're adding a number of spaces to the beginning of each line, but you're only taking into account the number of digits you're printing. However, you also need to take into account the number of spaces you're printing in the previous lines.
Once you get that part working, you might also consider what happens when you start to reach double-digit numbers and how that impacts the number of spaces. What you really want to do is pad the strings on the left so that they are all the same length as the longest line. You might check out the String.format() method to do this.
I start learning programming about 4 days ago by myself and iam a lil bit stuck with 2d arrays. I try to challenging myself with tasks, like get from 2d array column with most zeros or atleast just count zeros, so far i get this far
public class b {
public static void main(String[] args) {
int a[][] = new int [5][5];
int i,j;
int s = 0;
for(i= 0;i<a.length; i++)
for(j = 0; j<a[i].length; j++){
a[i][j] = (int)(Math.random()*10);
}
for(i=0;i<a.length;i++){
for(j=0;j<a[i].length;j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
for(j=0;j<a[0].length;j++) {
for(i=0;i<a.length;i++) {
if(a[i][j] >-1 || a[i][j]<1) {
s++;
System.out.println(s +"\t");
s = 0;
}
}
}
}
}
Can somebody explain me why result is always 1 and why it counts columns and rows in one row?
Suppose the condition enters into if(a[i][j] >-1 || a[i][j]<1) then you increase s by 1 then print it which gives 1 then you reassign it to s=0 so it gives same 1 each time.So remove the s=0 and place the printing line after end of loop
public class b {
public static void main(String[] args) {
int a[][] = new int [5][5];
int i,j;
int s = 0;
for(i= 0;i<a.length; i++)
for(j = 0; j<a[i].length; j++){
a[i][j] = (int)(Math.random()*10);
}
for(i=0;i<a.length;i++){
for(j=0;j<a[i].length;j++)
System.out.print(a[i][j] + "\t");
System.out.println();
}
for(j=0;j<a[0].length;j++){
for(i=0;i<a.length;i++)
if(a[i][j] >-1 && a[i][j]<1){
s++;
}
System.out.println("Zero in column no. "+j+" is "+s +"\t");
s=0;
}
}
}
Demo
Result will be 1 because you're re-assigning 0 to s everytime. But the issue is not only that.
Firstly your condition is using wrong indices. Instead of a[i][j] you should use a[j][i] as you're traversing column-wise. Secondly:
if(a[j][i] >-1 || a[j][i]<1){
can be simply written as:
if(a[j][i] == 0) {
So the structure is the outer for loop will iterate over each column number. And for each column number, inner for loop will find count of 0. You've to maintain a max variable outside both the loops, to track the current max. Also, you've to use another variable inside the outer for loop to store the count for current column.
Everytime the inner for loop ends, check if current column count is greater than max. If yes, reset max.
int max = 0;
for(j=0;j<a[0].length;j++){
int currentColumnCount = 0;
for(i=0;i<a.length;i++) {
if(a[j][i] == 0) {
currentColumnCount++;
}
}
if (currentColumnCount > max) {
max = currentColumnCount;
}
}
This is a homework question so I would like help, not an answer.
I'm trying to create 2 triangles out of numbers based on a number entered by the user.
"Enter a number between 2-9: "3"
1
12
123
1
21
321
IE2:
"Enter a number between 2-9: "5"
1
12
123
1234
12345
1
21
321
4321
54321
I have been able to get the first triangle complete. But when I add my nested loop it messes up my first triangle with the numbers developed from the nested loop. It also puts all the numbers in a straight vertical line. I've tried variations for different nest loops and even tried messing with a StringBuilder, but was still unsuccessful.
Here's what I have in code so far:
import java.util.Scanner;
public class NestedLoops
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a Number between 2-9: ");
int width = input.nextInt();
String r = "";
for (int i = 1; i <= width; i++)
{
r = r + i;
System.out.println(r);
}
}
}
Again, I'm looking for help/understanding and not just an answer.
There are two aspects the 2nd part of the question.
You need to generate strings with the numbers in the reverse order:
You could do this by adding the numbers at the other end.
You could do this by reversing the strings.
You need to arrange that there are spaces to the left.
You could do this by adding the required number of spaces to the left end of the string.
You could do this by using the System.out.format(...) with a template that right aligns the string in a field with the required number of characters. (OK, that's a bit too obscure ...)
Or, you can build the string in a character array or string builder rather than using string concatenation.
The "trick" is to figure out what strategy you are going to use ... before you start cutting code.
try
int width = 5;
// for all lines; number of lines = width
for (int line = 1; line <= width; line++) {
// print numbers from 1 to current line number
for (int n = 1; n <= line; n++) {
System.out.print(n);
}
// end of line
System.out.println();
}
// add empty line between triangles
System.out.println();
// for all lines; number of lines = width
for (int line = 1; line <= width; line++) {
// printing padding spaces, number of spaces = with - line number
int nSpaces = width - line;
for (int i = 0; i < nSpaces; i++) {
System.out.print(" ");
}
// print numbers from number of current line to 1
for (int n = line; n >= 1; n--) {
System.out.print(n);
}
// end of line
System.out.println();
}
Can you just add another loop after your first loop like
String r = "";
String space = "";
for (int i = width; i >= 1; i--)
{
r = r + i;
System.out.println(r);
}
Try it. not yet tested
You need to use a queue.
eg. http://docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html
Enque the numbers till you reach the max, and then start dequing them.
And while you dequeue, you need to apply the reverse
Queue<String> q = new LinkedList<String>();
for (int i = 1; i <= width; i++)
{
r = r + i;
q.add(r);
System.out.println(r);
}
while(!q.isEmpty()){
String j = q.remove();
//reverse j
System.out.println(reverse(j));
}
I leave the reversing part for you to do :)
public static void main(String[] args)
{
int n = 5;
for(int i=1; i<=n; i++)
{
for (int j=(n*2), k=n; j>1; j--)
{
if (k <= i)
{
System.out.print(k);
}
else
{
System.out.print('*');
}
k += (j)-1 > n ? -1 : 1;
}
System.out.println();
}
}
Just tried to implement in scala. Ignore if you don't like it..:-)
class Triangle extends App
{
val width = Console.readInt()
if (width < 2 || width > 9)
{
throw new RuntimeException()
}
var i, j = 1;
for (i <- 1 to width)
{
for (j <- 1 to i)
{
print(j)
}
print("\n")
}
for (i <- 1 to width)
{
for (dummy <- 1 to width-i)
{
print(" ")
}
for (j <- i to 1 by -1)
{
print(j)
}
print("\n")
}
}