仅使用一个循环打印图案

时间:2012-12-18 16:12:47

标签: java loops for-loop design-patterns

我使用一个循环打印了这个模式:

*
**
***
****
*****

String s = "";
for (i = 1; i <= n; ++i) {
    s += "*";
    System.out.println(s);
}

现在我想要如何仅使用一个循环打印以下模式。

1)
    *
   * *
  * * *
 * * * *
* * * * *

2)
  * * * * * 
   * * * *
    * * *
     * *
      *

3)
   1 2 3 4 5
   1 2 3 4
   1 2 3 
   1 2
   1

以及仅使用一个循环的其他类似模式,我使用多个循环完成了所有这些模式。

11 个答案:

答案 0 :(得分:6)

  

我想要优化。两个循环的时间复杂度将是O(n ^ 2),而对于仅一个循环,它将是O(n)。并且O(n)&lt;为O(n ^ 2)。

您意识到99.999%的时间将用于更新控制台。如果你想节省时间,不要写任何东西。通过比较,循环所花费的时间是微不足道的。

BTW你产生的星数是O(N ^ 2)所以时间复杂度为O(N ^ 2),无论你是使用1,2或3个循环。

答案 1 :(得分:2)

以下代码将使用单循环打印菱形。您可以相应地更改大小变量的值。

import java.util.Arrays;

class DiamondShapeUsingSingleLoop{
    public static void main(String args[]){
        int size = 5;
        for(int rowNumber = -size +1 ; rowNumber < size ; rowNumber++){
            char row[] = new char[2*size - Math.abs(rowNumber) - 1];
            Arrays.fill(row,0,Math.abs(rowNumber),' ');
            Arrays.fill(row,Math.abs(rowNumber), row.length,'*');
            System.out.println(String.valueOf(row));
        }
    }
}

输出如下:

    *                                                                                                                                                           
   ***                                                                                                                                                          
  *****                                                                                                                                                         
 *******                                                                                                                                                        
*********                                                                                                                                                       
 *******                                                                                                                                                        
  *****                                                                                                                                                         
   ***                                                                                                                                                          
    *

答案 2 :(得分:1)

    *
   * *
  * * *
 * * * *
* * * * *

写下一些要求 - 然后解决方案变得清晰:

  • 在迭代 0 时,在 4
  • 位置打印 1 "* "序列
  • 在迭代 1 时,在位置 3 打印 2 "* "序列
  • 在迭代 2 上,在位置 2 打印 3 "* "序列
  • 在迭代 3 时,在 1 位置打印 4 "* "个序列
  • 在迭代 4 时,在 0
  • 位置打印 5 "* "个序列

答案 3 :(得分:0)

int col = 1;        int space = 4;

   for(int i=1;i<=5;i++){
       for(int j=1;j<=space;j++){
           System.out.print(" ");

    }
       space--;

    for(int j=1;j<=col;j++){
    System.out.print("*");
        }
    System.out.println();
    col=col+2;

答案 4 :(得分:0)

您只需使用一个循环就可以打印钻石 如果你想打印金字塔使用这个程序的半逻辑

import java.util.Scanner;
class DiamandOneLoop {

    public static void main(String arg[]){
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the row Diamond Size");
        int n=sc.nextInt();
        String numSp="                                                                   ";
        String spaceAdd=numSp.substring(0,n-1);
        StringBuilder space=new StringBuilder(spaceAdd);
        StringBuilder star=new StringBuilder("* ");

        for(int i=1;i<=n*2-1;i++){
            if(i<n){
                System.out.print(space);
                space.delete(0,1);
                System.out.println(star);
                star.append("* ");
            }
            if(i==n){
                System.out.println(star);
            }
            if(i>n){
                space.append(' ');
                System.out.print(space);
                star.delete(0,2); 
                System.out.println(star);
            }
        }
    }
} 

答案 5 :(得分:0)

使用单循环打印图案:

代码用objective-c编写,任何人都可以使用这种逻辑并用各自的语言编写程序。

int k = 5;

for (int i = 1; i<= k; i++)
{
    NSLog(@"%d",i);
    if (i==k) {
        i=0;
        k--;
        NSLog(@"\n");
    }
}

输出:

1 2 3 4 5

1 2 3 4

1 2 3

1 2

1

答案 6 :(得分:0)

试试这个JavaScript代码:

public class SaveRetrieveObjects {
    List<Item>  objs        = new LinkedList<Item>();
    File        fileName    = new File("objects.sav");

public SaveRetrieveObjects() {
    createItems();
    showItems();
    serializeObjs(objs, fileName);
    objs = deserializeObjs(objs, fileName);
    showItems();
    System.out.println("Vale!");
}

private void createItems() {
    Item oneObject = new Item();
    oneObject.setId("Citric-45");
    oneObject.setDesc("orange");
    oneObject.setCost(12345.67);
    oneObject.setQty(67);
    oneObject.setBool(true);
    oneObject.setColor(Color.orange);
    objs.add(oneObject);

    oneObject = new Item();
    oneObject.setId("Mobil-12");
    oneObject.setDesc("car");
    oneObject.setCost(67890.12);
    oneObject.setQty(2);
    oneObject.setBool(true);
    oneObject.setColor(new Color(1, 2, 3));
    objs.add(oneObject);
}

private void showItems() {
    Item itm;
    for (int j = 0; j < objs.size(); j++) {
        itm = objs.get(j);
        System.out.println("Item " + (j + 1) + " Contents:");
        System.out.print("\t" + itm.getId());
        System.out.print("\t" + itm.getDesc());
        System.out.print("\t" + itm.getCost());
        System.out.print("\t\t" + itm.getQty());
        System.out.println("\t" + itm.isBool());
        System.out.println("\t" + itm.getColor());
    }
     System.out.println("----------------------------------------------------");
}

private void serializeObjs(List<Item> objs, File file) {
    System.out.println("Serialization process started");
    FileOutputStream fos = null;
    ObjectOutputStream oos = null;
    try {
        fos = new FileOutputStream(file);
        oos = new ObjectOutputStream(fos);
        oos.writeObject(objs);
    } catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } finally {
        try {
            oos.close();
            fos.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
    System.out.println("\nSerialization ended successfully");
    System.out.println("Checkout your specified output file");
    System.out.println("-----------------------------------");
}

@SuppressWarnings("unchecked")
private List<Item> deserializeObjs(List<Item> objs, File file) {
    objs.clear();
    System.out.println("Deserialization process started");
    FileInputStream fis = null;
    ObjectInputStream ois = null;
    try {
        fis = new FileInputStream(file);
        ois = new ObjectInputStream(fis);
        objs.addAll((Collection<? extends Item>) ois.readObject());
    } catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } finally {
        try {
            ois.close();
            fis.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
    System.out.println("Deserialization process ended");
    return objs;
}

public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new SaveRetrieveObjects();
        }
    });
}
}

