DEV Community

Discussion on: Daily Challenge #2 - String Diamond

Collapse
 
kunde21 profile image
Chad Kunde

Go (with bonus diamond of diamonds) playground link


func diamond(center int) (string, error) {
    if (center & 1) == 0 {
        return "", errors.New("center row must be an odd number")
    }
    return strings.Join(makeDiamond(center), "\n"), nil
}

func diamondOfDiamonds(center int) (string, error) {
    if (center & 1) == 0 {
        return "", errors.New("center row must be an odd number")
    }
    dmd := makeDiamond(center)
    outBuf := make([]string, center)
    row := strings.Repeat(" ", center)
    for i := 0; i <= center/2; i++ {
        rowBuf := make([]string, center)
        for j := range rowBuf {
            rowBuf[j] = strings.Repeat(row, center/2-i) + strings.Repeat(dmd[j], 2*i+1) + strings.Repeat(row, center/2-i)
        }
        outBuf[i], outBuf[center-i-1] = strings.Join(rowBuf, "\n"), strings.Join(rowBuf, "\n")
    }
    return strings.Join(outBuf, "\n"), nil
}

func makeDiamond(center int) []string {
    outBuf := make([]string, center)
    row := bytes.Repeat([]byte{' '}, center)
    for l, r := (center / 2), (center / 2); l >= 0; l, r = l-1, r+1 {
        row[l], row[r] = '*', '*'
        outBuf[center/2-l], outBuf[center/2+l] = string(row), string(row)
    }
    return outBuf
}
Collapse
 
coreyja profile image
Corey Alexander

Woah that's cool! I wanted to see what your diamond of diamonds looked like!

Thought I'd paste in the medium sized one, and let people go to the playground for the big one!

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