Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save shockalotti/6cbfc0aee8825bad168a to your computer and use it in GitHub Desktop.
Save shockalotti/6cbfc0aee8825bad168a to your computer and use it in GitHub Desktop.
Go Golang - pointers exercise, swap x and y
package main
import "fmt"
func swap(px, py *int) {
tempx := *px
tempy := *py
*px = tempy
*py = tempx
}
func main() {
x := int(1)
y := int(2)
fmt.Println("x was", x)
fmt.Println("y was", y)
swap(&x, &y)
fmt.Println("x is now", x)
fmt.Println("y is now", y)
}
@yathatguy
Copy link

do you know how to write test for this swap function?

@yathatguy
Copy link

hm, i've got it

package main

import (
	"testing"
)

type testpair struct {
	pairs []int
	result []int
}

func TestSwap (t *testing.T)  {
	tests := []testpair{
		{[]int{1,2}, []int{2,1}},
		{[]int{5,-1}, []int{-1,5}},
		{[]int{123,-123}, []int{-123,123}},
		{[]int{0,53535}, []int{53535,0}},
	}
	for _, tc := range tests {
		swap(&tc.pairs[0], &tc.pairs[1])
		if tc.pairs[0] != tc.result[0] || tc.pairs[1] != tc.result[1] {
			t.Error(
				"Expected",
				tc.result[0],
				tc.result[1],
				"but got",
				tc.pairs[0],
				tc.pairs[1],
				)
		}
	}
}

@dineshsonachalam
Copy link

dineshsonachalam commented May 24, 2020

Approach 1: Using a temporary(temp) variable to store the value of x

package main
import "fmt"

func swap(x *int, y *int) {
	temp := *x
	*x = *y
	*y = temp
}

func main(){
	x,y := 5,10
	fmt.Println("Before SWAP: ",x,y)
	swap(&x,&y)
	fmt.Println("After SWAP:  ",x, y)
}

/*
Output:
Before SWAP:  5 10
After SWAP:   10 5
*/

Approach 2: No mediators used

package main
import "fmt"

func swap(x *int, y *int) {
	*x,*y = *y,*x
}

func main(){
	x,y := 5,10
	fmt.Println("Before SWAP: ",x,y)
	swap(&x,&y)
	fmt.Println("After SWAP:  ",x, y)
}

/*
Output:
Before SWAP:  5 10
After SWAP:   10 5
*/

@PureSoulShard
Copy link

Ty, bro for your useful code.
+1 STAR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment