Write a JAVA program to print below sequence: - java

Input: {a, b, c, d} (Character Array)
I want to generate below sequence using above character array as Input
Output:
a bcd
ab cd
abc d
abcd
a b c d
ab c d
a bc d
a b cd

You can try,
char[] a = { 'a', 'b', 'c', 'd' };
for (int i = 0; i < (a.length*2); i++) {
if (i < a.length) {
for (int j = 0; j < a.length; j++) {
System.out.print(a[j]);
if (j == i)
System.out.print(" ");
}
System.out.println("");
} else {
for (int k = 0; k < a.length; k++) {
System.out.print(a[k]);
if (k != (i - (a.length + 1)))
System.out.print(" ");
}
System.out.println("");
}
}

import org.apache.commons.lang3.StringUtils;
public class Demo2 {
public static void main(String...args){
char [] a = {'a','b','c','d'};
String str = String.valueOf(a);//convert to
String[] input = str.split("");//string array
String str1 = StringUtils.join(input,""); // join to "abcd" for the first half of output
String str2 = StringUtils.join(input," "); // join to "a b c d" for the second half of output
for(int i = 1; i<str1.length()+1; i++){
System.out.println(str1.substring(0, i)+" "+str1.substring(i, str1.length())); //insert " "at index i
}
System.out.println(str2);
for(int i = 1; i<str2.length()-1; i=i+2){
System.out.println(str2.substring(0, i)+""+str2.substring(i+1, str2.length())); //remove " " at index i
}
}
}

for (int i = (1 << (a.length - 1)) - 1; i >= 0; --i) {
System.out.print(a[0]);
for (int j = 0; j < a.length - 1; ++j) {
if ((i & (1 << j)) == 0)
System.out.print(" ");
System.out.print(a[j + 1]);
}
System.out.println();
}

this code works for the above given output,
for(i=0;i<(2*a.length);i++){
if(i<a.length){
for(j=0;j<a.length;j++){
System.out.print(a[j]);
if(j==i)
System.out.print(" ");//for white spaces
}
System.out.println(""); //new line
}
else{
for(k=0;k<a.length;k++){
System.out.print(a[k]);
if(k!=(i-(a.length+1)))
System.out.print(" ");
}
System.out.println("");
}
}
But, i think your code doesn't give the expected output, not even the first few lines as you said.

Related

Combine 2 2D arrays that both contain chars with java

I have to write a code as a task for my university and we have to recreate Minesweeper with java and it has to be runned in the command line.
For the matchfield we have to make an array that looks in the end like this picture:
Example how it sould look in the end
And to choose the field we have to use the scanner.
For example if you want to chose field C3, you have to type into the scanner C3.
At the moment im struggleing a little bit with the field.
I had 2 ideas but both didn't work out very well.
in the first try i tried to create everything with 2 for loops and 1 array but my problem was that I couldn't add 2 charrs, so I had the chars 0 to 9 and the charrs A to J.
In the second try I created 3 array, one with the numbers 0 to 9 and anothe array A to J and in the third array i wanted to combine both arrays. And now I'm wondering if this it's possible if I can acctually combine them in the way I want and if it's possible could somebody give me some help?
import java.util.Scanner;
import java.util.Arrays;
public class Minesweeper {
public static void main (String[] args) {
char c = 'A';
char d = '0';
char e = '9';
char f = 'J';
char[][] feldz = new char[11][11];
char[][] feldb = new char[11][11];
char[][] feld = new char[11][11];
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (i == 0 && j == 0) {
feldz[i][j] = ' ';
System.out.print(feldz[i][j] + " |");
}
if (d > e) {
d = '0';
}
if (d <= e && i > 0){
feldz[i][j] = d;
System.out.print(feldz[i][j] + " |");
}
if (i > 0 && j == 10) {
d++;
}
}
System.out.println("");
}
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (i == 0 && j == 0) {
feldb[i][j] = ' ';
System.out.print(feldb[i][j] + " |");
}
if (i > 0 && j == 0){
feldb[i][j] = ' ';
System.out.print(feldb[i][j] + " |");
}
if (c > f) {
c = 'A';
}
if(c <= f && j > 0){
feldb[i][j] = c;
System.out.print(feldb[i][j] + " |");
c++;
}
if (j == 10){
System.out.println("");
}
}
}
}
}
You don't actually need array to print the maze , nested loops is enough for that. 2d Array is only required to store the input. Please try the below code:
int size = 10;
int [][] maze = new int[size][size];
while (true){
System.out.print(' ');
for (int i = 0; i < size; i++) {
System.out.print('|');
System.out.print((char) ('A' + i));
}
for (int i = 0; i < size; i++) {
System.out.println("");
System.out.print(i);
for (int j = 0; j < size; j++) {
System.out.print('|');
if(maze[i][j] > 0) {
System.out.print(maze[i][j]);
} else {
System.out.print(' ');
}
}
}
int row = -1;
int col = -1;
System.out.println("\nEnter CoOrdinates");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if(input.length() == 2) {
char charAt = input.charAt(0);
if(charAt >= 'A' && charAt <= 'A'+size-1) {
col = charAt-'A';
}
charAt = input.charAt(1);
if(charAt >= '0' && charAt <= '0'+size-1) {
row = charAt-'0';
}
if(row != -1 && col != -1) {
System.out.println("Enter Action");
input = scanner.nextLine();
int action = Integer.parseInt(input);
maze[row][col] = action;
} else {
System.out.println("Incorrect Input");
}
}
}

