Triangle Word Pattern using Nested Loops in Java - java

For this assignment, after inputting any word, it will print it in a pattern shown below (in this case, the word is computer):
C
O O
M M
P P
U U
T T
E E
RETUPMOCOMPUTER
Currently, my code is this:
String output = "";
for (int a = word.length()-1; a >= 1; a--)
{
for (int b = 0; b < word.length(); b++)
{
out.print(" ");
}
out.println(word.charAt(word.length()-1-a));
}
for (int c = 0; c < word.length(); c++)
{
out.print(word.charAt(word.length()-1-c));
}
out.print(word.substring(1));
return output + "\n";
The output for my code currently is:
C
O
M
P
U
T
E
RETUPMOCOMPUTER
Any advice or tips is much appreciated, thank you in advance!

The logic is simple, first try to create the last line, using reverse of StringBuilder. Then print each line from the first to the last line.
The last line case is simple.
From the first to the last line - 1, we only need to print those characters that has the distance equal 0, 1, 2 ... to the center of the last line.
public void printTriangle(String input) {
String tmp = input.substring(1);//Take the suffix
StringBuilder builder = new StringBuilder(tmp);
builder = builder.reverse().append(input);//Reverse, then append it
String line = builder.toString();//This is the last line
for(int i = 0; i < input.length(); i++){
for(int j = 0; j < line.length(); j++){
//Print the last line, or those that have distance equals i to the center of the last line
if(i + 1 == input.length() || Math.abs(j - line.length()/2) == i){
System.out.print(line.charAt(j));
}else{
System.out.print(" ");
}
}
System.out.println();
}
}
Input
COMPUTER
Output
C
O O
M M
P P
U U
T T
E E
RETUPMOCOMPUTER
Input
STACKOVERFLOW
Output
S
T T
A A
C C
K K
O O
V V
E E
R R
F F
L L
O O
WOLFREVOKCATSTACKOVERFLOW

You asked for nested loops, but there are a few other ways including padding it with spaces. If you are allowed to do that, you only need a single loop:
public static void printTriangle(String str){
int len = str.length()-1, idx = 1;
System.out.println(String.format("%"+(len+1)+"s", str.charAt(0)));
for(int x=0; x<str.length()-2; x++){
System.out.print(String.format("%"+(len--)+"s", str.charAt(idx)));
System.out.println(String.format("%"+(idx*2)+"s", str.charAt(idx++)));
}
System.out.println(new StringBuilder(str.substring(1)).reverse().toString() + str);
}
Output:
C
O O
M M
P P
U U
T T
E E
RETUPMOCOMPUTER

Instead of doing a code that will magically work for every case, try using a code that addresses every case:
String someString = "COMPUTER";
switch(someString.length()) {
case 0: System.out.println();
break;
case 1: System.out.println(someString);
break;
default:
int _spaces_before_after = someString.length()-1;
int _spaces_middle = 0;
for(int i=0; i<someString.length(); i++){
if(i!=someString.length()-1){
if(i==0){
for(int j=0; j<_spaces_before_after; j++)
System.out.print(" ");
System.out.print(someString.charAt(0));
for(int j=0; j<_spaces_before_after; j++)
System.out.print(" ");
System.out.println();
_spaces_middle = 1;
}
else {
for(int j=0; j<_spaces_before_after; j++)
System.out.print(" ");
System.out.print(someString.charAt(i));
for(int j=0; j<_spaces_middle; j++)
System.out.print(" ");
System.out.print(someString.charAt(i));
for(int j=0; j<_spaces_before_after; j++)
System.out.print(" ");
System.out.println();
_spaces_middle+=2;
}
_spaces_before_after-=1;
}
else {
for(int j=someString.length()-1; j>=0; j--)
System.out.print(someString.charAt(j));
for(int j=1; j<someString.length(); j++)
System.out.print(someString.charAt(j));
}
}
break;
}

