mathtools/cmd/partitions.go

95 lines
2.4 KiB
Go

/*
Copyright © 2025 filifa
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cmd
import (
"fmt"
"strconv"
"github.com/spf13/cobra"
"scm.dairydemon.net/filifa/mathtools/internal/lib"
)
var partitionsN string
var partitionsK string
func partitions(cmd *cobra.Command, args []string) {
n, err := strconv.Atoi(partitionsN)
if err != nil {
cobra.CheckErr("invalid input " + partitionsN)
}
var k int
if partitionsK == "" {
k = n
} else {
var err error
k, err = strconv.Atoi(partitionsK)
if err != nil {
cobra.CheckErr("invalid input " + partitionsK)
}
}
if n < 0 {
cobra.CheckErr("n must be nonnegative")
}
if k < 0 {
cobra.CheckErr("k must be nonnegative")
}
z := lib.Partitions(n, k)
fmt.Println(z)
}
// partitionsCmd represents the partitions command
var partitionsCmd = &cobra.Command{
Use: "partitions -n N -k N",
Short: "Compute the number of partitions of an integer",
Long: `Compute the number of partitions of an integer.
For example, 4 can be partitioned into
4
3+1
2+2
2+1+1
1+1+1+1
so p(n) = 5.
To compute the number of partitions into at most k parts, provide the -k flag.`,
Run: partitions,
}
func init() {
rootCmd.AddCommand(partitionsCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// partitionsCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// partitionsCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
partitionsCmd.Flags().StringVarP(&partitionsN, "number", "n", "", "number to compute partitions of")
partitionsCmd.MarkFlagRequired("number")
partitionsCmd.Flags().StringVarP(&partitionsK, "parts", "k", "", "maximum number of parts")
}