File tree 2 files changed +53
-11
lines changed
main/java/com/thealgorithms/others
test/java/com/thealgorithms/others 2 files changed +53
-11
lines changed Original file line number Diff line number Diff line change 1
1
package com .thealgorithms .others ;
2
2
3
- import java .util .Scanner ;
4
-
5
3
final class FloydTriangle {
6
4
private FloydTriangle () {
7
5
}
8
6
9
- public static void main (String [] args ) {
10
- Scanner sc = new Scanner (System .in );
11
- System .out .println ("Enter the number of rows which you want in your Floyd Triangle: " );
12
- int r = sc .nextInt ();
13
- int n = 0 ;
14
- sc .close ();
15
- for (int i = 0 ; i < r ; i ++) {
7
+ /**
8
+ * Generates a Floyd Triangle with the specified number of rows.
9
+ *
10
+ * @param rows The number of rows in the triangle.
11
+ * @return A string representing the Floyd Triangle.
12
+ */
13
+ public static String generateFloydTriangle (int rows ) {
14
+ StringBuilder triangle = new StringBuilder ();
15
+ int number = 1 ;
16
+
17
+ for (int i = 0 ; i < rows ; i ++) {
16
18
for (int j = 0 ; j <= i ; j ++) {
17
- System .out .print (++n + " " );
19
+ triangle .append (number ++).append (" " );
20
+ }
21
+ if (i < rows - 1 ) {
22
+ triangle .append ("\n " );
18
23
}
19
- System .out .println ();
20
24
}
25
+
26
+ return triangle .toString ();
21
27
}
22
28
}
Original file line number Diff line number Diff line change
1
+ package com .thealgorithms .others ;
2
+
3
+ import org .junit .jupiter .api .Test ;
4
+
5
+ import static org .junit .jupiter .api .Assertions .assertEquals ;
6
+
7
+ public class FloydTriangleTest {
8
+
9
+ @ Test
10
+ public void testGenerateFloydTriangleWithValidInput () {
11
+ String expectedOutput = "1 \n 2 3 \n 4 5 6 " ;
12
+ assertEquals (expectedOutput , FloydTriangle .generateFloydTriangle (3 ));
13
+ }
14
+
15
+ @ Test
16
+ public void testGenerateFloydTriangleWithOneRow () {
17
+ String expectedOutput = "1 " ;
18
+ assertEquals (expectedOutput , FloydTriangle .generateFloydTriangle (1 ));
19
+ }
20
+
21
+ @ Test
22
+ public void testGenerateFloydTriangleWithZeroRows () {
23
+ assertEquals ("" , FloydTriangle .generateFloydTriangle (0 ));
24
+ }
25
+
26
+ @ Test
27
+ public void testGenerateFloydTriangleWithNegativeRows () {
28
+ assertEquals ("" , FloydTriangle .generateFloydTriangle (-3 ));
29
+ }
30
+
31
+ @ Test
32
+ public void testGenerateFloydTriangleWithMultipleRows () {
33
+ String expectedOutput = "1 \n 2 3 \n 4 5 6 \n 7 8 9 10 \n 11 12 13 14 15 " ;
34
+ assertEquals (expectedOutput , FloydTriangle .generateFloydTriangle (5 ));
35
+ }
36
+ }
You can’t perform that action at this time.
0 commit comments