Suppose you have a string str of length n. You'll have a matrix of size n × 2n+1.
First, you need to define the center c of your triangle, which would be the position n
In your first line of the matrix, you draw only the first letter (str[0]) in the center and then go to the next line.
In the second line, you draw the second letter (str[1]) in the positions c-1 and c+1.
In the third line, you draw the third letter (str[2]) in the positions c-2 and c+2.
And so on.
The last line is the trickier. Starting from the center c, you have to draw the whole word str. From the center, you start writing your string forwards and backwards.
I've tried some implementation, it's really simple:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int n = str.length();
char[][] matrix = new char[n][2*n+1];
char[] chrArr = str.toCharArray();
// initializes the matrix with blank spaces
for (int i = 0; i < n; i++) {
for (int j = 0; j < 2*n+1; j++) {
matrix[i][j] = ' ';
}
}
// build the two sides of the triangle
for (int i = 0; i < n - 1; i++) {
matrix[i][n-i] = chrArr[i];
matrix[i][n+i] = chrArr[i];
}
// last line, build the base of the triangle
for (int i = 0; i < n; i++) {
matrix[n-1][n-i] = chrArr[i];
matrix[n-1][n+i] = chrArr[i];
}
// print
for (int i = 0; i < n; i++) {
for (int j = 0; j < 2*n+1; j++) {
System.out.print(matrix[i][j]);
}
System.out.print("\n");
}
Here is the sample code running in ideone.
You can try it with any string size.

Related

Using For Loop to Print Pattern in Java

I need to print this:
I need to print this square using a for loop in java.
This is what I have so far:
public static void main(String [] args)
{
for(int i = 0; i < 5; i++){
System.out.print("O ");
}
System.out.println();
for(int i = 0; i < 4; i++){
System.out.print("O ");
}
}
The easiest solution would be to nest two loops, first print O then use a second loop to print .. You know that each line should have a decreasing number of O (and increasing number of .s). In fact, you have 5 - i and i of each per line (where i is row number). And you can use the outer loop to determine how many of each should be drawn with those formulae. Like,
int size = 5;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size - i; j++) {
System.out.print("O ");
}
for (int j = 0; j < i; j++) {
System.out.print(". ");
}
System.out.println();
}
Which outputs (as requested)
O O O O O
O O O O .
O O O . .
O O . . .
O . . . .
Another option would be to create a StringBuilder to represent the initial conditions, print and then mutate the StringBuilder. This uses additional storage, but eliminates the need for nested loops.
int size = 5;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
sb.append("O ");
}
for (int i = 0; i < size; i++) {
System.out.println(sb);
sb.setCharAt(sb.length() - (i * 2) - 2, '.');
}
And, you could also make that with an array of boolean(s) (e.g. a bitmask). Convert false to O and true to ., and set the last element offset by the index to true on each iteration. Like,
int size = 5;
boolean[] arr = new boolean[size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(arr[j] ? ". " : "O ");
}
System.out.println();
arr[size - i - 1] = true;
}
This is not a 'design pattern' problem. You just need to use the logic with loops.
Here's the logic.
In a square of n x n cells, the ith row contains (n-i) ovals and i
dots, where 0 <= i < n.
Refer to the other answer to see a working snippet.

Printing a word in a diamond format

