new at using for loops - for-loop

All of the comments I received recommended this
package main
import (
"fmt"
)
func getWord(word string) string {
value:=[]rune(word)
for i := 0; i < len(word); i++ {
j := i + 1
fmt.Println("positions", i, j)
}
}
but when I want to subtract the values in the 2 positions
if value[i] - value[j] == 0 || value[i] - value[j] == 1 {
return value
} else {
return " "
}
these are the output instead
0 1
panic: runtime error: index out of range
goroutine 1 [running]:
https://play.golang.org/p/VAW6AhB1lev

Your second for loop runs through all iterations blocking the first until it completes.
This is why i prints 1 until j reaches 10
for (int i = 0; i < 10; i++){
printf("positions %d %d\n", i, i+1);
}

Related

panic: runtime error: index out of range [-1]

when I try to solve the leetcode problem of 118. Pascal's Triangle https://leetcode.com/problems/pascals-triangle/
it occured strange bug. Below the code can pass OJ.
func generate(numRows int) [][]int {
res := [][]int{}
for i := 0; i < numRows; i++ {
row := []int{}
for j := 0; j < i+1; j++ {
if j == 0 || j == i {
row = append(row, 1)
} else if i > 1 {
row = append(row, res[i-1][j-1] + res[i-1][j])
}
}
res = append(res, row)
}
return res
}
But the code I write like this and it occur panic, but the basic logic is same.
func generate(numRows int) [][]int {
res := [][]int{}
for i := 0; i < numRows; i++ {
row := []int{}
for j := 0; j < i+1; j++ {
if j == 0 || j == i {
row = append(row, 1)
}
if i > 1 {
row = append(row, res[i-1][j-1] + res[i-1][j])
}
}
res = append(res, row)
}
return res
}
I used if else if structure, it works fine, but I use 2 if condition judgment error.
In fact, their logic is the same, but why the error? I would be grateful if you could solve this problem. Good lcuk for you!
The problem is that you use 2 if conditions in the second version, while in the first version you have an if else.
but the basic logic is same
No, the logic is not the same. The result is that you try to do j-1 when j is 0.
If you have 2 if conditions like this, the program will enter both blocks individually if their respective condition is met.
if j == 0 || j == i {
row = append(row, 1)
}
// if j is 0 you still enter this block as long as i > 1
if i > 1 {
row = append(row, res[i-1][j-1] + res[i-1][j])
}
You could use continue to skip this section, if the first if is met.
if j == 0 || j == i {
row = append(row, 1)
// continue with the next iteration
continue
}
if i > 1 {
row = append(row, res[i-1][j-1] + res[i-1][j])
}
That said, using the if else in the first version of your code seems reasonable. I am not sure why you would want to change it.

Each character just after its consecutive occurrences

I'm solving this problem using Go:
https://www.geeksforgeeks.org/printing-frequency-of-each-character-just-after-its-consecutive-occurrences/
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
str := "GeeeEEKKKss"
strArr := strings.Split(str, "")
for i := 0; i < len(strArr); i++ {
count := 1
nxtIdx := i + 1
for nxtIdx < len(strArr) && strArr[nxtIdx] == strArr[i] {
i++
count++
}
fmt.Print(strArr[i], strconv.Itoa(count))
}
fmt.Println()
}
When I'm directly using i+1 in place of "nxtIdx" variable, I'm getting expected result
: G1e3E2K3s2
https://play.golang.org/p/wJBpNbIzlNd
But when I'm using "nxtIdx" variable, I'm getting unexpected result
: G1E4E1s4s1
https://play.golang.org/p/g8hejYTv2-0
Because you do not increment nxtIdx inside the loop that affects loop iteration.
nxtIdx := i + 1
for nxtIdx < len(strArr) && strArr[nxtIdx] == strArr[i] {
i++ // Here
count++
}
You should increment the nxtIdx also
nxtIdx := i + 1
for nxtIdx < len(strArr) && strArr[nxtIdx] == strArr[i] {
i++
nxtIdx++
count++
}

Writing Pascal's Triangle using big.Int int

I have some code for Pascal's Triangle using big.Int. How do I add the values? I get an error:
invalid operation:
PascalTriangle[r - 1][c - 1] + PascalTriangle[r - 1][c]
(operator + not defined on struct)
I am using a big.Int array so I cannot use Add from the big package.
func generatePascalTriangle(n int) [][]big.Int {
PascalTriangle := make([][]big.Int, n)
for i := range PascalTriangle {
PascalTriangle[i] = make([]big.Int, n)
}
var one big.Int
one.SetInt64(1)
for r := 0; r < n; r++ {
PascalTriangle[r][0] = one
PascalTriangle[r][r] = one
}
for r := 2; r < n; r++ {
for c := 1; c < r; c++ {
PascalTriangle[r][c] = PascalTriangle[r-1][c-1] + PascalTriangle[r-1][c]
}
}
return PascalTriangle
}
I am using big.Int array so cannot use "Add" from "big" package.
That claim is false. You can, and you should.
For example,
package main
import (
"fmt"
"math/big"
)
func generatePascalTriangle(n int) [][]big.Int {
PascalTriangle := make([][]big.Int, n)
for i := range PascalTriangle {
PascalTriangle[i] = make([]big.Int, n)
}
var one big.Int
one.SetInt64(1)
for r := 0; r < n; r++ {
PascalTriangle[r][0] = one
PascalTriangle[r][r] = one
}
for r := 2; r < n; r++ {
for c := 1; c < r; c++ {
// PascalTriangle[r][c] = PascalTriangle[r-1][c-1] + PascalTriangle[r-1][c]
PascalTriangle[r][c] = *PascalTriangle[r][c].Add(&PascalTriangle[r-1][c-1], &PascalTriangle[r-1][c])
}
}
return PascalTriangle
}
func main() {
t := generatePascalTriangle(7)
for i, r := range t {
for _, n := range r[:i+1] {
fmt.Print(n.String() + " ")
}
fmt.Println()
}
}
Playground: https://play.golang.org/p/KUGsjr8Mon5
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 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