Triangle printing letters in the wrong order, and unwanted characters

The purpose of this program is for the user to decide the length (rows) of a triangle, and also decide if it should be facing up or down. And the triangle is made of letters, so it is supposed to look like this:
How many rows would you like? (finish with -1): 4
Do you want the triangle to face up (1) or down (2)? 1
A
A B
A B C
A B C D
How many rows would you like? (finish with -1): 6
Do you want the triangle to face up (1) or down (2)? 2
A B C D E F
A B C D E
A B C D
A B C
A B
A
I have two problems when I try to get the triangle to print facing down, first the letters look like this (it should begin with an A)
F E D C B A
F E D C B
F E D C
F E D
F E
F
And the letters are followed by loads of different characters that I don't want. I've tried so many things and nothing seems to be working. I could really use some advice.
This is my code so far:
import java.util.Scanner;
public class Triangle {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int a = 0;
int b = 0;
while (a != -1) {
System.out.println("How many rows would you like? (finish with -1):");
a = scan.nextInt();
if (a != -1) {
b = a - 1;
int j = 'A';
char alphabet = (char) (j + 'A');
System.out.println("Do you want the triangle to face up (1) or down (2)?");
int c = scan.nextInt();
if (c == 1) {
for (int i = 1; i <= b + 'A'; i++) {
for (j = 'A'; j <= i; j++)
System.out.print((char) j + " ");
System.out.println(alphabet);
}
} else {
for (int i = 1; i <= b + 'A'; i++) {
for (j = b + 'A'; j >= i; j--)
System.out.print((char) j + " ");
System.out.println(alphabet);
}
}
}
}
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = 0;
int b = 0;
while (a != -1) {
System.out.println("How many rows would you like? (finish with -1):");
a = scan.nextInt();
if (a != -1) {
System.out.println("Do you want the triangle to face up (1) or down (2)?");
int c = scan.nextInt();
if (c == 1) {
for (int i = 0; i < a; i++) {
for (int j = 0; j <= i; j++) {
System.out.print((char) (j + 'A'));
}
System.out.println();
}
} else {
for (int i = 0; i < a; i++) {
for (int j = a; j > i; j--) {
System.out.print((char) (a - j + 'A'));
}
System.out.println();
}
}
}
}
}
Adopt a more modular solution given below.
It prints both triangles composed of 4 rows, one facing up and the other facing down.
public static void main(String args[]) {
int a = 4; // # of rows
// Triangle facing up
for (int i = 1; i <= a; i++) // i - How many letters in this row (also row No)
printRow(i);
System.out.println("--------"); // Separator
// Triangle facing down - Start from the longest row, then decrease its length
for (int i = a; i > 0; i--)
printRow(i);
}
static void printRow(int length) {
for (int j = 0; j < length; j++) // j - char code shift
System.out.printf("%c ", j + 'A');
System.out.println();
}
This solution is more elegant, as the code to print a row is not repeated.
Note also a more natural way to express the length of consecutive rows: For the triangle facing down the loop decreases the row length.

Print a text pattern in java

