Extract digits at a certain position in a number - go

number := 111555
How do I get, for instance the first 3 digits (111) and the last 2 digits (55)?

Try this:
number := 111555
fmt.Println(number % 100) // last 2 digits (55)
// first 3 digits (111)
for ; number > 999; number /= 10 {
}
fmt.Println(number) // 111
Try this:
number := 111555
slice := strconv.Itoa(number)
fmt.Println(slice[:3]) // first 3 digits (111)
fmt.Println(slice[len(slice)-2:]) // and the last 2 digits (55)
The first 3 digits (111):
strconv.Itoa(number)[:3]
and the last 2 digits (55):
number % 100
or:
slice := strconv.Itoa(number)
slice[len(slice)-2:]
try this:
number := 111555
// and the last 2 digits (55)
l2d := number % 100
fmt.Println(l2d)
// first 3 digits (111)
f3d := strconv.Itoa(number)[:3]
// i, e := strconv.Atoi(f3d)
fmt.Println(f3d)
Another way, try this:
package main
import (
"fmt"
"math"
)
func main() {
number := 111555
// last 2 digits (55)
l2d := number % 100
fmt.Println(l2d)
// first 3 digits (111)
remainingDigits := numberOfDigits(number) - 3
f3d := number / int(math.Pow10(remainingDigits))
fmt.Println(f3d)
}
func numberOfDigits(n int) (digits int) {
for ; n != 0; n /= 10 {
digits++
}
return
}
another way:
package main
import (
"fmt"
)
func main() {
number := 111555
// and the last 2 digits (55)
l2d := number % 100
fmt.Println(l2d)
// first 3 digits (111)
fmt.Println(leftDigits(number, 3))
}
func leftDigits(number, n int) int {
digits := make([]byte, 20)
i := -1
for number != 0 {
i++
digits[i] = byte(number % 10)
number /= 10
}
r := 0
for ; n != 0; n-- {
r = r * 10
r += int(digits[i])
i--
}
return r
}
output:
55
111

By using simple arithmetic:
func d(num int) (firstThree int, lastTwo int) {
firstThree = num / 1000
lastTwo = num % 100
return
}

This function gives the digit at a specific place:
func digit(num, place int) int {
r := num % int(math.Pow(10, float64(place)))
return r / int(math.Pow(10, float64(place-1)))
}
For example digit(1234567890, 2) (second number from the right side) gives 9 and digit(1234567890, 6) gives 5 (sixth number from the right side).

you cant turn int into slice of digits in golang
the trick is u have to turn it into string, do the composition, then fallback to int seperatly
https://play.golang.org/p/eZn1onG7T6

If the number is not too large, there is a simple way.
package main
import (
"fmt"
"log"
"strconv"
)
func main() {
num := 111555
s := strconv.Itoa(num)
pos := 3 // first 3 digits, others
part1 := s[:pos]
part2 := s[pos:]
num1, err := strconv.Atoi(part1)
if err != nil {
log.Fatal(err)
}
num2, err := strconv.Atoi(part2)
if err != nil {
log.Fatal(err)
}
fmt.Println(num1, num2)
}

str := strconv.Itoa(111555)
fmt.Println(str[len(str)-2:]) //trailing 2 digits
fmt.Println(str[:3]) //first 3 digits

For example,
package main
import (
"fmt"
"strconv"
)
func strDigits(n, digits int) (string, int) {
s := strconv.Itoa(n)
if s[0] == '-' {
s = s[1:]
}
if digits > len(s) {
digits = len(s)
}
if digits < 0 {
digits = 0
}
return s, digits
}
func firstDigits(n, digits int) string {
s, d := strDigits(n, digits)
return s[:d]
}
func lastDigits(n, digits int) string {
s, d := strDigits(n, digits)
return s[len(s)-d:]
}
func main() {
number := 111555
fmt.Println(firstDigits(number, 3))
fmt.Println(lastDigits(number, 2))
}
Playground: https://play.golang.org/p/oYwZ5HFndt
Output:
111
55

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

How to find sum of integers using recursion(without loops) in Golang?