Prime generator program SPOJ wrong answer

Problem Statement
Input
The input begins with the number t of test cases in a single line
(t<=10). In each of the next t lines there are two numbers m and n (1
<= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n,
one number per line, test cases separated by an empty line.
Example
Input:
2
1 10
3 5
Output:
2
3
5
7
3
5
My Problem
I have tried to write this problem with golang, at beginning I got time limit exceed error, then I solved it with finding the biggest n and only generate prime once. But now I got wrong answer error. Anyone can help to to find the bug? I can't figure it out. Thanks.
package main
import (
"fmt"
"math"
)
func main() {
var k, j, i, max_m, max_n, test_cases, kase int64
fmt.Scanln(&test_cases)
case_m, case_n := make([]int64, test_cases), make([]int64, test_cases)
EratosthenesArray := make(map[int64][]bool)
max_m = 0
max_n = 0
for i = 0; i < test_cases; i++ {
fmt.Scanf("%d %d", &case_m[i], &case_n[i])
if case_m[i] > case_n[i] {
case_m[i] = 0
case_n[i] = 0
}
if max_m < case_m[i] {
max_m = case_m[i]
}
if max_n < case_n[i] {
max_n = case_n[i]
}
length := case_n[i] - case_m[i] + 1
EratosthenesArray[i] = make([]bool, length)
}
if max_m <= max_n {
upperbound := int64(math.Sqrt(float64(max_n)))
UpperboundArray := make([]bool, upperbound+1)
for i = 2; i <= upperbound; i++ {
if !UpperboundArray[i] {
for k = i * i; k <= upperbound; k += i {
UpperboundArray[k] = true
}
for kase = 0; kase < test_cases; kase++ {
start := (case_m[kase] - i*i) / i
if case_m[kase]-i*i < 0 {
start = i
}
for k = start * i; k <= case_n[kase]; k += i {
if k >= case_m[kase] && k <= case_n[kase] {
EratosthenesArray[kase][k-case_m[kase]] = true
}
}
}
}
}
}
for i = 0; i < test_cases; i++ {
k = 0
for j = 0; j < case_n[i]-case_m[i]; j++ {
if !EratosthenesArray[i][j] {
ret := case_m[i] + j
if ret > 1 {
fmt.Println(ret)
}
}
}
fmt.Println()
}
}
according to the comments, the output for each prime number range is always have one line short, so here is the ACCEPTED solution
package main
import (
"fmt"
"math"
)
func main() {
var k, j, i, max_m, max_n, test_cases, kase int64
fmt.Scanln(&test_cases)
case_m, case_n := make([]int64, test_cases), make([]int64, test_cases)
EratosthenesArray := make(map[int64][]bool)
max_m = 0
max_n = 0
for i = 0; i < test_cases; i++ {
fmt.Scanf("%d %d", &case_m[i], &case_n[i])
if case_m[i] > case_n[i] {
case_m[i] = 0
case_n[i] = 0
}
if max_m < case_m[i] {
max_m = case_m[i]
}
if max_n < case_n[i] {
max_n = case_n[i]
}
length := case_n[i] - case_m[i] + 1
EratosthenesArray[i] = make([]bool, length)
}
if max_m <= max_n {
upperbound := int64(math.Sqrt(float64(max_n)))
UpperboundArray := make([]bool, upperbound+1)
for i = 2; i <= upperbound; i++ {
if !UpperboundArray[i] {
for k = i * i; k <= upperbound; k += i {
UpperboundArray[k] = true
}
for kase = 0; kase < test_cases; kase++ {
start := (case_m[kase] - i*i) / i
if case_m[kase]-i*i < 0 {
start = i
}
for k = start * i; k <= case_n[kase]; k += i {
if k >= case_m[kase] && k <= case_n[kase] {
EratosthenesArray[kase][k-case_m[kase]] = true
}
}
}
}
}
}
for i = 0; i < test_cases; i++ {
k = 0
for j = 0; j <= case_n[i]-case_m[i]; j++ {
if !EratosthenesArray[i][j] {
ret := case_m[i] + j
if ret > 1 {
fmt.Println(ret)
}
}
}
fmt.Println()
}
}
Note that I only changed one line from for j = 0; j < case_n[i]-case_m[i]; j++ { to for j = 0; j <= case_n[i]-case_m[i]; j++ {
And the execution time is about 1.08s, memory is about 772M (but seems the initial memory for golang in spoj is 771M, so it might be about 1M memory usage)

Resources