Can't trace the problem in BST delete function - go

I can't trace the mistake in my logic in BST delete function in Go.
func delete(d *Node, v int) {
if d == nil {
fmt.Println("The tree is empty")
}
if v < d.key {
delete(d.left, v)
} else if v > d.key {
delete(d.right, v)
} else if v == d.key {
if d.right == nil && d.left == nil {
d = nil
} else {
if d.left == nil && d.right != nil {
d.key= d.right.key
delete(d.right,d.key)
} else if d.right == nil && d.left != nil {
d.key= d.left.key
delete(d.left,d.key)
}else{
min := minvalue(d.right)
d.key = min.key
delete(d.right, min.key)
}
}
}
}
The output shouldn't contain 4 but the result is instead showing 6 two times
The expected output is 5 6, but it's showing 4 6 6

As several have noted in the comments, you should provide a Minimal Reproducible Example, which helps people avoid wasting time on simple misunderstandings.
In this case, though, it's pretty obvious what you have done wrong—at least, at the first layer. (There may be more, depending on what you intend to do with these trees.)
Consider the following function:
func setToNil(p *int) {
p = nil
}
Let's use this from a main:
func main() {
x := 3
px := &x
fmt.Println("before: x =", x, "px =", px)
setToNil(px)
fmt.Println("after: x =", x, "px =", px)
}
(Complete version on the Go playground)
What do you expect this program to do? Try it out: did it do what you expected? Why, or why not? If not, what about this variant:
func setToTheAnswer(i int) {
i = 42
}
func main() {
x := 3
fmt.Println("before: x =", x)
setToTheAnswer(x)
fmt.Println("after: x =", x)
}
Fill in the rest and try it out. Why didn't x change? (Should it have changed? If you think so, why do you think so? The language definition says that it should not.)
Now, compare that to this version:
func setToTheAnswer(p *int) {
*p = 42
}
func setToNil(q **int) {
*q = nil
}
func main() {
x := 3
px := &x
fmt.Println("before: x =", x, "px =", px)
setToTheAnswer(px)
setToNil(&px) // note the & in front of px
fmt.Println("after: x =", x, "px =", px)
}
What will this version do? Try it on the playground.
With that in mind, think about your variable d
Your function:
func delete(d *Node, v int) {
// ...
}
takes a parameter named d of type pointer to Node (and v of type int of course). If you change d in delete, that has no effect on any * Node variable in any caller, because d is a copy of this pointer-to-Node. You can change *d to change the Node to which the caller's pointer points, but you cannot change the caller's pointer.
There are multiple different ways to fix this. For instance, instead of taking a d *Node you might take a different object that contains a root *Node pointer, or you might take a pd **Node so that you can update a d *Node in the caller. Which is the right way? That's up to you.

Related

Operate on a struct with lots of pointers (especially to numbers)

I have quite a few data structures that contain mostly numbers, I get the data, do a calculation and return the result.
The thing is that all of those numbers can be zero and hence, I had to switch to using pointers (*int64 or *float64) so that the default is nil and not 0.
Unfortunately, I don't know of a solution to this in Go except using pointers.
The problem comes now in the Calculate() function that is implemented for all data structures:
type X struct {
A, B, C, D, E, F *int
// and much more
Result *float64
}
func (x *X) Calculate() {
floatptr := func(f float64) *float64 { return &f }
x.Result = floatptr(float64(*x.A + *x.B + *x.C + *x.D + *x.E + *x.F))
}
This function will obviously panic if any of the data is nil. So, I wrote the functions differently that it checks for nil data before the calculation:
func (x *X) CalculateWithNilChecks() {
floatptr := func(f float64) *float64 { return &f }
if x.A == nil || x.B == nil || x.C == nil || x.D == nil || x.E == nil || x.F == nil {
return
}
x.Result = floatptr(float64(*x.A + *x.B + *x.C + *x.D + *x.E + *x.F))
}
The problem is that the data structures are quite long. Having a SUPER long if x != nil looks ugly. I was wondering if there is another (cleaner) way to doing this.
I thought of doing like in the encoding/json and just recover nil pointer dereference panics, not sure if this is cleaner TBH.
Another thought was to reflect the data structures and stop if any of the required data is nil, I don't think this should be necessary for such a simple task.
Here is a playground link for the above code
What am I missing here? Thanks!
As general solution you can unmarshal your JSON into a map of *int pointers or json.RawMessage and then use a reflection to cross check with your struct or just check it with expected number of fields.
func main() {
result := make(map[string]*int)
str := `{ "A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6 }`
json.Unmarshal([]byte(str), &result)
for _, field := range result {
// Check if expect fields exists using reflection or manually
// ...
}
}
You can use reflect module and error when one of the required fields is missing.
Use this as template.
package main
import (
"fmt"
"reflect"
)
type X struct {
A, B, C, D, E, F *int
Result *float64
}
func (x *X) PrintFoo() {
fmt.Println(x.A)
}
func main() {
a := 3
x := X{A: &a}
val := reflect.ValueOf(x)
for i := 0; i < val.Type().NumField(); i++ {
field := val.Type().Field(i)
fieldType := fmt.Sprintf("%s", field.Type)
if fieldType == "*int" && val.FieldByName(field.Name).IsNil() {
fmt.Println("Missing value on field", field.Name)
}
}
}

