Generate string number for invitation code [duplicate] - go

This question already has answers here:
How to generate a random string of a fixed length in Go?
(18 answers)
Closed 4 years ago.
I would like to generate number for invitation code.
I get a number of digit for this and i need to generate a string number according to this digit.
Example :
For 3 i need to generate a string number beetween 111 and 999
for 4 1111 to 9999
for 2 11 to 99
etc...
What is the best way to do that ?
I have some idea like making two empty string filling them with 1 for the first one according to x, with 9 for the second one according to X.
Then converting them to int and make a random between these two number, but i don't thik it's the optimal way to do it.
package main
import (
"fmt"
"math/rand"
"strconv"
"time"
)
func randInt(min int, max int) int {
return min + rand.Intn(max-min)
}
func main() {
x := 3
first := ""
second := ""
i := 0
for i < x {
first = first + "1"
i = i + 1
}
i = 0
for i < x {
second = second + "9"
i = i + 1
}
rand.Seed(time.Now().UTC().UnixNano())
fmt.Println(first)
fmt.Println(second)
firstInt, _ := strconv.Atoi(first)
secondInt, _ := strconv.Atoi(second)
fmt.Println(randInt(firstInt, secondInt))
}
regards

You can do something like this:
package main
import (
"fmt"
"math/rand"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
var numbers = []rune("0123456789")
func GenerateNumberString(length int) string {
b := make([]rune, length)
for i := range b {
b[i] = numbers[rand.Intn(len(numbers))]
}
return string(b)
}
func main() {
fmt.Println(GenerateNumberString(2))
fmt.Println(GenerateNumberString(3))
fmt.Println(GenerateNumberString(4))
}
Try it here in the go playground.

Related

Golang gives different result everytime using map for AOC 2021 Day 6 problem

I've been trying to solve Advent of Code 2021 and in day 6, I am trying this solution but the result is different everytime. What seems to be the problem? Is there any memory leakage with map?
The input file can be found here
The details of the problem can be read here
For part one it was straight-forward looping over arrays but as the number of days increases, the population grows exponentially and the time complexity grows in similar manner.
with go version go1.19.3
I have tried this:
package main
import (
"fmt"
"os"
"strconv"
"strings"
)
func getInput() []int {
var parsedData []int
rawData, _ := os.ReadFile("input.txt")
data := strings.Split(string(rawData), ",")
for _, strNum := range data {
num, _ := strconv.Atoi(strNum)
parsedData = append(parsedData, num)
}
return parsedData
}
func main() {
data := getInput()
var total int64
// create a map t0 hold the number of fish with the same timer
fishWithSameTimer := make(map[int]int64)
for _, timer := range data {
if _, ok := fishWithSameTimer[timer]; ok {
fishWithSameTimer[timer] += 1
} else {
fishWithSameTimer[timer] = 1
}
}
const days int = 18
currDay := 1
for currDay <= days {
tempFishTimerData := make(map[int]int64)
for timer, numOfFishes := range fishWithSameTimer {
if timer == 0 {
tempFishTimerData[8] = numOfFishes
tempFishTimerData[6] = numOfFishes
}else{
tempFishTimerData[timer - 1] += numOfFishes
}
}
fishWithSameTimer = tempFishTimerData
fmt.Println("Day:", currDay, fishWithSameTimer)
currDay++
}
fmt.Println(fishWithSameTimer)
for _, num := range fishWithSameTimer {
total += num
}
fmt.Println(total)
}
Can anyone help?
I hope this piece of code does the work, please add the input file reading part and print the output slice as comma separated string. You can also validate if the input has all numbers between 0 and 8.
package main
import "fmt"
func refreshTimer(x int) (int, bool) {
if x == 0 {
return 6, true
} else {
return x - 1, false
}
}
func spawnFish(i []int) []int {
var parentIntTimer []int
var childIntTimer []int
for _, d := range i {
y, c := refreshTimer(d)
parentIntTimer = append(parentIntTimer, y)
if c {
childIntTimer = append(childIntTimer, 8)
}
}
return append(parentIntTimer, childIntTimer...)
}
func main() {
initialFishes := []int{3, 4, 3, 1, 2}
var spFishes []int
noOfDays := 18
for i := 1; i <= noOfDays; i++ {
spFishes = spawnFish(initialFishes)
initialFishes = spFishes
}
fmt.Println(spFishes)
}
Output: [6 0 6 4 5 6 0 1 1 2 6 0 1 1 1 2 2 3 3 4 6 7 8 8 8 8]

How to get the digits of int value in Golang

How can we get the digits of num := 658943 in Golang? I need to print each digit value from the given number (num) as integer instead of string.
package main
import "fmt"
func main() {
var (
num = 68932
digits []int
)
// do something with num, insert the result to digits
for _, val := range digits {
fmt.Println(val)
}
}
// expected output
// 6
// 8
// 9
// 3
// 2
You can use strconv
package main
import (
"fmt"
"strconv"
)
func main() {
var (
num = 68932
digits []int
)
s := strconv.Itoa(num)
for _, n := range s {
digits = append(digits, int(n-'0'))
}
for _, val := range digits {
fmt.Println(val)
}
}
https://go.dev/play/p/AHzwHPd7GJC

Is it Following Some algorithm or formula ..?

Perfect Number series
N:1 =1
N:2 =34
N:3 =122
N:4 =1111
N:5 =11123
N:6 so on...??
Here N is the number of digits in an Integer.
Number is called perfect if it follow these Rules:-
Number(without leading zeros) does not contain any other zeros.
The sum of squares of all digits of Number is a perfect square.
Example:-For N=2 34
34:- 3^2+4^2 :- 25 which is a perfect square
How to Compute Next smallest N Digit Number of This series is there any algorithm or formula following this series ..??
package main
import (
"fmt"
"math"
"strconv"
)
func main() {
all := 1
for all < 21 {
fmt.Println(keepdo(0,0,all))
all++
}
}
func keepdo(i int,sum int, ma int) (bool, int, string){
if i>= ma {
return square_check(sum), sum, ""
}
try := 1
for try < 10 {
sumc := sum +try*try
check, s,ss := keepdo(i+1,sumc, ma)
if check {
return check, s, strconv.Itoa(try) + ss
}
try++
}
return false, sum, ""
}
func square_check(a int) bool {
var int_root int = int(math.Sqrt(float64(a)))
return (int_root * int_root) == a
}
This is a very naive solution.
Should work. Pls do let me know if any improvement
https://play.golang.org/p/drVPaE0R71I

How to apply a function to an input of integers in Golang

For example, if the input was this
1 3 4 5
all separated by a space, I want to apply the function of squaring each individual number then adding it.
I just don't know how to apply the function to each number. All I can figure is that I have to put the numbers into a slice then apply the function to each of the numbers. I have looked everywhere and can't find out how to do this.
in Python I just do it like this and I already put the values into a list called "n".
#The list is pasted from the initial puzzle
n=[10, 10, 9, 8, 10, 10, 10]
# The list is first squared
b = (list(map(lambda x:x**2,n)))
b becomes the new list where the function is done to each number.
You can do it like this if your integers are actually a string separated by spaces.
package main
import "fmt"
import "strings"
import "strconv"
func main() {
numbers := "1 3 4 5"
var n []int
for _, v := range strings.Fields(numbers) {
i, err := strconv.Atoi(v)
if err != nil {
fmt.Println(err.Error())
break
}
n = append(n, i*i)
}
fmt.Println(n)
}
https://play.golang.org/p/JcivNd29Gzg
package main
import (
"strconv"
"fmt"
"strings"
)
func main() {
stringwithnumbers := "1 2 3 4 5"
numberarray := strings.Split(stringwithnumbers, " ")
stringwithnumbers = ""
for _, number := range numberarray {
numbernew,err := strconv.Atoi(number)
if err != nil{
return
}
numbernew = numbernew * 2
stringwithnumbers += strconv.Itoa(numbernew)
stringwithnumbers += " "
}
stringwithnumbers = strings.Trim(stringwithnumbers, " ")
//You can check the result...
fmt.Print(stringwithnumbers)
}
You can check the code and your changes here:
https://play.golang.org/

How to use Math/Big in Go Lang

I am trying to create a factorial program, but when the numbers get too big the answer becomes wrong. Here is my code. I am new to math/big and cannot figure out how to correctly implement it into the program. Any help is appreciated. Thanks.
package main
import (
"fmt"
"os"
"strconv"
"math/big"
)
func main() {
fmt.Print("What integer would you like to to find a total factorial for?")
var userinput string
var userint int
fmt.Scan(&userinput)
userint, err := strconv.Atoi(userinput)
if err != nil {
fmt.Println("ERROR: Please input an integer")
os.Exit(2)
}
var efactorial int = 1
var ofactorial int = 1
var tfactorial int
var counter int
for counter = 2; counter <= userint; counter = counter + 2 {
efactorial = efactorial * counter
}
for counter = 1; counter <= userint; counter = counter + 2 {
ofactorial = ofactorial * counter
}
fmt.Println("Even factorial is: ", efactorial)
fmt.Println("Odd factorial is: ", ofactorial)
tfactorial = efactorial + ofactorial
fmt.Println("The Total factorial is: ", tfactorial)
}
You can use big.Int.MulRange to find the product of a range of integers. This is ideal for computing factorials. Here's a complete example that computes 50!
package main
import (
"fmt"
"math/big"
)
func main() {
var f big.Int
f.MulRange(1, 50)
fmt.Println(&f)
}
The output:
30414093201713378043612608166064768844377641568960512000000000000
you want ofactorial and tfactorial to be of type big.Int
ofactorial := big.NewInt(1)
tfactorial := big.NewInt(0)
Then you will want to use the methods from the big package for multiplying Ints found here
your for loop will look something like
for counter = 2; counter <= userint; counter = counter + 2 {
efactorial.Mul(efactorial * big.NewInt(counter))
}

Resources