Program should ask values "number of numbers" and "numbers" for each "number of inputs", answers are sum of squares of these numbers. My code works but it shows answers in wrong order, how to make it work properly? Outputs should be shown after all inputs.
I think its easier to understand this program by reading inputs and outputs:
Enter the number of inputs // output
2 // input
Enter the number of numbers // output
2 // input
Enter the numbers // output
1 2 // input (second ans)
Enter the number of numbers // output
2 // input
Enter the numbers
2 3 // input (first ans)
ans = 13 // ans = 2^2 + 3^2
ans = 5 () // ans = 1^2 + 2^2
MyCode:
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Println(`Enter the number of inputs`)
n, _ := reader.ReadString('\n')
n = strings.TrimRight(n, "\r\n")
test_cases, err := strconv.Atoi(n)
if err != nil {
fmt.Println(err)
}
process_test_case(test_cases, reader)
}
func process_test_case(test_cases int, reader *bufio.Reader) {
fmt.Println(`Enter the number of numbers`)
_, _ = reader.ReadString('\n')
fmt.Println(`Enter the numbers`)
input, _ := reader.ReadString('\n')
input = strings.TrimRight(input, "\r\n")
arr := strings.Split(input, " ")
test_cases -= 1
if test_cases != 0 {
process_test_case(test_cases, reader)
}
fmt.Println("ans = ", process_array(arr, 0))
}
func process_array(arr []string, result int) int {
num, _ := strconv.Atoi(arr[0])
if len(arr) > 1 {
next := arr[1:]
if num < 0 {
num = 0
}
result = num*num + process_array(next, result)
return result
} else {
if num >= 0 {
return num * num
}
return 0
}
}
How to find sum of integers using recursion (without loops) in Go?
The program should ask "number of numbers" and "numbers" for each "number of inputs", answers are sum of squares of these numbers.
Here is an answer to the question, a recursive solution in Go:
$ go run sumsq.go
Enter the number of inputs:
2
Enter the number of numbers:
2
Enter the numbers:
1
2
Enter the number of numbers:
2
Enter the numbers:
2
3
Sum of Squares:
5
13
$
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func readInt(r *bufio.Reader) int {
line, err := r.ReadString('\n')
line = strings.TrimSpace(line)
if err != nil {
if len(line) == 0 {
return 0
}
}
i, err := strconv.Atoi(line)
if err != nil {
return 0
}
return i
}
func nSquares(n int, r *bufio.Reader) int {
if n == 0 {
return 0
}
i := readInt(r)
return i*i + nSquares(n-1, r)
}
func nNumbers(n int, r *bufio.Reader, sums *[]int) int {
if n == 0 {
return 0
}
fmt.Println("\nEnter the number of numbers: ")
i := readInt(r)
fmt.Println("Enter the numbers: ")
*sums = append(*sums, nSquares(i, r))
return nNumbers(n-1, r, sums)
}
func nInputs(r *bufio.Reader) []int {
fmt.Println("Enter the number of inputs: ")
i := readInt(r)
sums := make([]int, 0, i)
nNumbers(i, r, &sums)
return sums
}
func sumSqrs(sums []int) {
if len(sums) == 0 {
return
}
fmt.Println(sums[0])
sumSqrs(sums[1:])
}
func main() {
r := bufio.NewReader(os.Stdin)
fmt.Println()
sums := nInputs(r)
fmt.Println("\nSum of Squares:")
sumSqrs(sums)
fmt.Println()
}
I have created a sample code for your scenario. You can modify it by using bufio.NewReader(os.Stdin)
func process_array(arr []string) int {
res := 0
for _, v := range arr {
num, err := strconv.Atoi(v)
if err != nil {
panic(err)
}
fmt.Println("num :", num)
res += num * num
}
return res
}
func process_test_case() int {
fmt.Println(`Enter the number of numbers`)
num := 2
fmt.Println("number of numbers :", num)
fmt.Println(`Enter the numbers`)
input := "1 2"
fmt.Println("the numbers :", input)
arr := strings.Split(input, " ")
res := process_array(arr)
return res
}
func main() {
fmt.Println(`Enter the number of inputs`)
test_cases := 1
fmt.Println("number of inputs :", test_cases)
for test_cases >= 1 {
res := process_test_case()
fmt.Println(res)
test_cases -= 1
}
}
You can run it here : https://go.dev/play/p/zGkAln2ghZp
OR
As commented by #phonaputer you can change the sequence. Return the slice and print it from the end.
I think this code answer your title of the question:
package main
import "fmt"
func SumValues(x int, y ...int) (sum int) {
q := len(y) - 1
sum = y[q - x]
if x < q {
sum += SumValues(x + 1, y...)
}
return sum
}
func main() {
sum := SumValues(0,1,2,3,4,5)
fmt.Println("Sum is:", sum)
}

Golang Calculator -- Can't divide by 0 error

I'm actually in a bit of a trouble...
I have a calculator, but when I want to divide nubers with them, I have a panic err saying that you can't divide by 0.
Well, I know that in maths we can't divide by 0, but I don't put 0 in my ints.
Any idea of the problem ?
Here is the code :
package main
import (
"fmt"
"os"
"strconv"
)
func mult(nums ...int) {
result := 0
total := 1
for _, num := range nums {
result = total * num
total = result
}
fmt.Println(result)
}
func add(nums ...int){
result := 0
total := 0
for _, num := range nums {
result = total + num
total = result
}
fmt.Println(result)
}
func sub(nums ...int){
result := 0
total := 0
for _, num := range nums {
result = num - total
total = result
}
fmt.Println(result)
}
func div(nums ...int){
result := 1
total := 1
for _, num := range nums {
result = num / total
total = result
}
fmt.Println(result)
}
func main() {
var d [] int
var args= os.Args[1:]
nums := make([]int, len(args))
for i := 0; i < len(args); i++ {
nums[i], _ = strconv.Atoi(args[i]);
strconv.Atoi(args[i])
d = append(d, nums[i])
}
num := d
if os.Args[1] == "*"{
mult(num...)
} else if os.Args[1] == "+"{
add(num...)
} else if os.Args[1] == "-"{
sub(num...)
} else if os.Args[1] == "/"{
div(num...)
} else {
fmt.Println("Well well well, you didn't entered a right operand ! Try with +, -, /, or * between double quotes")
}
}
The command I want to run this go code is :
go run calc.exe / 3 2 [Infinite args,...]
If your first parameter will always be a operator select, you can do something like that in your main func, you have a two problems in your main, you are ignoring the convertion error of a string to int and then this index of your array are setted with 0, and you are defining the array larger than you need because your first parameter it's not a number to your div func
nums := make([]int, len(args)-1)
for i := 0; i < len(args); i++ {
ret, errAtoi := strconv.Atoi(args[i])
if errAtoi != nil {
fmt.Println(errAtoi.Error())
} else {
nums[i-1] = ret
d = append(d, nums[i-1])
}
}

