So I have a simple program that creates a LinkedList array of given size n, with each value in the list representing a new separate LinkedList data Structure.
public class Graph {
public final LinkedList[] graph;
public Graph(int n){
graph = new LinkedList[n];
for (int i=0; i<n; i++){
graph[i] = new LinkedList();
}
}
public void addEdge(int x, int y){
graph[x].addFirst(y);
graph[y].addFirst(x);
}
For some reason, however, when I call the addEdge() method with two int values, instead of adding them to the specific called LinkedList in graph[], it adds them to every LinkedList in graph[].
What is the problem here?
Edit:*
public void addEdge(int x, int y){
graph[x].addFirst(y);
graph[y].addFirst(x);
for (int i=0; i<graph.length; i++){
Node tmp = graph[i].first;
System.out.println(i + ":");
while (tmp != null){
System.out.print(tmp.name + " ");
tmp = tmp.Rnext;
}
System.out.println();
}
System.out.println();
}
public class Test {
public static void main(String[] args) {
Graph myGraph1 = new Graph(8);
myGraph1.addEdge(1, 2);
myGraph1.addEdge(1, 7);
myGraph1.addEdge(1, 4);
myGraph1.addEdge(2, 5);
myGraph1.addEdge(2, 6);
myGraph1.addEdge(6, 3);
myGraph1.addEdge(3, 8);
myGraph1.addEdge(5, 7);
}
}
Here is the output of graph:
0:
1 2
1:
1 2
2:
1 2
3:
1 2
4:
1 2
5:
1 2
6:
1 2
7:
1 2
0:
1 7 1 2
1:
1 7 1 2
2:
1 7 1 2
3:
1 7 1 2
4:
1 7 1 2
5:
1 7 1 2
6:
1 7 1 2
7:
1 7 1 2
0:
1 4 1 7 1 2
1:
1 4 1 7 1 2
2:
1 4 1 7 1 2
3:
1 4 1 7 1 2
4:
1 4 1 7 1 2
5:
1 4 1 7 1 2
6:
1 4 1 7 1 2
7:
1 4 1 7 1 2
0:
2 5 1 4 1 7 1 2
1:
2 5 1 4 1 7 1 2
2:
2 5 1 4 1 7 1 2
3:
2 5 1 4 1 7 1 2
4:
2 5 1 4 1 7 1 2
5:
2 5 1 4 1 7 1 2
6:
2 5 1 4 1 7 1 2
7:
2 5 1 4 1 7 1 2
0:
2 6 2 5 1 4 1 7 1 2
1:
2 6 2 5 1 4 1 7 1 2
2:
2 6 2 5 1 4 1 7 1 2
3:
2 6 2 5 1 4 1 7 1 2
4:
2 6 2 5 1 4 1 7 1 2
5:
2 6 2 5 1 4 1 7 1 2
6:
2 6 2 5 1 4 1 7 1 2
7:
2 6 2 5 1 4 1 7 1 2
0:
6 3 2 6 2 5 1 4 1 7 1 2
1:
6 3 2 6 2 5 1 4 1 7 1 2
2:
6 3 2 6 2 5 1 4 1 7 1 2
3:
6 3 2 6 2 5 1 4 1 7 1 2
4:
6 3 2 6 2 5 1 4 1 7 1 2
5:
6 3 2 6 2 5 1 4 1 7 1 2
6:
6 3 2 6 2 5 1 4 1 7 1 2
7:
6 3 2 6 2 5 1 4 1 7 1 2
Here is the LinkedList and Node Class I am using:
import java.util.NoSuchElementException;
public class LinkedList {
public static Node first;
public LinkedList(){
first = null;
}
// Returns true if the list is empty
public boolean isEmpty(){
return first == null;
}
// Inserts a new node at the beginning of this list.
public void addFirst(int name){
first = new Node(name, first);
}
public boolean findData(int d){
if(first == null) throw new NoSuchElementException();
Node tmp = first;
while (tmp != null) {
if (tmp.name == d) return true;
tmp = tmp.Rnext;
} return false;
}
}
public class Node {
public int name;
public Node Rnext;
public Node(){
name = 0;
Rnext = null;
}
public Node(int n, Node r){
this.name = n;
this.Rnext = r;
}
}
public static Node first;
This is the problem. Every single LinkedList you make is sharing the same Node, so they're all effectively the same list.
Don't use static for instance variables.
Related
I am trying to print out a Right Triangle that looks like this:
1
2 1
3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1
The size of the triangle increases if the number in the method gets larger, which in this case is 11.
My code seems to only work up to 10 as after 10, my spacing is messed up.
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1
12 11 10 9 8 7 6 5 4 3 2 1
13 12 11 10 9 8 7 6 5 4 3 2 1
I am trying to make it so that up to 99, the spacing is correct. What kind of edits should I do to my if statements or for loops in order to space it properly?
Code:
public class Patterns
{
public static void main(String[] args)
{
displayPattern(13);
//displayPattern(11,",");
}
public static void displayPattern(int n)
{
//print out n-1 spaces and the first number
//print n-2 spaces and the 2nd then first number
int counter = n;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= counter; j++)
{
if (n > 10)
{
if (i == n)
{
System.out.print("");
}
else if (i <= 10)
{
System.out.print(" ");
}
else
{
System.out.print(" ");
}
}
else if (n <=10)
{
if (i>9)
{
System.out.print(" ");
}
else
{
System.out.print(" ");
}
}
}
System.out.print(i + " ");
int tempValue = i - 1;
while(tempValue>0)
{
System.out.print(tempValue);
if(tempValue>1)
{
System.out.print(" ");
}
tempValue--;
}
if(tempValue==0)
{
System.out.print("\n");
}
counter--;
}
}
}
The following is the java code. I am trying to get the arrays from the problem1.txt and save it into the arraylist.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
class CSP {
public int nMeetings;
public static int nEmployees;
public int nTimeSlots;
public static int probNumber;
public ArrayList<ArrayList<Integer>> nMeetingsPerEmployee;
//public int[][] travelTime;
public CSP(int nMeetings, int nEmployees, int nTimeSlots, int probNumber) throws FileNotFoundException {
this.nMeetings = nMeetings;
this.nEmployees = nEmployees;
this.nTimeSlots = nTimeSlots;
this.probNumber = probNumber;
this.nMeetingsPerEmployee = getnMeetingsPerEmployeeArrayList();
}
//gets nMeetingsPerEmployee Arrylist
public static ArrayList<ArrayList<Integer>> getnMeetingsPerEmployeeArrayList() throws FileNotFoundException
{
ArrayList<ArrayList<Integer>> arraylist = new ArrayList<ArrayList<Integer>>();
File openFile = null;
if(probNumber == 1){
openFile = new File("problem1.txt");
}else if(probNumber == 2){
openFile = new File("problem2.txt");
}else if(probNumber ==3){
openFile = new File("problem3.txt");
}else
System.out.println("File Not Found");
Scanner in = new Scanner(openFile);
for(int i=0; i<5; i++)
in.nextLine(); //skip 5 lines until matrix
while(true){
for(int i=0; i<nEmployees; i++) //nEmployees = 33
{
for(int j=0; j<6 ;j++)
{
for(int k=0; k<3; k++)
in.next(); //skip 3 characters until individual number
arraylist.get(nEmployees).set(nEmployees, Integer.parseInt(in.next()));
if(in.hasNext() == false);
break;
}
}
return arraylist;
}
}
}
public class CSP_Main
{
public static void main(String[] args) throws FileNotFoundException
{
CSP problem1 = new CSP(20, 33, 12, 1);
//CSP problem2 = new CSP(20, 33, 12, 2);
//CSP problem3 = new CSP(40, 62, 12, 3);
}
}
The following is the error I keep getting.
Exception in thread "main" java.io.FileNotFoundException: problem1.txt
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at CSP.getnMeetingsPerEmployeeArrayList(CSP_Main.java:43)
at CSP.<init>(CSP_Main.java:22)
at CSP_Main.main(CSP_Main.java:70)
The following is the problem1.txt file that I am trying to read and save in the arraylist.
Number of meetings: 20
Number of employees: 33
Number of time slots: 12
Meetings each employee must attend:
1: 2 6 7 9 19
2: 2 5 6 12 16
3: 1 3 8 9 16
4: 1 6 15 16 18
5: 1 3 8 13 18
6: 8 10 11 17 20
7: 3 8 10 13 20
8: 1 3 14 16 20
9: 6 7 9 16 19
10: 2 6 7 12 17 19
11: 2 6 7 9 13
12: 2 4 7 12 16
13: 2 6 7 9 16 18
14: 2 5 11 17 18
15: 1 5 11 17 18 20
16: 6 8 12 16 18
17: 6 7 15 17 19
18: 1 7 11 18 20
19: 4 5 9 10 13
20: 4 7 9 17 18
21: 7 10 11 12 17
22: 5 6 9 13 18
23: 1 9 11 17 18
24: 2 11 14 15 17
25: 1 3 14 15 16
26: 5 6 10 13 15
27: 8 11 15 17 18
28: 1 4 7 9 16
29: 1 11 13 18 20
30: 2 5 12 13 18
31: 2 6 8 12 16
32: 2 7 15 17 19
33: 6 7 15 17 18
Travel time between meetings:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1: 0 1 1 1 2 1 1 1 1 1 1 2 1 2 1 1 1 1 2 1
2: 1 0 1 1 2 2 1 1 1 1 1 1 1 1 1 2 2 1 1 2
3: 1 1 0 1 1 2 2 1 1 2 2 2 2 2 2 1 2 2 1 1
4: 1 1 1 0 1 2 2 2 2 2 1 1 1 2 2 1 1 2 2 2
5: 2 2 1 1 0 2 2 2 1 1 1 2 1 2 1 2 2 1 2 2
6: 1 2 2 2 2 0 1 1 1 1 2 1 2 1 2 1 1 2 2 1
7: 1 1 2 2 2 1 0 1 2 1 1 1 1 1 2 2 2 1 1 2
8: 1 1 1 2 2 1 1 0 2 1 1 2 1 1 2 1 2 1 2 1
9: 1 1 1 2 1 1 2 2 0 2 2 1 1 1 2 2 2 2 1 2
10: 1 1 2 2 1 1 1 1 2 0 1 2 2 2 2 2 1 1 2 2
11: 1 1 2 1 1 2 1 1 2 1 0 1 2 1 1 2 1 2 1 1
12: 2 1 2 1 2 1 1 2 1 2 1 0 1 2 2 2 2 1 2 2
13: 1 1 2 1 1 2 1 1 1 2 2 1 0 1 1 2 2 2 1 1
14: 2 1 2 2 2 1 1 1 1 2 1 2 1 0 2 1 1 2 1 1
15: 1 1 2 2 1 2 2 2 2 2 1 2 1 2 0 2 1 2 2 1
16: 1 2 1 1 2 1 2 1 2 2 2 2 2 1 2 0 1 1 2 2
17: 1 2 2 1 2 1 2 2 2 1 1 2 2 1 1 1 0 2 2 2
18: 1 1 2 2 1 2 1 1 2 1 2 1 2 2 2 1 2 0 1 1
19: 2 1 1 2 2 2 1 2 1 2 1 2 1 1 2 2 2 1 0 2
20: 1 2 1 2 2 1 2 1 2 2 1 2 1 1 1 2 2 1 2 0
The problem1.txt file that I am trying to open is surely in the directory where my java codes are. So I don't know why I keep getting this error.
Thank you for your time.
ProjectRoot is working directory for Eclipse.
Move file above src directory i.e. to project root (Running from eclipse)
openFile = new File("problem1.txt");
Provide path from src or bin to file location (Running from eclipse):
openFile = new File("src/superbase/problem1.txt");
You can see the bellow example.You will get file from same package.
public class Hello {
public static void main(String[] args) {
Hello obj = new Hello();
System.out.println(obj.getFile("file/p1.txt"));
}
private String getFile(String fileName) {
StringBuilder result = new StringBuilder("");
//Get file from resources folder
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
result.append(line).append("\n");
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
}
This exception will is thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors when a file with the specified pathname does not exist. It is also thrown by these constructors if the file does exist but for some reason is inaccessible, for example when an attempt is made to open a read-only file for writing.
For more Information : https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html
This is how you can give correct path you did not add backslash and also backslash should be two because one backslash is consider as escape sequence.
File file = File("C:\\abcfolder\\textfile.txt");
I am working on a lab for a class where a user inputs a number and it recursively prints out a number pattern. For example,
The base case is if they enter 1, it will print: 1
If they enter 2 it will print: 1 2 1
If 3, it will print: 1 2 1 3 1 2 1
and then for something bigger, if they enter 7, it will print:
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 6
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 7
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 6
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
I'm a little stuck on what the number pattern is to be able to complete this problem. Does anyone have any ideas?
So you need to write a recursive function. Something of this form:
private String pattern(int num) {
// ...
}
The most important part is finding the right exit condition that should stop the recursion. In this case, that's when num == 1.
From the description, it looks like for a number k,
the output is pattern(k - 1) + k + pattern(k - 1).
I already spoiled too much.
You might need to improve the efficiency of this.
For example, realize that you don't need to run pattern(k - 1) twice,
it's enough to do it once.
I'm a little stuck on what the number pattern is to be able to
complete this problem.
Lets try to analyse the sequence using some function f
f(1) = 1 (Total digits = 1)
f(2) = 1 2 1 ( Total digits = 3)
f(3) = 121 3 121 (Total digits = 7)
f(4) = 1213121 4 1213121 (Total digits = 15)
f(5) = 121312141213121 5 121312141213121 (Total digits = 31)
So as you can observe total digits sequence looks like 1,3,7,15,31,....2^n-1
Now we can express this logic as mentioned below(Note : in order to help you to better understand how the program works i am printing sequence at every level)
public class SequenceGenerator {
public static void main(String[] args) {
generate(7);
}
static void generate(int depth) {
recursiveGenerator(1, null, depth);
}
static void recursiveGenerator(int num, String prev, int limit) {
if (num <= limit) {
if (prev != null) {
System.out.println();
}
if (prev != null) {
System.out.printf("%s %d %s", prev, num, prev);
} else {
prev = "";
System.out.printf("%d", num);
}
if (prev.equals("")) {
prev += num + prev;
} else {
prev += " " + num + " " + prev;
}
recursiveGenerator(++num, prev, limit);
}
}
}
Outputs
1
1 2 1
1 2 1 3 1 2 1
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 6 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 6 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 7 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 6 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
This is currently what I have for my Palindrome program for my computer science class. I have it pretty much working, except whenever a word is a palindrome, it is an infinite loop. I know I have to insert a number base case, but I do not how to do that...I'm really having trouble understanding recursion. Help is appreciated.
public class PalindromeTester
{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
String str, another = "y";
int left, right;
while (another.equalsIgnoreCase("y"))
{
System.out.println("Enter a potential palindrome:");
str = scan.next();
left = 0;
right = str.length() - 1;
tester(str, left, right);
System.out.println();
System.out.println("Test another palindrome (y/n)?");
another = scan.next();
}
}
public static void tester (String str, int left, int right)
{
Scanner scan = new Scanner (System.in);
while (str.charAt(left) == str.charAt(right) && left < right)
{
System.out.println(str);
tester( str, left + 1, right -1);
}
if (left < right)
{
System.out.println("That string is NOT a palindrome.");
}
else
{
System.out.println("That string IS a palindrome.");
}
}
}
You are using a while loop. With recursion, this is done implicitly.
You have to split the algorithm in small parts.
[] represents left, {} represents right.
[1] 2 3 4 5 6 7 8 9 0 9 8 7 6 5 4 3 2 {1} -->Level 0
1 [2] 3 4 5 6 7 8 9 0 9 8 7 6 5 4 3 {2} 1 -->Level 1
1 2 [3] 4 5 6 7 8 9 0 9 8 7 6 5 4 {3} 2 1 -->Level 2
1 2 3 [4] 5 6 7 8 9 0 9 8 7 6 5 {4} 3 2 1 -->Level 3
1 2 3 4 [5] 6 7 8 9 0 9 8 7 6 {5} 4 3 2 1 -->Level 4
1 2 3 4 5 [6] 7 8 9 0 9 8 7 {6} 5 4 3 2 1 -->Level 5
1 2 3 4 5 6 [7] 8 9 0 9 8 {7} 6 5 4 3 2 1 -->Level 6
1 2 3 4 5 6 7 [8] 9 0 9 {8} 7 6 5 4 3 2 1 -->Level 7
1 2 3 4 5 6 7 8 [9] 0 {9} 8 7 6 5 4 3 2 1 -->Level 8
1 2 3 4 5 6 7 8 9 {[0]} 9 8 7 6 5 4 3 2 1 -->Level 9
So, tester will continue until:
We've reached the middle of the word.
The word is not a palindrome
Example of case 2:
[1] 2 3 A 5 6 7 8 9 0 9 8 7 6 5 4 3 2 {1}
1 [2] 3 A 5 6 7 8 9 0 9 8 7 6 5 4 3 {2} 1
1 2 [3] A 5 6 7 8 9 0 9 8 7 6 5 4 {3} 2 1
1 2 3 [A] 5 6 7 8 9 0 9 8 7 6 5 {4} 3 2 1 --> !!!
I thought this method would be very helpful for the understanding of how is this recursion working
public static String positions(String word, int l, int r) {
char[] a = word.toCharArray();
String s = "";
// [letter] if left, {} if right, [{}] if both
for (int i = 0; i < a.length; i++) {
if (l == i && r == i) {
s += "{[" + a[i] + "]}";
} else if (l == i) {
s += "[" + a[i] + "]";
} else if (r == i) {
s += "{" + a[i] + "}";
} else {
s += a[i];
}
s+=" ";
}
return s;
}
And finally, the tester method.
public static boolean tester(String str, int left, int right) {
System.out.println(positions(str, left, right) +" tester(str, "+left +", "+right+")");
if (left>=right) // case 1
return true; // that's ok, we've reached the middle
// the middle was not reached yet.
// is the condition satisfied?
if (str.charAt(left) == str.charAt(right)) {
// yes. So, lets do it again, with the parameters changed
return tester(str, left + 1, right - 1);
}
//the condition was not satisfied. Let's get out of here.
else {
return false;
}
}
Some outputs:
Enter a potential palindrome:
1234567890987654321
[1] 2 3 4 5 6 7 8 9 0 9 8 7 6 5 4 3 2 {1} tester(str, 0, 18)
1 [2] 3 4 5 6 7 8 9 0 9 8 7 6 5 4 3 {2} 1 tester(str, 1, 17)
1 2 [3] 4 5 6 7 8 9 0 9 8 7 6 5 4 {3} 2 1 tester(str, 2, 16)
1 2 3 [4] 5 6 7 8 9 0 9 8 7 6 5 {4} 3 2 1 tester(str, 3, 15)
1 2 3 4 [5] 6 7 8 9 0 9 8 7 6 {5} 4 3 2 1 tester(str, 4, 14)
1 2 3 4 5 [6] 7 8 9 0 9 8 7 {6} 5 4 3 2 1 tester(str, 5, 13)
1 2 3 4 5 6 [7] 8 9 0 9 8 {7} 6 5 4 3 2 1 tester(str, 6, 12)
1 2 3 4 5 6 7 [8] 9 0 9 {8} 7 6 5 4 3 2 1 tester(str, 7, 11)
1 2 3 4 5 6 7 8 [9] 0 {9} 8 7 6 5 4 3 2 1 tester(str, 8, 10)
1 2 3 4 5 6 7 8 9 {[0]} 9 8 7 6 5 4 3 2 1 tester(str, 9, 9)
true
Test another palindrome (y/n)?
y
Enter a potential palindrome:
12345A678654321
[1] 2 3 4 5 A 6 7 8 6 5 4 3 2 {1} tester(str, 0, 14)
1 [2] 3 4 5 A 6 7 8 6 5 4 3 {2} 1 tester(str, 1, 13)
1 2 [3] 4 5 A 6 7 8 6 5 4 {3} 2 1 tester(str, 2, 12)
1 2 3 [4] 5 A 6 7 8 6 5 {4} 3 2 1 tester(str, 3, 11)
1 2 3 4 [5] A 6 7 8 6 {5} 4 3 2 1 tester(str, 4, 10)
1 2 3 4 5 [A] 6 7 8 {6} 5 4 3 2 1 tester(str, 5, 9)
false
Test another palindrome (y/n)?
In the main method,
System.out.println(tester(str, left, right));
In order to see the true/false output
Since your are using recursion (in its basic purposes mostly used to eliminate loops), isn't your while loop inside the tester() method supposed to be an if?
public static void tester (String str, int left, int right)
{
Scanner scan = new Scanner (System.in);
if (str.charAt(left) == str.charAt(right) && left < right)
{
System.out.println(str);
tester( str, left + 1, right -1);
}
else if (left < right)
{
System.out.println("That string is NOT a palindrome.");
}
else
{
System.out.println("That string IS a palindrome.");
}
}
I modified your tester() method and replaced your while with an if and moved your second if clause.
public static void tester(String str, int left, int right) {
if (str.charAt(left) == str.charAt(right) && left < right) {
tester(str, left + 1, right - 1);
} else {
if (left < right) {
System.out.println("That string is NOT a palindrome.");
} else {
System.out.println("That string IS a palindrome.");
}
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
___________1
__________1 2 1
_________1 2 3 2 1
________1 2 3 4 3 2 1
______1 2 3 4 5 4 3 2 1
_____1 2 3 4 4 4 4 4 3 2 1
___1 2 3 3 3 3 3 3 3 3 3 2 1
__1 2 2 2 2 2 2 2 2 2 2 2 2 2 1
_1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
I would like to create this pyramid using java? Any suggestion?
This should do it:
public class Tower {
public static void main(String[] args) {
System.out.println(" 1 ");
System.out.println(" 1 2 1 ");
System.out.println(" 1 2 3 2 1 ");
System.out.println(" 1 2 3 4 3 2 1 ");
System.out.println(" 1 2 3 4 5 4 3 2 1 ");
System.out.println(" 1 2 3 4 4 4 4 4 3 2 1 ");
System.out.println(" 1 2 3 3 3 3 3 3 3 3 3 2 1 ");
System.out.println(" 1 2 2 2 2 2 2 2 2 2 2 2 2 2 1 ");
System.out.println(" 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ");
}
}
Try using a mono-spaced font like courier.
This will surve the purpose. You can change the number 5 to another number other than 5. eg. 1,2,3,.. , 6,8
public static void main(String[] args) {
List<String> list = new LinkedList<String>();
for(int i = 5; i > 0; i-- ){
wrapWithNumber(list, i);
}
for (String string : editListToBeInTriangleShape(list)) {
System.out.println(string);
};
}
/**
* Wrap the number strings in the llist with a perticular number.
* #param list list of Strings
* #param ba number which need to wrapp the list with.
*/
private void wrapWithNumber(List<String> list, final int ba) {
list.add(0, String.format("%d",ba));
for (int i = 1; i < list.size(); i++) {
String newformat = "%1$d " + list.get(i) + " %1$d";
list.remove(list.get(i));
list.add(i,String.format(newformat, ba));
}
String lastFormat = "%1$d";
for(int i = 0; i < 2 * list.size();i++){
lastFormat += " %1$d";
}
if(list.size() != 1) {
list.add(String.format(lastFormat, ba));
}
}
/**
* Arrage the Strings in the list in triangular manner.
* #param list list of Strings.
*/
private List<String> editListToBeInTriangleShape(final List<String> list) {
final List<String> returnList = new LinkedList<String>();
for (int i = list.size(); i > 0; i--) {
String s = list.get(list.size()-i);
int possition = list.size()*2 + s.length()/2;
returnList.add(String.format("%"+possition+"s", s));
}
return returnList;
}
out put of this :
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 4 4 4 4 3 2 1
1 2 3 3 3 3 3 3 3 3 3 2 1
1 2 2 2 2 2 2 2 2 2 2 2 2 2 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
I would suggest a series of for loops.