Commits

Arkadi Shishlov  committed eb06893 Draft

Diamond

  • Participants

Comments (0)

Files changed (2)

File src/Diamond.java

+
+public class Diamond {
+	public String createDiamond(int size) {
+		if (size == 1) {
+			return "+";
+		}
+		StringBuilder sb = new StringBuilder();
+		createHead(sb, size);
+		sb.append("\n");
+		for (int i = 0; i < size - 2; i++) {
+			createMid(sb, size, i);
+		}
+		for (int i = size - 2; i >= 0; i--) {
+			createMid(sb, size, i);
+		}
+		createHead(sb, size);
+		return sb.toString();
+	}
+	
+	public void createMid(StringBuilder sb, int size, int i) {
+		addSpaces(sb, size - i - 2);
+		sb.append('+');
+		addSpaces(sb, i * 2 + 1);
+		sb.append("+\n");
+	}
+
+	private void createHead(StringBuilder sb, int size) {
+		addSpaces(sb, size - 1);
+		sb.append("+");
+	}
+	
+	private void addSpaces(StringBuilder sb, int count) {
+		for(int i = 0; i < count; i++) {
+			sb.append(' ');
+		}
+	}
+
+}

File src/DiamondTest.java

+import static org.junit.Assert.*;
+
+import org.junit.Before;
+import org.junit.Test;
+
+
+public class DiamondTest {
+
+	private Diamond diamond;
+
+	@Before
+	public void setUp() {
+		diamond = new Diamond();
+	}
+
+	private void p(String str) { System.out.println(str+"\n");}
+
+	@Test
+	public void test1() {
+		p(diamond.createDiamond(1));
+		assertEquals("+", diamond.createDiamond(1));
+	}
+	
+	@Test
+	public void test2() {
+		p(diamond.createDiamond(2));
+		assertEquals(" +\n" +
+                     "+ +\n" +
+                     " +", diamond.createDiamond(2));
+	}
+	
+	@Test
+	public void test3() {
+		p(diamond.createDiamond(3));
+		assertEquals("  +\n" +
+                     " + +\n" +
+                     "+   +\n" +
+                     " + +\n" +
+                     "  +", diamond.createDiamond(3));
+	}
+	
+	@Test
+	public void test4() {
+		p(diamond.createDiamond(4));
+		assertEquals("   +\n" +
+                     "  + +\n" +
+                     " +   +\n" +
+                     "+     +\n" +
+                     " +   +\n" +
+                     "  + +\n" +
+                     "   +", diamond.createDiamond(4));
+	}
+
+}