[英]Write a JAVA program to print below sequence:
Input: {a, b, c, d}
(Character Array) 输入:
{a, b, c, d}
(字符数组)
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. 但是,我认为您的代码没有给出预期的输出,甚至没有您所说的前几行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.