How to fill a slice with scan values

I'm brand new to Go and having trouble getting fmt.scan() to fill a slice. The number of input values is dynamic and I can't use a for loop. My initial thought was to try this:
package main
import "fmt"
func main() {
var x []int
fmt.Println("Enter input")
fmt.Scanf("%v", append(x))
fmt.Println(x)
}
Which obviously doesn't work. Can someone point me in the right direction?
[Get] fmt.Scan() to fill a slice. The number of input values is dynamic and I can't use a for loop.
Perhaps, something like this:
package main
import "fmt"
func input(x []int, err error) []int {
if err != nil {
return x
}
var d int
n, err := fmt.Scanf("%d", &d)
if n == 1 {
x = append(x, d)
}
return input(x, err)
}
func main() {
fmt.Println("Enter input:")
x := input([]int{}, nil)
fmt.Println("Input:", x)
}
Output:
Enter input:
1
2 3
4
5 6 7
Input: [1 2 3 4 5 6 7]
ADDENDUM:
When storage is allocated for a variable or a new value is created, and no explicit initialization is provided, the variable or value is given a default value, the zero value for its type: nil for slices. Conversions are expressions of the form T(x) where T is a type and x is an expression that can be converted to type T. []int(nil) is a conversion to the zero value for the slice value []int.
x := input([]int(nil), nil)
is equivalent to
x := input([]int{}, nil)
or
var x []int
x = input(x, nil)
I have revised my answer to use:
x := input([]int{}, nil)
I'm new to Go, so this are my 2cents as a newbie.
func main(){
var numsToInput int
fmt.Println("Welcome user!")
fmt.Println("How many numbers would you like to scale today?")
fmt.Scan(&numsToInput)
fmt.Println("Type please the ", num, " numbers: ")
var values []float32 // Empty slice
for i := 0; i < num; i++{
var val float32
fmt.Scanln(&val)
values = append(values, val)
}
fmt.Println(values)
}
It's not a very elaborate program, but certainly it's simple.
I hope it was useful.
Using simple packages and more logic, you could try this,
package main
import "fmt"
func main() {
var ele rune
var size int
var sli = make([]int,0,1)
size = cap(sli)
for i:=0; i<=size; i++{
if i>=len(sli){
size=size+1
}
ele = 0
fmt.Println("Enter a number to add: ")
fmt.Scan(&ele)
if ele==0 {
fmt.Println("Stopping!")
break
}
sli = append(sli, int(ele))
}
fmt.Println(sli)
}
The code would stop and print the slice when you enter anything other than an integer.

Go error checking and chaining

