If else function with identical symbols - go

I have this:
func main() {
n1 := new(big.Int)
n1.SetString("1000000", 10)
n2 := new(big.Int)
n2.SetString("1000009", 10)
one := big.NewInt(1)
for i := n1; i.Cmp(n2) < 0; i.Add(i, one) {
//fmt.Println(i)
}
}
How do I make when n1 := 100000 <-- got 5 identical symbols or 122222 and etc just to keep count till there is only 4 identical symbols (example 100001) ... then go to next line.
I know I need to use ... if ... else ... but I have no idea how to check if there is only 4 identical symbols in result of n1
Any idea?

I don't know if this is exactly what you mean or not, but I can suggest you create a function which accepts a *big.Int and a specific number of identical symbols, and returns weather or not there's a character that is repeated n times:
func containsNIdenticalSymbols(n int, i *big.Int) bool {
counter := make(map[rune]int)
for _, char := range i.String() {
counter[char] ++
}
hasNumIdenticalSymbols := false
for _, count := range counter {
if count == n { hasNumIdenticalSymbols = true; break }
}
return hasNumIdenticalSymbols
}
And just && it with the i.Cmp(n2) < 0 condition:
numIdenticalSymbols := 4
// as you said "keep count till there is only 4 identical symbols"
for i := n1; i.Cmp(n2) < 0 && !containsNIdenticalSymbols(numIdenticalSymbols, i) ; i.Add(i, one) { ... }

Related

Why is it wrong to use if here,in golang,remove-duplicates-from-sorted-array

I am a beginner and hope to get your help
it is remove-duplicates-from-sorted-array
func remove(nums []int)int{
i,j:= 0,0
//Why is it wrong to use if here?
// if j< len(nums)
for j < len(nums){
if i==0 || nums[i-1]!= nums[j]{
nums[i] = nums[j]
i++
j++
}else{
j++
}
}
return i
}
func main(){
nums := []int{1,2,2,3,5,5}
result := remove(nums)
fmt.Println(result)
}
please help me
On short notice, here's what I have:
func remove(nums []int) int {
temp := map[int]string{}
for _, n := range nums {
temp[n] = "exist"
}
result := []int{}
for n, _ := range temp {
result = append(result, n)
}
return result
}
And the output is:
[1 2 3 5]
Iterate through the slice and put into a map.
Iterate through the map and put into a slice.
Return the new slice.
It is a sorted list of numbers, so you can store the last number added into the results list and skip adding into the result list if the next number is the same.
func remove(nums []int) []int {
if len(nums) == 0 {
return []int{}
}
result := []int{nums[0]}
current := nums[0]
for _, num := range nums {
if current == num {
continue
}
result = append(num)
current = num
}
return result
}
If you are asking about why is it wrong to use for j < len(nums), its not wrong, but using for _, num := range nums would make your life easier as you don't have to keep track of where you are in the array.

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

Generate combinations from a given range

