Skip to content

refactor: FloydTriangle #5367

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Aug 23, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 17 additions & 11 deletions src/main/java/com/thealgorithms/others/FloydTriangle.java
Original file line number Diff line number Diff line change
@@ -1,22 +1,28 @@
package com.thealgorithms.others;

import java.util.Scanner;

final class FloydTriangle {
private FloydTriangle() {
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows which you want in your Floyd Triangle: ");
int r = sc.nextInt();
int n = 0;
sc.close();
for (int i = 0; i < r; i++) {
/**
* Generates a Floyd Triangle with the specified number of rows.
*
* @param rows The number of rows in the triangle.
* @return A string representing the Floyd Triangle.
*/
public static String generateFloydTriangle(int rows) {
StringBuilder triangle = new StringBuilder();
int number = 1;

for (int i = 0; i < rows; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(++n + " ");
triangle.append(number++).append(" ");
}
if (i < rows - 1) {
triangle.append("\n");
}
System.out.println();
}

return triangle.toString();
}
}
36 changes: 36 additions & 0 deletions src/test/java/com/thealgorithms/others/FloydTriangleTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.thealgorithms.others;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

public class FloydTriangleTest {

@Test
public void testGenerateFloydTriangleWithValidInput() {
String expectedOutput = "1 \n2 3 \n4 5 6 ";
assertEquals(expectedOutput, FloydTriangle.generateFloydTriangle(3));
}

@Test
public void testGenerateFloydTriangleWithOneRow() {
String expectedOutput = "1 ";
assertEquals(expectedOutput, FloydTriangle.generateFloydTriangle(1));
}

@Test
public void testGenerateFloydTriangleWithZeroRows() {
assertEquals("", FloydTriangle.generateFloydTriangle(0));
}

@Test
public void testGenerateFloydTriangleWithNegativeRows() {
assertEquals("", FloydTriangle.generateFloydTriangle(-3));
}

@Test
public void testGenerateFloydTriangleWithMultipleRows() {
String expectedOutput = "1 \n2 3 \n4 5 6 \n7 8 9 10 \n11 12 13 14 15 ";
assertEquals(expectedOutput, FloydTriangle.generateFloydTriangle(5));
}
}