My assignment is to print a word in the shape of a diamond like so:
*****s
****p*p
***i***i
**d*****d
*e*******e
r*********r
*e*******e
**d*****d
***i***i
****p*p
*****s
P.S. The asterisks are only there to show spacing, pretend one asterisk represent one space.
So far I have this:
public class DiamondWords
{
public static void main(String[] args)
{
Scanner kbReader = new Scanner(System.in);
System.out.print("Enter a word to be printed in diamond format: ");
String word = kbReader.nextLine();
int wordLength = word.length();
for(int i = 0; i<wordLength-1; i++)
{
System.out.print(" ");
}
wordLength = wordLength - 1;
System.out.print(word.charAt(0));
System.out.println();
int x =1;
int d =1;
for(int j =wordLength; j>0; j--)
{
wordLength = j;
for(int a =1; a<wordLength; a++)
{
System.out.print(" ");
}
System.out.print(word.charAt(x));
for(int q =0; q<d; q++)
{
System.out.print(" ");
}
d+=2;
System.out.print(word.charAt(x));
x++;
System.out.println();
}
//r*********r
//*e*******e
//**d*****d
//***i***i
//****p*p
//*****s
}
}
Which prints the first half of the diamond perfectly:
*****s
****p*p
***i***i
**d*****d
*e*******e
r*********r
The only part where I'm getting stuck is when I have to print the latter half of the diamond. Can anyone point me in the right direction? Please do not write the code for me, just try and give me some pointers based off the logic I've shown. Thank you.
Try to have only one loop. A very easy way to handle the "technicalities" of the problem is to work with an char array for the output. First you initialize it with the proper length, fill it with blanks (there is a library function for it), fill the two characters, and only then convert it to a String.
The only open question is where to put the characters, and I don't want (and should) to spoil that.
int fullLength = 2 * word.length() - 1;
for(int i = 0; i < fullLength; i++) {
char[] line = new char[fullLength];
Arrays.fill(line, ' ');
int k = ???;
char c = s.charAt(k);
line[word.length() - 1 - k] = c;
line[word.length() - 1 + k] = c;
System.out.println(new String(line));
}
Obviously, you want to calculate the position "from the middle" (so we have something like word.length() - 1 +- k), and for the first half of the word, k is equal to i.
Your task, should you decide to accept it, is to find out how to "bend k back" for the second half of the word.
import java.util.Scanner;
public class DiamondWords
{
public static void main(String[] args)
{
Scanner kbReader = new Scanner(System.in);
System.out.print("Enter a word to be printed in diamond format: ");
String word = kbReader.nextLine();
int wordLength = word.length();
int wordLength2 = word.length();
int wordSize = word.length();
int wordLengthReverse = word.length();
for(int i = 0; i<wordLength-1; i++)
{
System.out.print(" ");
}
wordLength = wordLength - 1;
System.out.print(word.charAt(0));
System.out.println();
int x =1;
int d =1;
for(int j =wordLength; j>0; j--)
{
wordLength = j;
for(int a =1; a<wordLength; a++)
{
System.out.print(" ");
}
System.out.print(word.charAt(x));
for(int q =0; q<d; q++)
{
System.out.print(" ");
}
d+=2;
System.out.print(word.charAt(x));
x++;
System.out.println();
}
System.out.print(" " + word.charAt(wordLength2-2));
int spaceLength =((wordLength2*2)-1) -4;
int u =spaceLength -2;
for(int i =0; i < spaceLength; i++)
{
System.out.print(" ");
}
System.out.print(word.charAt(wordLength2-2));
System.out.println();
int m=3;
for(int num =2; num<wordSize-1; num++)
{
wordLength2 = num;
for(int i =0; i<num; i++)
{
System.out.print(" ");
}
System.out.print(word.charAt(wordSize-m));
for(int b = 0; b<u; b++)
{
System.out.print(" ");
}
System.out.print(word.charAt(wordSize-m));
System.out.println();
m++;
u = u-2;
}
for(int r =0; r<word.length()-1; r++)
{
System.out.print(" ");
}
System.out.print(word.charAt(0));
}
}
I have finished. This is my final code. I understand it is not as efficient as possible, or easy to follow, but it is flexible and not hard-coded, so I am content.

Getting each letter in a String only once

I'm writing a Java program for Horspool's algorithm, and am having a bit of trouble. I'm trying to create an array of chars that will hold each letter in a string, but I don't want duplicates of the letters. Right now this is my code:
public static void main(String[] args)
{
Scanner scanIn = new Scanner (System.in);
int count = 0;
int count2 = 0;
int inc = 0;
//The text to search for the phrase in
String t = "";
//The phrase/pattern to search for
String p = "";
System.out.println(" ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Harspool's Algorithm: ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" ");
System.out.println("Please enter the full text: ");
t = scanIn.nextLine();
System.out.println("Please enter the pattern to search for: ");
p = scanIn.nextLine();
char[] text = new char[t.length()];
char[] pattern = new char[p.length()];
char[] alphabet = new char[t.length()];
for (int i = 0; i < alphabet.length; i++)
{
alphabet[i] = ' ';
}
for (int i = 0; i < text.length; i++)
{
text[i] = t.charAt(i);
}
for (int i = 0; i < pattern.length; i++)
{
pattern[i] = p.charAt(i);
}
while (inc < text.length)
{
for (int j = 0; j < text.length; j++)
{
if (text[inc] != alphabet[j])
{
count++;
}
if (count == p.length() - 1 && count2 < text.length)
{
alphabet[count2] = text[inc];
count2++;
count = 0;
inc++;
}
}
}
for (int i = 0; i < alphabet.length; i++)
{
System.out.print(alphabet[i]);
}
}
I believe the problem is in the while loop, but I can't figure out what exactly is going wrong. Right now, it will print out the entire string passed in, when it should be printing each letter only once. Could someone please help?
Instead of counting the occurrences of each character, Use Set<Character>. A set contains unique elements and so you will not have duplicates that way.
You can also convert a Set to an array by doing mySet.toArray(new String[mySet.size()]); or just mySet.toArray(new String[0]);
Your code is not easy to read. You might consider using the following algorithm instead.
int ccount[256];
int ii;
for(ii=0;ii<256;ii++) ccount[ii]=0;
for (ii = 0; ii < text.length; ii++)
{
ccount[t.charAt(i)%256]++;
}
for (ii = 0; ii<256; ii++) {
if(ccount[ii]>0) System.out.printf("%c", ii);
}
EDIT - made sure ccount was initialized, and captured characters outside of range 0-255 with % operator.

Writing the contents of an array to a string

I have a two-dimensional character array board[row][col], which is designed to simulate a game board for a game of Xs and Os. (For reference, each element in the array is either an X, an O, or ' ', a space to signify no move in that square.)
I am trying to get a string of all characters in the array, row by row. That is, the first row will be printed to string, then the second row will be appended to that string, until all rows are traversed. In the end, the result should look like a string of symbols such as "XXO X OOX" for this game board:
X X O
X
O O X
How can this be done?
try:
StringBuilder str = new StringBuilder();
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
str.append(board[i][j]);
you could find more data about StringBuilder here.
I think better sulution will be like this
char [][] board = new char[][]{{'x','x','o',},{'x',},{'o','o','x',}};
StringBuilder builder = new StringBuilder();
for (char[] aBoard : board)
builder.append(String.valueOf(aBoard)).append(" ");
System.out.println(builder.toString());
out
xxo x oox
You can try something along these lines:
char[][] board = {{'X', 'O', 'X'}, {0, 'O', 0}, {'X', 'O', 'X'}};
String s = "";
for (char[] row : board) {
for (char c : row)
s += c == 0 ? " " : c;
s += "\n";
}
System.out.println(s);
Output:
XOX
O
XOX
Edit: If you want the output to be spaced out, you could use
for (char[] row : board) {
for (char c : row)
s += c == 0 ? " " : c + " ";
s += "\n";
}
Output:
X O X
O
X O X
for(int i=0; i< board.length; i++){
for(int j=0; i< board[i].length; j++){
System.out.print(""+board[i][j]); //<- use print() here
}
System.out.println(); //<- use println() here
}
Have nested loops like so:
for (int i = 0; i < board.length; i++)
{
for (int j = 0; j < board[0].length; j++)
{
System.out.print(board[i][j] + " ");
}
System.out.println();
}
The first print statement will add all the characters from one row together and then the next print statement, outside of the second loop, will append a newline.
String[][] board = {{"X", "X","O"},{" ", "X", " "},{"O", "O", "X"}};
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}