Too many results in a loop for Project Euler #145

I am trying to create a solution for Project Euler #145. I am writing in Go. When I run my program I get a result of 125. The expected result is 120. I have 2 different ways I have tried to write the code but both come up with the same answer. Any help pointing out my error would be appreciated.
Code option #1 using strings:
package main
import (
"fmt"
"strconv"
)
//checks to see if all the digits in the number are odd
func is_Odd(sum int) bool {
intString := strconv.Itoa(sum)
for x := len(intString); x > 0; x-- {
newString := intString[x-1]
if newString%2 == 0 {
return false
}
}
return true
}
//reverse the number passed
func reverse_int(value int) int {
intString := strconv.Itoa(value)
newString := ""
for x := len(intString); x > 0; x-- {
newString += string(intString[x-1])
}
newInt, err := strconv.Atoi(newString)
if err != nil {
fmt.Println("Error converting string to int")
}
return newInt
}
//adds 2 int's passed to it and returns an int
func add(x int, y int) int {
return x + y
}
func main() {
//functions test code
/*y := 35
x := reverse_int(y)
z := add(x,y)
fmt.Println(is_Odd(z))*/
counter := 1
for i := 1; i < 1000; i++ {
flipped := reverse_int(i)
sum := add(flipped, i)
oddCheck := is_Odd(sum)
if oddCheck {
fmt.Println(counter, ":", i, "+", flipped, "=", sum)
counter++
}
}
counter--
fmt.Println("total = ", counter)
}
Code option #2 using only ints:
package main
import (
"fmt"
)
var counter int
//breaks down an int number by number and checks to see if
//all the numbers in the int are odd
func is_Odd(n int) bool {
for n > 0 {
remainder := n % 10
if remainder%2 == 0 {
return false
}
n /= 10
}
return true
}
//adds 2 int's passed to it and returns an int
func add(x int, y int) int {
return x + y
}
//reverses the int passed to it and returns an int
func reverse_int(n int) int {
var new_int int
for n > 0 {
remainder := n % 10
new_int *= 10
new_int += remainder
n /= 10
}
return new_int
}
func main() {
//functions test code
/*y := 35
x := reverse_int(y)
z := add(x,y)
fmt.Println(is_Odd(z))*/
counter = 1
for i := 1; i < 1000; i++ {
flipped := reverse_int(i)
sum := add(flipped, i)
oddCheck := is_Odd(sum)
if oddCheck {
//fmt.Println(counter,":",i,"+",flipped,"=",sum)
counter++
}
}
counter--
fmt.Println(counter)
}
Leading zeroes are not allowed in either n or reverse(n) so in reverse(n int) int remove Leading zeroes like so:
remainder := n % 10
if first {
if remainder == 0 {
return 0
}
first = false
}
try this:
package main
import (
"fmt"
)
//breaks down an int number by number and checks to see if
//all the numbers in the int are odd
func isOdd(n int) bool {
if n <= 0 {
return false
}
for n > 0 {
remainder := n % 10
if remainder%2 == 0 {
return false
}
n /= 10
}
return true
}
//adds 2 int's passed to it and returns an int
func add(x int, y int) int {
return x + y
}
//reverses the int passed to it and returns an int
func reverse(n int) int {
first := true
t := 0
for n > 0 {
remainder := n % 10
if first {
if remainder == 0 {
return 0
}
first = false
}
t *= 10
t += remainder
n /= 10
}
return t
}
func main() {
counter := 0
for i := 0; i < 1000; i++ {
flipped := reverse(i)
if flipped == 0 {
continue
}
sum := add(flipped, i)
if isOdd(sum) {
counter++
//fmt.Println(counter, ":", i, "+", flipped, "=", sum)
}
}
fmt.Println(counter)
}
output:
120
You're ignoring this part of the criteria:
Leading zeroes are not allowed in either n or reverse(n).
Five of the numbers you count as reversible end in 0. (That means their reverse has a leading zero.) Stop counting those as reversible and you're done.
Some positive integers n have the property that the sum [ n +
reverse(n) ] consists entirely of odd (decimal) digits. For instance,
36 + 63 = 99 and 409 + 904 = 1313. We will call such numbers
reversible; so 36, 63, 409, and 904 are reversible. Leading zeroes are
not allowed in either n or reverse(n).
All digits of the sum must all be odd.
Try this one: https://play.golang.org/p/aUlvKrb9SB

Resources