I'm trying to create a program capable to generate combinations from a given range.
I started editing this code below that generates combinations:
package main
import "fmt"
func nextPassword(n int, c string) func() string {
r := []rune(c)
p := make([]rune, n)
x := make([]int, len(p))
return func() string {
p := p[:len(x)]
for i, xi := range x {
p[i] = r[xi]
}
for i := len(x) - 1; i >= 0; i-- {
x[i]++
if x[i] < len(r) {
break
}
x[i] = 0
if i <= 0 {
x = x[0:0]
break
}
}
return string(p)
}
}
func main() {
np := nextPassword(2, "ABCDE")
for {
pwd := np()
if len(pwd) == 0 {
break
}
fmt.Println(pwd)
}
}
This is the Output of the code:
AA
AB
AC
AD
AE
BA
BB
BC
BD
BE
CA
CB
CC
CD
CE
DA
DB
DC
DD
DE
EA
EB
EC
ED
EE
And this is the code I edited:
package main
import "fmt"
const (
Min = 5
Max = 10
)
func nextPassword(n int, c string) func() string {
r := []rune(c)
p := make([]rune, n)
x := make([]int, len(p))
return func() string {
p := p[:len(x)]
for i, xi := range x {
p[i] = r[xi]
}
for i := len(x) - 1; i >= 0; i-- {
x[i]++
if x[i] < len(r) {
break
}
x[i] = 0
if i <= 0 {
x = x[0:0]
break
}
}
return string(p)
}
}
func main() {
cont := 0
np := nextPassword(2, "ABCDE")
for {
pwd := np()
if len(pwd) == 0 {
break
}
if cont >= Min && cont <= Max{
fmt.Println(pwd)
} else if cont > Max{
break
}
cont += 1
}
}
Output:
BA
BB
BC
BD
BE
CA
My code works, but if I increase the length of the combination and my range starts from the middle, the program will generate even the combinations that I don't want (and of course that will take a lot of time).
How can I solve this problem?
I really didn't like how nextPassword was written, so I made a variation. Rather than starting at 0 and repeatedly returning the next value, this one takes an integer and converts it to the corresponding "password." E.g. toPassword(0, 2, []rune("ABCDE")) is AA, and toPassword(5, ...) is BA.
From there, it's easy to loop over whatever range you want. But I also wrote a nextPassword wrapper around it that behaves similarly to the one in the original code. This one uses toPassword under the cover and takes a starting n.
Runnable version here: https://play.golang.org/p/fBo6mx4Mji
Code below:
package main
import (
"fmt"
)
func toPassword(n, length int, alphabet []rune) string {
base := len(alphabet)
// This will be our output
result := make([]rune, length)
// Start filling from the right
i := length - 1
// This is essentially a conversion to base-b, where b is
// the number of possible letters (5 in the case of "ABCDE")
for n > 0 {
// Filling from the right, put the right digit mod b
result[i] = alphabet[n%base]
// Divide the number by the base so we're ready for
// the next digit
n /= base
// Move to the left
i -= 1
}
// Fill anything that's left with "zeros" (first letter of
// the alphabet)
for i >= 0 {
result[i] = alphabet[0]
i -= 1
}
return string(result)
}
// Convenience function that just returns successive values from
// toPassword starting at start
func nextPassword(start, length int, alphabet []rune) func() string {
n := start
return func() string {
result := toPassword(n, length, alphabet)
n += 1
return result
}
}
func main() {
for i := 5; i < 11; i++ {
fmt.Println(toPassword(i, 2, []rune("ABCDE")))
} // BA, BB, BC, BD, BE, CA
// Now do the same thing using nextPassword
np := nextPassword(5, 2, []rune("ABCDE"))
for i := 0; i < 6; i++ {
fmt.Println(np())
} // BA, BB, BC, BD, BE, CA
}

Why this correct code in Golang is considered wrong at HackerRank?

I solved "Compare the Triplets" in Golang using the following code, but its saying that the answer is wrong.
When I run the code in my local environment it shows the desired results.
(here is the link to the problem at HackerRank)
Following is the code.
package main
import "fmt"
func main() {
a, b := ReadArrays()
sa, sb := CompareIt(a, b)
fmt.Printf("A: %d, B: %d\n", sa, sb)
}
func CompareIt(a, b []int) (int, int) {
var scoreA int
var scoreB int
for i := 0; i < 3; i++ {
if a[i] > b[i] {
scoreA += 1
} else if b[i] > a[i] {
scoreB += 1
}
}
return scoreA, scoreB
}
func ReadArrays() ([]int, []int) {
a := make([]int, 3)
fmt.Println("Please enter the first 3 digits separated by space or comma")
for i := range a {
fmt.Scanf("%d", &a[i])
}
b := make([]int, 3)
fmt.Println("Please enter the second 3 digits separated by space or comma")
for i := range b {
fmt.Scanf("%d", &b[i])
}
return a, b
}
When I run this code in my local environment, its asks me at the terminal to enter the first 3 digits, then its asks me to to insert the other 3 digits, then the code compare it and give the scores to A and B as required in the challenge.
Your output does not match the expected output:
Your Output (stdout)
Please enter the first 3 digits separated by space or comma
Please enter the second 3 digits separated by space or comma
A: 1, B: 1
Expected Output
1 1
You are printing way more than they asked for. You are also making this program for a computer to run not a person. You don't need to have a text prompt.
Remove the excess printing:
package main
import "fmt"
func main() {
a, b := ReadArrays()
sa, sb := CompareIt(a, b)
fmt.Printf("%d %d", sa, sb)
}
func CompareIt(a, b []int) (int, int) {
var scoreA int
var scoreB int
for i := 0; i < 3; i++ {
if a[i] > b[i] {
scoreA += 1
} else if b[i] > a[i] {
scoreB += 1
}
}
return scoreA, scoreB
}
func ReadArrays() ([]int, []int) {
a := make([]int, 3)
for i := range a {
fmt.Scanf("%d", &a[i])
}
b := make([]int, 3)
for i := range b {
fmt.Scanf("%d", &b[i])
}
return a, b
}

Resources