package main
import (
"errors"
"fmt"
)
type FieldElement struct {
Num int
Prime int
}
func (el *FieldElement) Add(o FieldElement) (FieldElement, error) {
if el.Prime != o.Prime {
return FieldElement{}, errors.New("cannot operate on two numbers in different Fields")
}
return FieldElement{(el.Num + o.Num) % el.Prime, el.Prime}, nil
}
// Sub, Mul, Div and Pow also members of FieldElement returning (FieldElement, error)
func main() {
a := FieldElement{13, 19}
b := FieldElement{9, 19}
fmt.Println(a.Add(b))
}
type Point struct {
X FieldElement
Y FieldElement
A FieldElement
B FieldElement
}
Now upon Point creation I want to check if a point is on the curve defined as y^2 = x^3 + ax + b
Each operation of FieldElement returns 2 values to satisfy the error checking.
So I can not do
x.Pow(3).Add(a.Mul(x)).Add(b)
and end up with
pow3, e1 := x.Pow(three)
mul, e2 := a.Mul(x)
add, e3 := pow3.Add(mul)
rval, e4 := add.Add(b)
// check that y^2 == rval
This makes the code hard to follow, what is the golang way to properly do this?
playground
Make your methods return only a single value, so they can be chained, and store the error value in that returned value, to check after. Example:
type FieldElement struct {
Num int
Prime int
Error error
}
func (el *FieldElement) Add(o FieldElement) *FieldElement {
if el.Error != nil {
// An error already happened, so do nothing
return el
}
if el.Prime != o.Prime {
el.Error = errors.New("cannot operate on two numbers in different Fields")
} else {
el.Num = (el.Num + o.Num) & el.Prime
}
return el
}
Then use it like this:
x.Add(...).Mul(...).Sub(...) // etc
if x.Error != nil {
// handle error here
}

check for equality on slices without order