java for loop pyramid

I want to create a loop with a string so that with each successive loop, the last and first characters from the previous line will not be displayed. I'm also trying to print the length of each loop next to each line. It will look like an upside-down pyramid.
I had this:
for(int scounter = fullName.length(); scounter > 0; scounter--)
for (String name : fullName)
for(int counter = 0; counter < fullName.length(); counter++)
System.out.println(scounter + "[ " + fullName.substring(0, fullName.length() counter)+ " ]");
It prints something like this:
24******
24****
24**
24*
Yet I'm looking for something similar to this:
7*******
5*****
4***
1*
String str = "*******";
for (int i = 0, l = str.length(); i <= l/2; i++) {
String line = str.substring(i, l - i);
System.out.printf("%" + (i + 1) + "d%s\n", line.length(), line);
}
This will print:
7*******
5*****
3***
1*
I'm assuming you meant 3 instead of 4 in your example, that is, that you want to decrement by 2.
I started working on this problem and found my solution to be slightly different from Joao's. Hope this helps!
public class pyramid
{
public static void main(String[] args)
{
for(int i=0, sz=args[0].length();i<sz; ++i,--sz)
{
System.out.printf("%"+(i+1)+"d%s\n", sz-i, args[0].substring(i,sz));
}
}
}
Invocation as per request:
java pyramid abcdefg
7abcdefg
5bcdef
3cde
1d
java pyramid abcdef
6abcdef
4bcde
2cd
Your example does not match the words of your question, so here's a method that behaves according to your words as I understand them:
public void pyramid(String text) {
int len = text.length();
int start = 0;
while (start < len) {
for (int i = 0; i < start; ++i) {
System.out.print(" ");
}
System.out.println(text.substring(start, len));
++start;
--len;
}
}
for(int i = 1; i<=4; i++) {
for(int k = 3;k>=i; k--){
System.out.print(" ");
}
for(int j = 1; j<=i; j++){
System.out.print("*");
}
for(int n = 2; n<=i;n++){
System.out.print("*");
}
System.out.println(" ");
}
for(int m = 1 ;m<=3; m++){
for(int o = 1;o<=m; o++){
System.out.print(" ");
}
for(int p = 3;p>=m;p--){
System.out.print("*");
}
for(int q = 2;q>=m;q--){
System.out.print("*");
}
System.out.println();
}
}
}

Categories

Resources