class Item implements Serializable {
private static final long   serialVersionUID    = 1L;

private String                      id;
private String                      desc;
private double                      cost;
private int                             qty;
private boolean                     bool;
private Color                           color;

public Item() {
    id = "";
    desc = "";
    cost = 0;
    qty = 0;
    bool = false;
    color = new Color(0, 0, 0);
}

public Item(String id, String desc, double cost, int qty, boolean bool, Color color) {
    this.id = id;
    this.desc = desc;
    this.cost = cost;
    this.qty = qty;
    this.bool = bool;
    this.color = color;
}

public String getId() {
    return id;
}

public void setId(String itemID) {
    this.id = itemID;
}

public String getDesc() {
    return desc;
}

public void setDesc(String desc) {
    this.desc = desc;
}

public double getCost() {
    return cost;
}

public void setCost(double cost) {
    this.cost = cost;
}

public int getQty() {
    return qty;
}

public void setQty(int quantity) {
    this.qty = quantity;
}

public boolean isBool() {
    return bool;
}

public void setBool(boolean bool) {
    this.bool = bool;
}

public Color getColor() {
    return color;
}

public void setColor(Color color) {
    this.color = color;
}
}

答案 7 :(得分:0)

这是c

中的解决方案

#include<iostream>
using namespace std;
int main(){
    int n=15;
    int x=1;
    int j=1;
    for(int i=1;x<=n; )
    {

        if(!(j<=i))
        {
            cout<<endl;
            j=1;
            i++;
        }
        else
        {
            cout<<"*";
            x++;
            j++;
        }

    }
}

请随时询问

答案 8 :(得分:0)

从 JDK 11 开始,我们可以使用单循环打印任何基本模式,即使是单条语句。在 JDK 11 中,我们有一个名为 Stringrepeat 方法。

class Sample
{
 public static void main(String...arg)
 {
  int n = 5;
  
  System.out.println("\nPattern #1");
  for(int i=0;i<=n;i++)
   System.out.println(" ".repeat(n-i)+"* ".repeat(i));
 }
}

答案 9 :(得分:-1)

  

我想要优化。两个循环的时间复杂度将是O(n ^ 2),而对于仅一个循环,它将是O(n)。并且O(n)&lt;为O(n ^ 2)。

最佳解决方案是否没有循环?

System.out.println("     *\n    * *\n   * * *\n  * * * *\n* * * * *");

如果你真的想用一个循环来做这个,你可以使用逗号运算符和字符串format()replace()方法的强大功能:

int j = triangle_levels - 1; // triangle_levels is some int you can make 5, but this 
                             // is more generic
for(int i = 0; i < triangle_levels; j--, i++) {
    System.out.println("%" + j + "s", " ");
    System.out.println("%0" + (i+1) + "d", 0).replace("0", "* "));
}

这将允许您打印没有第二个循环的空格数,然后是*的模式。

您可以使用此类解决方案制作任意方向的三角形。

答案 10 :(得分:-1)

用单循环制作星形金字塔

for(i=0; i<a; i++)
{
    for(j=0; j<a-i-1; j++)
        printf(" ");
    for(j=0; j<2*i+1; j++)
        printf("*");
    printf("\n");
}