I am trying to find a solution to check for equality in 2 slices. Unfortanely, the answers I have found require values in the slice to be in the same order. For example, http://play.golang.org/p/yV0q1_u3xR evaluates equality to false.
I want a solution that lets []string{"a","b","c"} == []string{"b","a","c"} evaluate to true.
MORE EXAMPLES
[]string{"a","a","c"} == []string{"c","a","c"} >>> false
[]string{"z","z","x"} == []string{"x","z","z"} >>> true
Here is an alternate solution, though perhaps a bit verbose:
func sameStringSlice(x, y []string) bool {
if len(x) != len(y) {
return false
}
// create a map of string -> int
diff := make(map[string]int, len(x))
for _, _x := range x {
// 0 value for int is 0, so just increment a counter for the string
diff[_x]++
}
for _, _y := range y {
// If the string _y is not in diff bail out early
if _, ok := diff[_y]; !ok {
return false
}
diff[_y] -= 1
if diff[_y] == 0 {
delete(diff, _y)
}
}
return len(diff) == 0
}
Try it on the Go Playground
You can use cmp.Diff together with cmpopts.SortSlices:
less := func(a, b string) bool { return a < b }
equalIgnoreOrder := cmp.Diff(x, y, cmpopts.SortSlices(less)) == ""
Here is a full example that runs on the Go Playground:
package main
import (
"fmt"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
)
func main() {
x := []string{"a", "b", "c"}
y := []string{"a", "c", "b"}
less := func(a, b string) bool { return a < b }
equalIgnoreOrder := cmp.Diff(x, y, cmpopts.SortSlices(less)) == ""
fmt.Println(equalIgnoreOrder) // prints "true"
}
The other answers have better time complexity O(N) vs (O(N log(N)), that are in my answer, also my solution will take up more memory if elements in the slices are repeated frequently, but I wanted to add it because I think this is the most straight forward way to do it:
package main
import (
"fmt"
"sort"
"reflect"
)
func array_sorted_equal(a, b []string) bool {
if len(a) != len(b) {return false }
a_copy := make([]string, len(a))
b_copy := make([]string, len(b))
copy(a_copy, a)
copy(b_copy, b)
sort.Strings(a_copy)
sort.Strings(b_copy)
return reflect.DeepEqual(a_copy, b_copy)
}
func main() {
a := []string {"a", "a", "c"}
b := []string {"c", "a", "c"}
c := []string {"z","z","x"}
d := []string {"x","z","z"}
fmt.Println( array_sorted_equal(a, b))
fmt.Println( array_sorted_equal(c, d))
}
Result:
false
true
I would think the easiest way would be to map the elements in each array/slice to their number of occurrences, then compare the maps:
func main() {
x := []string{"a","b","c"}
y := []string{"c","b","a"}
xMap := make(map[string]int)
yMap := make(map[string]int)
for _, xElem := range x {
xMap[xElem]++
}
for _, yElem := range y {
yMap[yElem]++
}
for xMapKey, xMapVal := range xMap {
if yMap[xMapKey] != xMapVal {
return false
}
}
return true
}
You'll need to add some additional due dilligence, like short circuiting if your arrays/slices contain elements of different types or are of different length.
Generalizing the code of testify ElementsMatch, solution to compare any kind of objects (in the example []map[string]string):
https://play.golang.org/p/xUS2ngrUWUl
Like adrianlzt wrote in his answer, an implementation of assert.ElementsMatch from testify can be used to achieve that. But how about reusing actual testify module instead of copying that code when all you need is a bool result of the comparison? The implementation in testify is intended for tests code and usually takes testing.T argument.
It turns out that ElementsMatch can be quite easily used outside of testing code. All it takes is a dummy implementation of an interface with ErrorF method:
type dummyt struct{}
func (t dummyt) Errorf(string, ...interface{}) {}
func elementsMatch(listA, listB interface{}) bool {
return assert.ElementsMatch(dummyt{}, listA, listB)
}
Or test it on The Go Playground, which I've adapted from the adrianlzt's example.
Since I haven't got enough reputation to comment, I have to post yet another answer with a bit better code readability:
func AssertSameStringSlice(x, y []string) bool {
if len(x) != len(y) {
return false
}
itemAppearsTimes := make(map[string]int, len(x))
for _, i := range x {
itemAppearsTimes[i]++
}
for _, i := range y {
if _, ok := itemAppearsTimes[i]; !ok {
return false
}
itemAppearsTimes[i]--
if itemAppearsTimes[i] == 0 {
delete(itemAppearsTimes, i)
}
}
if len(itemAppearsTimes) == 0 {
return true
}
return false
}
The logic is the same as in this answer
I know its been answered but still I would like to add my answer. By following code here stretchr/testify we can have something like
func Elementsmatch(listA, listB []string) (string, bool) {
aLen := len(listA)
bLen := len(listB)
if aLen != bLen {
return fmt.Sprintf("Len of the lists don't match , len listA %v, len listB %v", aLen, bLen), false
}
visited := make([]bool, bLen)
for i := 0; i < aLen; i++ {
found := false
element := listA[i]
for j := 0; j < bLen; j++ {
if visited[j] {
continue
}
if element == listB[j] {
visited[j] = true
found = true
break
}
}
if !found {
return fmt.Sprintf("element %s appears more times in %s than in %s", element, listA, listB), false
}
}
return "", true
}
Now lets talk about performance of this solution compared to map based ones. Well it really depends on the size of the lists which you are comparing, If size of list is large (I would say greater than 20) then map approach is better else this would be sufficent.
Well on Go PlayGround it shows 0s always, but run this on local system and you can see the difference in time taken as size of list increases
So the solution I propose is, adding map based comparision from above solution
func Elementsmatch(listA, listB []string) (string, bool) {
aLen := len(listA)
bLen := len(listB)
if aLen != bLen {
return fmt.Sprintf("Len of the lists don't match , len listA %v, len listB %v", aLen, bLen), false
}
if aLen > 20 {
return elementsMatchByMap(listA, listB)
}else{
return elementsMatchByLoop(listA, listB)
}
}
func elementsMatchByLoop(listA, listB []string) (string, bool) {
aLen := len(listA)
bLen := len(listB)
visited := make([]bool, bLen)
for i := 0; i < aLen; i++ {
found := false
element := listA[i]
for j := 0; j < bLen; j++ {
if visited[j] {
continue
}
if element == listB[j] {
visited[j] = true
found = true
break
}
}
if !found {
return fmt.Sprintf("element %s appears more times in %s than in %s", element, listA, listB), false
}
}
return "", true
}
func elementsMatchByMap(x, y []string) (string, bool) {
// create a map of string -> int
diff := make(map[string]int, len(x))
for _, _x := range x {
// 0 value for int is 0, so just increment a counter for the string
diff[_x]++
}
for _, _y := range y {
// If the string _y is not in diff bail out early
if _, ok := diff[_y]; !ok {
return fmt.Sprintf(" %v is not present in list b", _y), false
}
diff[_y] -= 1
if diff[_y] == 0 {
delete(diff, _y)
}
}
if len(diff) == 0 {
return "", true
}
return "", false
}

Golang - Swap PNG channels of a picture using Image and Image/PNG

I'm trying to write a short one, which will read a PNG file, and swap one channel with the other (R,G,B) being the possible choices.
I can't find out however, how to extract the integer from the color.Color object returned by image.At(x,y) . Writing it back would probably easier with image.Set(x,y,color) once i can construct the new RGBA color with the swapped channels.
Here I am now (you can pretty much skip to the last loop):
package main
import (
"flag"
"fmt"
//"image"
"image/color"
"image/png"
"os"
)
type Choice struct {
value string
valid bool
}
func (c *Choice) validate() {
goodchoices := []string{"R", "G", "B"}
for _, v := range goodchoices {
if c.value == v {
c.valid = true
}
}
}
func main() {
var fname string
var c1 Choice
var c2 Choice
flag.StringVar(&c1.value, "c1", "", "The color channel to swap - R or G or B ")
flag.StringVar(&c2.value, "c2", "", "The color channel to swap with - R or G or B ")
flag.StringVar(&fname, "f", "", "A .png image (normal map)")
flag.Parse()
c1.validate()
c2.validate()
if c1.valid == true && c2.valid == true {
fmt.Println("We could proceed..")
fmt.Println("Swapping channels:", c1.value, "<->", c2.value, "In", fname) //for testing
} else {
fmt.Println("Invalid channel... Please use R, G or B.")
return
}
file, err := os.Open(fname)
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
pic, err := png.Decode(file)
if err != nil {
fmt.Fprintf(os.Stderr, "%s: %v\n", fname, err)
return
}
b := pic.Bounds()
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
col := pic.At(x, y)
???? How do I swap the channels in col ????
}
}
}
I'm really new to Go and programming in general, so please consider it in your answer. Thank You.
Hmmm, that was harder than I thought it would be - I wonder if anyone can come up with a better idea!
The problem is that you don't know the concrete type that png.Decode returns - it may return any of the image types. You only have an image.Image interface which doesn't have a Set method.
To get round that, first define an interface which all the Image types which can set pixels satisfies
type ImageSet interface {
Set(x, y int, c color.Color)
}
Next see whether pic implements that interface (go will panic if it doesn't - use the picSet, ok form if that bothers you)
// Get an interface which can set pixels
picSet := pic.(ImageSet)
Now your loop looks like this - I only swapped red and green so you can see the idea.
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
col := pic.At(x, y)
r, g, b, a := col.RGBA()
// Swap green and red
newCol := color.RGBA{uint8(g>>8), uint8(r>>8), uint8(b>>8), uint8(a>>8)}
picSet.Set(x, y, newCol)
}
}
I suspect that a high performing version of this would have to use a type switch to determine which image type it was, then have a customized code for each one with uint8s for 24 bit images and uint16s for 48 bit images etc.
Here is the complete working example if you want to have a go. It doesn't work in the playground though - you'll have to download it.
Update: Just noticed your comment. If you know that you have an RGBA image, then you can use a type assertion to get the underlying image which makes things a whole lot easier.
// Get an image.RGBA if it is one
rgba, ok := pic.(*image.RGBA)
if !ok {
fmt.Println("That wasn't an RGBA!")
return
}
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
// Note type assertion to get a color.RGBA
col := rgba.At(x, y).(color.RGBA)
// Swap green and red
col.G, col.R = col.R, col.G
rgba.Set(x, y, col)
}
}

Resources