I need the pattern to be printed in the form
ABCDEF FEDCBA
ABCDE EDCBA
ABCD DCBA
ABC CBA
AB BA
A A
Below is my code :
public static void main(String args[])
{
char[] c = {'A','B','C','D','E','F','G'};
int i, j;
for(j = 5; j >= 0; j--)
{
for(int k = 0; k <= j; k++)
{
System.out.print(c[k]);
}
for(i = j; i >= 0; i--)
{
System.out.print(c[i]);
}
System.out.println();
}
}
Which gives me the output as
ABCDEFFEDCBA
ABCDEEDCBA
ABCDDCBA
ABCCBA
ABBA
AA
It was fairly easy to reach to this output. However, i haven't been able to provide spaces. I know the loop to produce the space will come in between both the for loops but i couldn't figure out how to do it. Its bugging me for a while.
I give you hint, count the spaces :
For line 1 : 1 spaces
For line 2 : 3 spaces
For line 3 : 5 spaces
For line 4 : 7 spaces
etc., see the pattern? :)
And yes, put one more "space for cycle" between existing for cycles.
Spoiler ALERT, here is Java solution, but try to do it without it.
This is fully working code, it also works with any size of array :
public static void main(String args[]) {
char[] c = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'Y', 'Z'};
int i, j;
for (j = c.length-1; j >= 0; j--) {
for (int k = 0; k <= j; k++) {
System.out.print(c[k]);
}
for (int k = 0; k < (c.length-j)*2 - 1; k++) {
System.out.print(" ");
}
for (i = j; i >= 0; i--) {
System.out.print(c[i]);
}
System.out.println();
}
}
Sample output :
ABCDEFGYZ ZYGFEDCBA
ABCDEFGY YGFEDCBA
ABCDEFG GFEDCBA
ABCDEF FEDCBA
ABCDE EDCBA
ABCD DCBA
ABC CBA
AB BA
A A
char[] c = {'A','B','C','D','E','F','G'};
int i, j,n,p=1;
for(j = 5; j >= 0; j--)
{
for(int k = 0; k <= j; k++)
{
System.out.print(c[k]);
}
for(n = 1; n <= p; n++)
System.out.print(" ");
p+=2;
for(i = j; i >= 0; i--)
{
System.out.print(c[i]);
}
System.out.println();
}
Even though there are some (already) answered solutions, too many loops increase the complexity:
char[] c = { 'A', 'B', 'C', 'D', 'E', 'F', 'G' };
for (int i = 0; i < c.length; i++) {
String tmp = String.valueOf(c).substring(0, c.length - i);
System.out.printf("%s %" + (c.length + i) + "s%n", tmp, new StringBuilder(tmp).reverse());
}
OUTPUT
ABCDEFG GFEDCBA
ABCDEF FEDCBA
ABCDE EDCBA
ABCD DCBA
ABC CBA
AB BA
A A
Your char array can be increased any time, the output would be "the same" (in terms of formatting).
Each row of your pattern is of fixed width: 13 characters. That means that if you print j characters (index of your outer loop), you need to print 13-2*j spaces.
for (int k=0; k<13-2*j; k++){
System.out.print(" ");
}
Here I use a new variable max to set up j initially. This variable is used for the len calculation for the spaces.
char[] c = {'A','B','C','D','E','F','G'};
int i, j;
int max = 5; //your max output (could be 6)
for(j = max; j >= 0; j--)
{
for(int k = 0; k <= j; k++)
{
System.out.print(c[k]);
}
int len = max*2+1; //length calculation
for(int x = 0; x < len-2*j; x++){ //space loop
System.out.print(" ");
}
for(i = j; i >= 0; i--)
{
System.out.print(c[i]);
}
System.out.println();
}
Please use proper names for your variables. Java is not Basic, so you can use up to 65,535 characters in a variable name if you wish.
Documentation through code helps people who have to maintain code in the future.
public class PrintChars {
public static void main(String args[]) {
char[] chars = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H' };
int length = chars.length;
for (int row = length; row > 0; row--) {
for (int left = 0; left < row; left++) {
System.out.print(chars[left]);
}
for (int space = 0; space < (length-row)*2+1; space++) {
System.out.print(' ');
}
for (int right = row-1; right >= 0; right--) {
System.out.print(chars[right]);
}
System.out.println();
}
}
}
Output:
ABCDEFGH HGFEDCBA
ABCDEFG GFEDCBA
ABCDEF FEDCBA
ABCDE EDCBA
ABCD DCBA
ABC CBA
AB BA
A A

Common length of strings in java

In this java program everything works fine but at the last i have to get the number of words matched in length of character but i cant how to get it?
Scanner input = new Scanner(System.in);
String s1 = "Enter the name 1:";
System.out.println(s1);
s1 = input.next();
String s2 = "Enter the name 2:";
System.out.println(s2);
s2 = input.next();
if (s1.equals(s2)) {
System.out.println("They match");
} else {
System.out.println("They dont match");
}
char[] c = s1.toCharArray();
char[] d = s2.toCharArray();
for (char i = 0; i < c.length; i++) {
for (char j = 0; j < d.length; j++) {
if (c[i] == d[j]) {
System.out.println("The number of letters matched are :" + c[i]);
}
}
}
System.out.println("The number of letters matched are :" + c.length);
Use a counter
int counter = 0 ;
for (char i = 0; i < c.length; i++) {
boolean found = false;
for (char j = 0; j < d.length; j++) {
if (c[i] == d[j]) {
found = true;
System.out.println("The number of letters matched are :" + c[i]);
break;
}
}
if(found){
counter++;
}
}
System.out.println("The number of letters matched are :" + counter);
char[] c = s1.toCharArray();
char[] d = s2.toCharArray();
int count = 0;
for (char i = 0; i < c.length; i++) {
for (char j = 0; j < d.length; j++) {
if (c[i] == d[j]) {
count++;
}
}
}
System.out.println("The number of letters matched are :" + count);
I think this is what you are looking for.
You need to count the number of matches in your loop, then after looping display the number of letters that are in both arrays.
If the objective is to get the number of common characters between two strings, then one approach is to convert both strings to character sets and do set intersection between the two sets and get its size.
If you want the number of times a character in s1 also appears in s2:
int counter = 0;
for (int i=0; i<s1.length(); i++) {
if (s2.indexOf(s1.charAt(i)) >= 0) {
counter++;
}
}
System.out.println("The number of letters matched are :" + counter);
If instead you want the number of distinct characters shared by s1 and s2:
Set<Character> set = new HashSet<>();
int counter = 0;
for (int i=0; i<s1.length(); i++) {
set.add(s1.charAt(i));
}
for (int j=0; j<s2.length(); j++) {
if (set.contains(s2.charAt(j))) {
counter++;
}
}
System.out.println("The number of letters matched are :" + counter);

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