How to properly use .dropLast()

Viewed 89

So this question is a just a smaller portion of a bigger problem. But it all boils down to my misunderstanding of this function..

Given my function:

    func diamond(_ size: Int) -> String {
         var diamonds = ""
         for diamond in 0...size {
             if diamond % 2 == 1 || diamond == 1 {
                  diamonds.append(String(repeating: "*", count: diamond))
                  diamonds.append("\n")
    }
  }
    print(diamonds)
    print("This should print one row less but doesn't\n", diamonds.dropLast())
    diamonds = diamonds + diamonds.dropLast().reversed()
    return diamonds
}

diamond(5)

The expected output for diamond(5) should be =

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

But current output is:

*
***
*****
***** //<-- Doubled
***
*

How am I misusing dropLast? Thanks

1 Answers

The problem is here diamonds.append("\n") You are adding a new line at the last and you are dropping last. It means you are dropping "\n" instead of *.

Also, you have to drop the character for size size . The reason is while you printing you have already printing and covering ***** max size starts at the first time so no need this in reversed()

So, your final function is

func diamond(_ size: Int) -> String {
    var diamonds = ""
    for diamond in 0...size {
        if diamond % 2 == 1 || diamond == 1 {
            if diamond != 1 {
                diamonds.append("\n")
            }
            diamonds.append(String(repeating: "*", count: diamond))
        }
    }
    diamonds = diamonds + diamonds.dropLast(size).reversed()
    return diamonds
}

Test:

// Inputs
print("============diamond(3)================")
print(diamond(3))
print("============diamond(5)================")
print(diamond(5))
print("============diamond(7)================")
print(diamond(7))


// Outputs
============diamond(3)================
    *
    ***
    *
    ============diamond(5)================
    *
    ***
    *****
    ***
    *
    ============diamond(7)================
    *
    ***
    *****
    *******
    *****
    ***
    *
Related