Browse Source

github.com/01-edu/public/test-go -> github.com/01-edu/go-tests

pull/768/head
xpetit 4 years ago
parent
commit
967d42561b
No known key found for this signature in database
GPG Key ID: 97C60669182C17A5
  1. 24
      test-go/Dockerfile
  2. 22
      test-go/README.md
  3. 56
      test-go/entrypoint.sh
  4. 7
      test-go/go.mod
  5. 2
      test-go/go.sum
  6. 119
      test-go/lib/base/base.go
  7. 37
      test-go/lib/is/is.go
  8. 420
      test-go/lib/lib.go
  9. 29
      test-go/solutions/addprimesum_prog/main.go
  10. 22
      test-go/solutions/alphamirror_prog/main.go
  11. 31
      test-go/solutions/balancedstring_prog/main.go
  12. 14
      test-go/solutions/boolean_prog/main.go
  13. 51
      test-go/solutions/brackets_prog/main.go
  14. 66
      test-go/solutions/brainfuck_prog/main.go
  15. 252
      test-go/solutions/btree.go
  16. 25
      test-go/solutions/cat_prog/main.go
  17. 190
      test-go/solutions/challenge.go
  18. 16
      test-go/solutions/cleanstr_prog/main.go
  19. 21
      test-go/solutions/comcheck_prog/main.go
  20. 55
      test-go/solutions/costumeprofit_prog/main.go
  21. 7
      test-go/solutions/countdown_prog/main.go
  22. 7
      test-go/solutions/displaya_prog/main.go
  23. 7
      test-go/solutions/displayalpham_prog/main.go
  24. 7
      test-go/solutions/displayalrevm_prog/main.go
  25. 21
      test-go/solutions/displayfile_prog/main.go
  26. 12
      test-go/solutions/displayfirstparam_prog/main.go
  27. 13
      test-go/solutions/displaylastparam_prog/main.go
  28. 7
      test-go/solutions/displayz_prog/main.go
  29. 50
      test-go/solutions/doop_prog/main.go
  30. 24
      test-go/solutions/expandstr_prog/main.go
  31. 16
      test-go/solutions/firstword_prog/main.go
  32. 47
      test-go/solutions/fixthemain_prog/main.go
  33. 72
      test-go/solutions/flags_prog/main.go
  34. 35
      test-go/solutions/fprime_prog/main.go
  35. 17
      test-go/solutions/gcd_prog/main.go
  36. 60
      test-go/solutions/grouping_prog/main.go
  37. 7
      test-go/solutions/hello_prog/main.go
  38. 51
      test-go/solutions/hiddenp_prog/main.go
  39. 25
      test-go/solutions/inter_prog/main.go
  40. 19
      test-go/solutions/ispowerof2_prog/main.go
  41. 16
      test-go/solutions/lastword_prog/main.go
  42. 23
      test-go/solutions/listat.go
  43. 13
      test-go/solutions/listclear.go
  44. 19
      test-go/solutions/listfind.go
  45. 28
      test-go/solutions/listforeach.go
  46. 43
      test-go/solutions/listforeachif.go
  47. 15
      test-go/solutions/listlast.go
  48. 10
      test-go/solutions/listmerge.go
  49. 22
      test-go/solutions/listpushback.go
  50. 14
      test-go/solutions/listpushfront.go
  51. 19
      test-go/solutions/listremoveif.go
  52. 15
      test-go/solutions/listreverse.go
  53. 11
      test-go/solutions/listsize.go
  54. 28
      test-go/solutions/listsort.go
  55. 32
      test-go/solutions/nbrconvertalpha_prog/main.go
  56. 32
      test-go/solutions/nenokku_prog/main.go
  57. 7
      test-go/solutions/onlya_prog/main.go
  58. 7
      test-go/solutions/onlyz_prog/main.go
  59. 50
      test-go/solutions/options_prog/main.go
  60. 10
      test-go/solutions/paramcount_prog/main.go
  61. 20
      test-go/solutions/piglatin_prog/main.go
  62. 22
      test-go/solutions/pilot_prog/main.go
  63. 22
      test-go/solutions/point_prog/main.go
  64. 7
      test-go/solutions/printalphabet_prog/main.go
  65. 8
      test-go/solutions/printalphabetalt2_prog/main.go
  66. 8
      test-go/solutions/printalphabetalt_prog/main.go
  67. 7
      test-go/solutions/printalphabetg_prog/main.go
  68. 7
      test-go/solutions/printalt2_prog/main.go
  69. 7
      test-go/solutions/printalt_prog/main.go
  70. 7
      test-go/solutions/printaltu2_prog/main.go
  71. 7
      test-go/solutions/printaltu_prog/main.go
  72. 18
      test-go/solutions/printbits_prog/main.go
  73. 40
      test-go/solutions/printchessboard_prog/main.go
  74. 7
      test-go/solutions/printdigits_prog/main.go
  75. 17
      test-go/solutions/printhex_prog/main.go
  76. 12
      test-go/solutions/printparams_prog/main.go
  77. 11
      test-go/solutions/printprogramname_prog/main.go
  78. 17
      test-go/solutions/printrevcomb_prog/main.go
  79. 7
      test-go/solutions/printreversealphabet_prog/main.go
  80. 8
      test-go/solutions/printreversealphabetalt2_prog/main.go
  81. 8
      test-go/solutions/printreversealphabetalt_prog/main.go
  82. 7
      test-go/solutions/printreversealphabetg_prog/main.go
  83. 33
      test-go/solutions/printrot_prog/main.go
  84. 87
      test-go/solutions/raid3_prog/main.go
  85. 33
      test-go/solutions/range_prog/main.go
  86. 64
      test-go/solutions/rectangle_prog/main.go
  87. 22
      test-go/solutions/repeatalpha_prog/main.go
  88. 33
      test-go/solutions/reverserange_prog/main.go
  89. 21
      test-go/solutions/reversestrcap_prog/main.go
  90. 12
      test-go/solutions/revparams_prog/main.go
  91. 20
      test-go/solutions/revwstr_prog/main.go
  92. 31
      test-go/solutions/robottoorigin_prog/main.go
  93. 66
      test-go/solutions/romannumbers_prog/main.go
  94. 31
      test-go/solutions/rostring_prog/main.go
  95. 28
      test-go/solutions/rot13_prog/main.go
  96. 37
      test-go/solutions/rotatevowels_prog/main.go
  97. 67
      test-go/solutions/rpncalc_prog/main.go
  98. 18
      test-go/solutions/searchreplace_prog/main.go
  99. 16
      test-go/solutions/sortedlistmerge.go
  100. 25
      test-go/solutions/sortlistinsert.go
  101. Some files were not shown because too many files changed in this diff diff.show_more

24
test-go/Dockerfile

@ -1,24 +0,0 @@
FROM docker.01-edu.org/golang:1.16.3-alpine3.13
ENV GIT_TERMINAL_PROMPT=0
RUN apk add --no-cache git
RUN go get golang.org/x/tools/cmd/goimports
RUN go get github.com/01-edu/rc
WORKDIR /piscine-go
RUN go mod init piscine-go
RUN go get github.com/01-edu/z01@v0.1.0
WORKDIR /public/test-go
COPY go.* ./
RUN go mod download
COPY lib lib
COPY solutions solutions
COPY tests tests
RUN go install $(grep -rl ChallengeMain ./tests | rev | cut -d/ -f2- | rev)
RUN rm -rf /piscine-go
COPY entrypoint.sh /usr/local/bin
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]

22
test-go/README.md

@ -1,22 +0,0 @@
# Tests
To run the tests make sure the two repositories are right next to each other:
- github.com/01-edu/piscine-go
- github.com/01-edu/public
To test an exercise, run this command in this folder (`public/test-go`):
```
go run github.com/01-edu/public/test-go/tests/isnegative_test
```
Relative paths work anywhere in `public/test-go`:
```
go run ./tests/printalphabet_test
cd tests
go run ./isnegative_test
```
No output means success.

56
test-go/entrypoint.sh

@ -1,56 +0,0 @@
#!/bin/sh
set -e
cp -r /public .
cp -a student piscine-go
cd piscine-go
if test "$EXAM_MODE"; then
go mod init main 2>/dev/null
GOSUMDB=off go get github.com/01-edu/z01@v0.1.0 2>/dev/null
fi
if test "$EXAM_RUN_ONLY" = true; then
go build -o exe "./$EXERCISE"
./exe "$@"
exit
fi
if ! test "$EXAM_MODE"; then
s=$(goimports -d .)
if test "$s"; then
echo 'Your Go files are not correctly formatted :'
echo
echo '$ goimports -d .'
echo "$s"
exit 1
fi
fi
if ! find . -type f -name '*.go' | grep -q .; then
echo "Missing Go file: $FILE"
exit 1
fi
if find . -type f -name '*.go' -exec grep -qE 'print(ln)?\(' {} +; then
echo "Your Go files cannot use print & println builtins"
exit 1
fi
# Check restrictions
if test "$ALLOWED_FUNCTIONS" && test "$FILE"; then
# shellcheck disable=SC2086
rc "$FILE" $ALLOWED_FUNCTIONS
fi
cd ~/public/test-go
# Compile and run test
if command -v "${EXERCISE}_test" >/dev/null 2>&1; then
# The exercise is a program
"${EXERCISE}_test"
else
# The exercise is a function
go run "./tests/${EXERCISE}_test"
fi

7
test-go/go.mod

@ -1,7 +0,0 @@
module github.com/01-edu/public/test-go
go 1.16
require student v0.0.0
replace student => ../../piscine-go

2
test-go/go.sum

@ -1,2 +0,0 @@
github.com/01-edu/z01 v0.1.0 h1:Rr1p92CKYXUgVFw872iGDABXpdkuKf2jmS+KV6r1034=
github.com/01-edu/z01 v0.1.0/go.mod h1:BH7t35JaNFuP83rTJDc5nkSfgmC/HYVcJsUcdFqYZNo=

119
test-go/lib/base/base.go

@ -1,119 +0,0 @@
package base
import (
"math/rand"
"strings"
"github.com/01-edu/public/test-go/lib"
)
func uniqueChar(s string) bool {
m := map[rune]struct{}{}
for _, r := range s {
if _, ok := m[r]; ok {
return false
}
m[r] = struct{}{}
}
return true
}
func IsValid(base string) bool {
return len(base) >= 2 && !strings.ContainsAny(base, "+-") && uniqueChar(base)
}
func power(nbr int, pwr int) int {
if pwr == 0 {
return 1
}
if pwr == 1 {
return nbr
}
return nbr * power(nbr, pwr-1)
}
func Atoi(s string, base string) int {
var result int
var i int
sign := 1
lengthBase := len(base)
lengths := len(s)
if !IsValid(base) {
return 0
}
if s[i] == '-' {
sign = -1
}
if s[i] == '-' || s[i] == '+' {
i++
}
for i < len(s) {
result += strings.Index(base, string(s[i])) * power(lengthBase, lengths-1)
i++
lengths--
}
return result * sign
}
func Valid() string {
valid := []string{
"01",
"CHOUMIisDAcat!",
"choumi",
"0123456789",
"abc",
"Zone01",
"0123456789ABCDEF",
"WhoAmI?",
}
i := rand.Intn(len(valid))
return valid[i]
}
func Invalid() string {
invalid := []string{
"0",
"1",
"CHOUMIisdacat!",
"choumiChoumi",
"01234567890",
"abca",
"Zone01Zone01",
"0123456789ABCDEF0",
"WhoAmI?IamWhoIam",
}
i := rand.Intn(len(invalid))
return invalid[i]
}
func StringFrom(base string) string {
letters := []rune(base)
size := lib.RandIntBetween(1, 10)
runes := make([]rune, size)
for i := range runes {
runes[i] = letters[rand.Intn(len(letters))]
}
return string(runes)
}
func ConvertNbr(n int, base string) string {
var result string
length := len(base)
for n >= length {
result = string(base[(n%length)]) + result
n = n / length
}
result = string(base[n]) + result
return result
}
func Convert(nbr, baseFrom, baseTo string) string {
resultIntermediary := Atoi(nbr, baseFrom)
resultFinal := ConvertNbr(resultIntermediary, baseTo)
return resultFinal
}

37
test-go/lib/is/is.go

@ -1,37 +0,0 @@
package is
import (
"math/big"
"unicode"
)
func Digit(s string) bool {
for _, r := range s {
if !unicode.IsDigit(r) {
return false
}
}
return true
}
func Lower(s string) bool {
for _, r := range s {
if !unicode.IsLower(r) {
return false
}
}
return true
}
func Upper(s string) bool {
for _, r := range s {
if !unicode.IsUpper(r) {
return false
}
}
return true
}
func Prime(i int) bool {
return big.NewInt(int64(i)).ProbablyPrime(0)
}

420
test-go/lib/lib.go

@ -1,420 +0,0 @@
package lib
import (
"bytes"
"fmt"
"io"
"math/big"
"math/rand"
"os"
"os/exec"
"path"
"reflect"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
)
const (
MinInt = ^MaxInt
MaxInt = 1<<63 - 1
StrLen = 13 // Default length of random strings
SliceLen = 8 // Default length of slices
)
var (
nsSince1970 = time.Now().UnixNano()
bigRand = rand.New(rand.NewSource(nsSince1970))
// charsets
Digit = RuneRange('0', '9') // Decimal digit characters
Lower = RuneRange('a', 'z') // Lowercase latin alphabet characters
Upper = RuneRange('A', 'Z') // Uppercase latin alphabet characters
ASCII = RuneRange(' ', '~') // ASCII printable characters
Space = strings.Repeat(" ", StrLen) // Spaces characters
Basic = Lower + Upper // Lower and Upper characters
Alnum = Basic + Digit // Basic and Digit characters
Words = Alnum + Space // Alnum and Space characters
)
func init() {
rand.Seed(nsSince1970)
}
// RuneRange returns a string containing all the valid runes from a to b.
func RuneRange(a, b rune) string {
var s []rune
for {
if utf8.ValidRune(a) {
s = append(s, a)
}
if a == b {
return string(s)
}
if a < b {
a++
} else {
a--
}
}
}
// IntRange returns a slice containing all the int from a to b.
func IntRange(a, b int) (s []int) {
for {
s = append(s, a)
if a == b {
return
}
if a < b {
a++
} else {
a--
}
}
}
// RandIntBetween returns a random int between a and b included.
func RandIntBetween(a, b int) int {
if a > b {
a, b = b, a
}
n := big.NewInt(int64(b)) // b
n.Sub(n, big.NewInt(int64(a))) // b-a
n.Add(n, big.NewInt(1)) // b-a+1
n.Rand(bigRand, n) // 0 <= n <= b-a
n.Add(n, big.NewInt(int64(a))) // a <= n <= b
return int(n.Int64())
}
// RandPosZ returns a random int between 0 and MaxInt included.
func RandPosZ() int { return RandIntBetween(0, MaxInt) }
// RandPos returns a random int between 1 and MaxInt included.
func RandPos() int { return RandIntBetween(1, MaxInt) }
// RandInt returns a random int between MinInt and MaxInt included.
func RandInt() int { return RandIntBetween(MinInt, MaxInt) }
// RandNeg returns a random int between MinInt and 1 included.
func RandNeg() int { return RandIntBetween(MinInt, 1) }
// RandNegZ returns a random int between MinInt and 0 included.
func RandNegZ() int { return RandIntBetween(MinInt, 0) }
// MakeIntFunc returns a slice of ints created by f.
func MakeIntFunc(f func() int) (s []int) {
i := 0
for i < SliceLen {
s = append(s, f())
i++
}
return
}
// MultRandPosZ returns a slice of random ints between 0 and MaxInt included.
func MultRandPosZ() []int { return MakeIntFunc(RandPosZ) }
// MultRandPos returns a slice of random ints between 1 and MaxInt included.
func MultRandPos() []int { return MakeIntFunc(RandPos) }
// MultRandInt returns a slice of random ints between MinInt and MaxInt included.
func MultRandInt() []int { return MakeIntFunc(RandInt) }
// MultRandNeg returns a slice of random ints between MinInt and 1 included.
func MultRandNeg() []int { return MakeIntFunc(RandNeg) }
// MultRandNegZ returns a slice of random ints between MinInt and 0 included.
func MultRandNegZ() []int { return MakeIntFunc(RandNegZ) }
// MultRandIntBetween returns a slice of random ints between a and b included.
func MultRandIntBetween(a, b int) []int {
return MakeIntFunc(func() int { return RandIntBetween(a, b) })
}
// RandRune returns a random printable rune
// (although you may not have the corresponding glyph).
// One-in-ten chance to get a rune higher than 0x10000 (1<<16).
func RandRune() rune {
ranges := unicode.PrintRanges
table := ranges[rand.Intn(len(ranges))]
if rand.Intn(10) == 0 {
r := table.R32[rand.Intn(len(table.R32))]
n := uint32(rand.Intn(int((r.Hi-r.Lo)/r.Stride) + 1))
return rune(r.Lo + n*r.Stride)
}
r := table.R16[rand.Intn(len(table.R16))]
n := uint16(rand.Intn(int((r.Hi-r.Lo)/r.Stride) + 1))
return rune(r.Lo + n*r.Stride)
}
// RandStr returns a string with l random characters taken from chars.
// If chars is empty, the characters are random printable runes.
func RandStr(l int, chars string) string {
if l <= 0 {
return ""
}
dst := make([]rune, l)
if chars == "" {
for i := range dst {
dst[i] = RandRune()
}
} else {
src := []rune(chars)
for i := range dst {
r := rand.Intn(len(src))
dst[i] = src[r]
}
}
return string(dst)
}
// RandDigit returns a string containing random decimal digit characters.
func RandDigit() string { return RandStr(StrLen, Digit) }
// RandLower returns a string containing random lowercase latin alphabet characters.
func RandLower() string { return RandStr(StrLen, Lower) }
// RandUpper returns a string containing random uppercase latin alphabet characters.
func RandUpper() string { return RandStr(StrLen, Upper) }
// RandASCII returns a string containing random ASCII printable characters.
func RandASCII() string { return RandStr(StrLen, ASCII) }
// RandSpace returns a string containing random spaces characters.
func RandSpace() string { return RandStr(StrLen, Space) }
// RandBasic returns a string containing random lower and upper characters.
func RandBasic() string { return RandStr(StrLen, Basic) }
// RandAlnum returns a string containing random basic and digit characters.
func RandAlnum() string { return RandStr(StrLen, Alnum) }
// RandWords returns a string containing random alphanumeric and space characters.
func RandWords() string { return RandStr(StrLen, Words) }
// MakeStrFunc returns a slice of strings created by f.
func MakeStrFunc(f func() string) (s []string) {
i := 0
for i < StrLen {
s = append(s, f())
i++
}
return
}
// MultRandDigit returns a slice of strings containing random Decimal digit characters.
func MultRandDigit() []string { return MakeStrFunc(RandDigit) }
// MultRandLower returns a slice of strings containing random Lowercase latin alphabet.
func MultRandLower() []string { return MakeStrFunc(RandLower) }
// MultRandUpper returns a slice of strings containing random Uppercase latin alphabet.
func MultRandUpper() []string { return MakeStrFunc(RandUpper) }
// MultRandASCII returns a slice of strings containing random ASCII printable characters.
func MultRandASCII() []string { return MakeStrFunc(RandASCII) }
// MultRandSpace returns a slice of strings containing random Spaces characters.
func MultRandSpace() []string { return MakeStrFunc(RandSpace) }
// MultRandBasic returns a slice of strings containing random Lower and Upper characters.
func MultRandBasic() []string { return MakeStrFunc(RandBasic) }
// MultRandAlnum returns a slice of strings containing random Basic and Digit characters.
func MultRandAlnum() []string { return MakeStrFunc(RandAlnum) }
// MultRandWords returns a slice of strings containing random Alnum and Space characters.
func MultRandWords() []string { return MakeStrFunc(RandWords) }
func Format(a ...interface{}) string {
ss := make([]string, len(a))
for i, v := range a {
switch v.(type) {
case nil:
ss[i] = "nil" // instead of "<nil>"
case
string,
byte, // uint8
rune: // int32
// string : a double-quoted string safely escaped with Go syntax
// byte, rune : a single-quoted character literal safely escaped with Go syntax
ss[i] = fmt.Sprintf("%q", v)
default:
// a Go-syntax representation of the value
ss[i] = fmt.Sprintf("%#v", v)
}
}
return strings.Join(ss, ", ")
}
var valueOf = reflect.ValueOf
func Call(fn interface{}, args []interface{}) []interface{} {
// Convert args from []interface{} to []reflect.Value
vals := make([]reflect.Value, len(args))
for i, v := range args {
if v != nil {
vals[i] = valueOf(v)
} else {
vals[i] = reflect.Zero(reflect.TypeOf((*interface{})(nil)).Elem())
}
}
vals = valueOf(fn).Call(vals)
// Convert the return values from []reflect.Value to []interface{}
result := make([]interface{}, len(vals))
for i, v := range vals {
result[i] = v.Interface()
}
return result
}
type Output struct {
Results []interface{}
Stdout string
}
func Monitor(fn interface{}, args []interface{}) (out Output) {
old := os.Stdout
r, w, err := os.Pipe()
panicIfNotNil(err)
os.Stdout = w
out.Results = Call(fn, args)
outC := make(chan string)
var buf strings.Builder
go func() {
io.Copy(&buf, r)
outC <- buf.String()
}()
os.Stdout = old
w.Close()
out.Stdout = <-outC
return out
}
func Challenge(name string, fn1, fn2 interface{}, args ...interface{}) {
st1 := Monitor(fn1, args)
st2 := Monitor(fn2, args)
if !reflect.DeepEqual(st1.Results, st2.Results) {
Fatalf("%s(%s) == %s instead of %s\n",
name,
Format(args...),
Format(st1.Results...),
Format(st2.Results...),
)
}
if !reflect.DeepEqual(st1.Stdout, st2.Stdout) {
Fatalf("%s(%s) prints:\n%s\ninstead of:\n%s\n",
name,
Format(args...),
Format(st1.Stdout),
Format(st2.Stdout),
)
}
}
func Fatal(a ...interface{}) {
fmt.Fprint(os.Stderr, a...)
os.Exit(1)
}
func Fatalln(a ...interface{}) {
fmt.Fprintln(os.Stderr, a...)
os.Exit(1)
}
func Fatalf(format string, a ...interface{}) {
fmt.Fprintf(os.Stderr, format, a...)
os.Exit(1)
}
func panicIfNotNil(err error) {
if err != nil {
panic(err)
}
}
func ChallengeMainStdin(exercise, input string, args ...string) {
run := func(pkg string) (string, int) {
binaryPath := path.Join(os.TempDir(), "binaries", path.Base(pkg))
panicIfNotNil(exec.Command("go", "build", "-o", binaryPath, pkg).Run())
cmd := exec.Command(binaryPath, args...)
if input != "" {
cmd.Stdin = bytes.NewBufferString(input)
}
b, err := cmd.CombinedOutput()
if err != nil {
if ee, ok := err.(*exec.ExitError); ok {
return string(b), ee.ExitCode()
}
panic(err)
}
return string(b), 0
}
console := func(out string) string {
var quotedArgs []string
for _, arg := range args {
quotedArgs = append(quotedArgs, strconv.Quote(arg))
}
s := "\n$ "
if input != "" {
s += "echo -ne " + strconv.Quote(input) + " | "
}
return fmt.Sprintf(s+"./%s %s\n%s$ ", exercise, strings.Join(quotedArgs, " "), out)
}
code := func(code int) string {
return fmt.Sprintf("echo $?\n%d\n$", code)
}
student, studentCode := run(path.Join("student", exercise))
solution, solutionCode := run(path.Join("github.com/01-edu/public/test-go/solutions", exercise+"_prog"))
if solutionCode == 0 {
if studentCode != 0 {
Fatalln("Your program fails (non-zero exit status) when it should not :\n" +
console(student) +
code(studentCode) + "\n\n" +
"Expected :\n" +
console(solution) +
code(solutionCode))
}
} else {
if studentCode == 0 {
Fatalln("Your program does not fail when it should (with a non-zero exit status) :" + "\n" +
console(student) +
code(studentCode) + "\n\n" +
"Expected :\n" +
console(solution) +
code(solutionCode))
}
}
if student != solution {
Fatalln("Your program output is not correct :\n" +
console(student) + "\n\n" +
"Expected :\n" +
console(solution))
}
}
// GCD returns greatest common divisor of a and b.
func GCD(a, b int) int {
for a != b {
if a > b {
a -= b
} else {
b -= a
}
}
return a
}
func ChallengeMain(exercise string, args ...string) {
ChallengeMainStdin(exercise, "", args...)
}
// TODO: check unhandled errors on all solutions (it should contains "ERROR" on the first line to prove we correctly handle the error)
// TODO: remove the number of rand functions, refactor test cases (aka "table")

29
test-go/solutions/addprimesum_prog/main.go

@ -1,29 +0,0 @@
package main
import (
"fmt"
"os"
"strconv"
"github.com/01-edu/public/test-go/lib/is"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("0")
} else {
argument, _ := strconv.Atoi(os.Args[1])
if argument < 0 {
fmt.Println("0")
} else {
result := 0
for ; argument >= 0; argument-- {
if is.Prime(argument) {
result += argument
}
}
fmt.Println(result)
}
}
}

22
test-go/solutions/alphamirror_prog/main.go

@ -1,22 +0,0 @@
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) == 2 {
arg := []rune(os.Args[1])
for i, ch := range arg {
if ch >= 'a' && ch <= 'z' {
arg[i] = 'z' - ch + 'a'
} else if ch >= 'A' && ch <= 'Z' {
arg[i] = 'Z' - ch + 'A'
}
}
fmt.Print(string(arg))
}
fmt.Println()
}

31
test-go/solutions/balancedstring_prog/main.go

@ -1,31 +0,0 @@
package main
import (
"fmt"
"os"
)
func solve(s string) int {
var count, countC, countD int
for _, r := range s {
if r == 'C' {
countC++
} else if r == 'D' {
countD++
}
if countC == countD {
count++
countC = 0
countD = 0
}
}
return count
}
func main() {
args := os.Args[1:]
if len(args) == 1 {
result := solve(args[0])
fmt.Println(result)
}
}

14
test-go/solutions/boolean_prog/main.go

@ -1,14 +0,0 @@
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args[1:])%2 == 0 {
fmt.Println("I have an even number of arguments")
} else {
fmt.Println("I have an odd number of arguments")
}
}

51
test-go/solutions/brackets_prog/main.go

@ -1,51 +0,0 @@
package main
import (
"fmt"
"os"
)
func matchBrackets(exp string) bool {
runes := []rune(exp)
var opened []rune
ptr := -1
for _, c := range runes {
if c == '(' || c == '[' || c == '{' {
opened = append(opened, c)
ptr++
} else if c == ')' {
if ptr < 0 || opened[ptr] != '(' {
return false
}
opened = opened[:len(opened)-1]
ptr--
} else if c == ']' {
if ptr < 0 || opened[ptr] != '[' {
return false
}
opened = opened[:len(opened)-1]
ptr--
} else if c == '}' {
if ptr < 0 || opened[ptr] != '{' {
return false
}
opened = opened[:len(opened)-1]
ptr--
}
}
return len(opened) == 0
}
func main() {
if len(os.Args) == 1 {
fmt.Println()
} else {
for _, v := range os.Args[1:] {
if matchBrackets(v) {
fmt.Println("OK")
} else {
fmt.Println("Error")
}
}
}
}

66
test-go/solutions/brainfuck_prog/main.go

@ -1,66 +0,0 @@
package main
import (
"fmt"
"os"
)
const SIZE = 2048
func main() {
if len(os.Args) != 2 {
return
}
progpoint := []byte(os.Args[1])
var arby [SIZE]byte
pos := 0
openBr := 0 // opened brackets
i := 0 // iterates through the source code passed in the argument
N := len(progpoint) // length of the source code
for i >= 0 && i < N {
switch progpoint[i] {
case '>':
// Increment the pointer
pos++
case '<':
// decrement the pointes
pos--
case '+':
// increment the pointed byte
arby[pos]++
case '-':
// decrement the pointed byte
arby[pos]--
case '.':
// print the pointed byte on std output
fmt.Printf("%c", rune(arby[pos]))
case '[':
// go to the matching ']' if the pointed byte is 0 (while start)
openBr = 0
if arby[pos] == 0 {
for i < N && (progpoint[i] != byte(']') || openBr > 1) {
if progpoint[i] == byte('[') {
openBr++
} else if progpoint[i] == byte(']') {
openBr--
}
i++
}
}
case ']':
// go to the matching '[' if the pointed byte is not 0 (while end)
openBr = 0
if arby[pos] != 0 {
for i >= 0 && (progpoint[i] != byte('[') || openBr > 1) {
if progpoint[i] == byte(']') {
openBr++
} else if progpoint[i] == byte('[') {
openBr--
}
i--
}
}
}
i++
}
}

252
test-go/solutions/btree.go

@ -1,252 +0,0 @@
package solutions
type TreeNode struct {
Left, Right, Parent *TreeNode
Data string
}
func BTreeInsertData(bt *TreeNode, elem string) *TreeNode {
if bt == nil {
return &TreeNode{Data: elem}
}
if elem < bt.Data {
bt.Left = BTreeInsertData(bt.Left, elem)
bt.Left.Parent = bt
} else if elem >= bt.Data {
bt.Right = BTreeInsertData(bt.Right, elem)
bt.Right.Parent = bt
}
return bt
}
func BTreeApplyInorder(root *TreeNode, f func(...interface{}) (int, error)) {
if root != nil {
BTreeApplyInorder(root.Left, f)
f(root.Data)
BTreeApplyInorder(root.Right, f)
}
}
func BTreeApplyPreorder(root *TreeNode, f func(...interface{}) (int, error)) {
if root != nil {
f(root.Data)
BTreeApplyPreorder(root.Left, f)
BTreeApplyPreorder(root.Right, f)
}
}
func BTreeApplyPostorder(root *TreeNode, f func(...interface{}) (int, error)) {
if root != nil {
BTreeApplyPostorder(root.Left, f)
BTreeApplyPostorder(root.Right, f)
f(root.Data)
}
}
func BTreeSearchItem(root *TreeNode, elem string) *TreeNode {
if root == nil {
return nil
}
if root.Data == elem {
return root
}
if elem < root.Data {
return BTreeSearchItem(root.Left, elem)
}
return BTreeSearchItem(root.Right, elem)
}
func BTreeLevelCount(root *TreeNode) int {
if root == nil {
return 0
}
left := BTreeLevelCount(root.Left)
right := BTreeLevelCount(root.Right)
if left > right {
return left + 1
}
return right + 1
}
func BTreeIsBinary(root *TreeNode) bool {
condLeft := true
condRight := true
if root == nil {
return true
}
if root.Left != nil {
condLeft = BTreeIsBinary(root.Left) && root.Data >= root.Left.Data
}
if root.Right != nil {
condRight = BTreeIsBinary(root.Right) && root.Data <= root.Right.Data
}
return condLeft && condRight
}
func applyGivenOrder(root *TreeNode, level int, f func(...interface{}) (int, error)) {
if root == nil {
return
}
if level == 0 {
arg := interface{}(root.Data)
f(arg)
} else if level > 0 {
applyGivenOrder(root.Left, level-1, f)
applyGivenOrder(root.Right, level-1, f)
}
}
// Apply the function f level by level
func BTreeApplyByLevel(root *TreeNode, f func(...interface{}) (int, error)) {
h := BTreeLevelCount(root)
for i := 0; i < h; i++ {
applyGivenOrder(root, i, f)
}
}
/*-----------------------------------
* node-> (A) (B)
* / / \
* temp-> (B) --------> (C) (A)
* / \ /
* (C) [z] [z]
*------------------------------------*/
func BTreeRotateRight(node *TreeNode) *TreeNode {
if node == nil {
return nil
}
if node.Left == nil {
return node
}
temp := node.Left
node.Left = temp.Right
if temp.Right != nil {
temp.Right.Parent = node
}
if node.Parent != nil {
if node == node.Parent.Left {
node.Parent.Left = temp
} else {
node.Parent.Right = temp
}
}
temp.Right = node
temp.Parent = node.Parent
node.Parent = temp
return temp
}
/*------------------------------------
* node->(A) (B)
* \ / \
* temp-> (B) -------> (A) (C)
* / \ \
* [z] (C) [z]
*------------------------------------- */
func BTreeRotateLeft(node *TreeNode) *TreeNode {
if node == nil {
return nil
}
if node.Right == nil {
return node
}
temp := node.Right
node.Right = temp.Left
if temp.Left != nil {
temp.Left.Parent = node
}
if node.Parent != nil {
if node == node.Parent.Left {
node.Parent.Left = temp
} else {
node.Parent.Right = temp
}
}
temp.Left = node
temp.Parent = node.Parent
node.Parent = temp
return temp
}
// Returns the maximum node in the subtree started by root
func BTreeMax(root *TreeNode) *TreeNode {
if root == nil || root.Right == nil {
return root
}
return BTreeMax(root.Right)
}
// Returns the minimum value in the subtree started by root
func BTreeMin(root *TreeNode) *TreeNode {
if root == nil || root.Left == nil {
return root
}
return BTreeMin(root.Left)
}
func BTreeTransplant(root, node, repla *TreeNode) *TreeNode {
if root == nil {
return nil
}
replacement := node
if node.Parent == nil {
root = repla
} else if node == node.Parent.Left {
replacement.Parent.Left = repla
} else {
replacement.Parent.Right = repla
}
if repla != nil {
repla.Parent = node.Parent
}
return root
}
func BTreeDeleteNode(root, node *TreeNode) *TreeNode {
if node != nil {
if node.Left == nil {
root = BTreeTransplant(root, node, node.Right)
} else if node.Right == nil {
root = BTreeTransplant(root, node, node.Left)
} else {
y := BTreeMin(node.Right)
if y != nil && y.Parent != node {
root = BTreeTransplant(root, y, y.Right)
y.Right = node.Right
y.Right.Parent = y
}
root = BTreeTransplant(root, node, y)
y.Left = node.Left
y.Left.Parent = y
}
}
return root
}

25
test-go/solutions/cat_prog/main.go

@ -1,25 +0,0 @@
package main
import (
"io"
"io/ioutil"
"os"
"github.com/01-edu/public/test-go/lib"
)
func main() {
if len(os.Args) == 1 {
if _, err := io.Copy(os.Stdout, os.Stdin); err != nil {
panic(err)
}
} else {
for _, arg := range os.Args[1:] {
b, err := ioutil.ReadFile(arg)
if err != nil {
lib.Fatalln("ERROR:", err)
}
os.Stdout.Write(b)
}
}
}

190
test-go/solutions/challenge.go

@ -1,190 +0,0 @@
package solutions
import (
"reflect"
"runtime"
"strconv"
"strings"
"github.com/01-edu/public/test-go/lib"
)
func FormatTree(root *TreeNode) string {
if root == nil {
return ""
}
res := root.Data + "\n"
res += formatSubTree(root, "")
return res
}
func formatSubTree(root *TreeNode, prefix string) string {
if root == nil {
return ""
}
var res string
hasLeft := root.Left != nil
hasRight := root.Right != nil
if !hasLeft && !hasRight {
return res
}
res += prefix
if hasLeft && hasRight {
res += "├── "
}
if !hasLeft && hasRight {
res += "└── "
}
if hasRight {
printStrand := (hasLeft && hasRight && (root.Right.Right != nil || root.Right.Left != nil))
newPrefix := prefix
if printStrand {
newPrefix += "│ "
} else {
newPrefix += " "
}
res += root.Right.Data + "\n"
res += formatSubTree(root.Right, newPrefix)
}
if hasLeft {
if hasRight {
res += prefix
}
res += "└── " + root.Left.Data + "\n"
res += formatSubTree(root.Left, prefix+" ")
}
return res
}
func ParentList(root *TreeNode) string {
if root == nil {
return ""
}
var parent string
if root.Parent == nil {
parent = "nil"
} else {
parent = root.Parent.Data
}
r := "Node: " + root.Data + " Parent: " + parent + "\n"
r += ParentList(root.Left) + ParentList(root.Right)
return r
}
func ChallengeTree(
name string,
fn1, fn2 interface{},
arg1 *TreeNode, arg2 interface{},
args ...interface{},
) {
args1 := []interface{}{arg1}
args2 := []interface{}{arg2}
if args != nil {
for _, v := range args {
args1 = append(args1, v)
args2 = append(args2, v)
}
}
st1 := lib.Monitor(fn1, args1)
st2 := lib.Monitor(fn2, args2)
if st1.Stdout != st2.Stdout {
lib.Fatalf("%s(\n%s)\n prints %s instead of %s\n",
name,
FormatTree(arg1),
lib.Format(st2.Stdout),
lib.Format(st1.Stdout),
)
}
}
func PrintList(n *NodeI) string {
var res string
it := n
for it != nil {
res += strconv.Itoa(it.Data) + "-> "
it = it.Next
}
res += "<nil>"
return res
}
func ListToString(n *NodeL) string {
var res string
it := n
for it != nil {
switch it.Data.(type) {
case int:
res += strconv.Itoa(it.Data.(int)) + "-> "
case string:
res += it.Data.(string) + "-> "
}
it = it.Next
}
res += "<nil>"
return res
}
func ConvertIntToInterface(t []int) []interface{} {
RandLen := lib.RandIntBetween(0, len(t))
s := make([]interface{}, RandLen)
for j := 0; j < RandLen; j++ {
for i := 0; i < lib.RandIntBetween(1, len(t)); i++ {
s[j] = t[i]
}
}
return s
}
func ConvertIntToStringface(t []string) []interface{} {
RandLen := lib.RandIntBetween(0, len(t))
s := make([]interface{}, RandLen)
for j := 0; j < RandLen; j++ {
for i := 0; i < lib.RandIntBetween(1, len(t)); i++ {
s[j] = t[i]
}
}
return s
}
type NodeTest struct {
Data []interface{}
}
func ElementsToTest(table []NodeTest) []NodeTest {
table = append(table,
NodeTest{
Data: []interface{}{},
},
)
for i := 0; i < 3; i++ {
val := NodeTest{
Data: ConvertIntToInterface(lib.MultRandInt()),
}
table = append(table, val)
}
for i := 0; i < 3; i++ {
val := NodeTest{
Data: ConvertIntToStringface(lib.MultRandWords()),
}
table = append(table, val)
}
return table
}
// GetName gets the function name
func GetName(f interface{}) string {
pathFuncUsed := strings.Split(runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name(), "/")
return pathFuncUsed[len(pathFuncUsed)-1]
}

16
test-go/solutions/cleanstr_prog/main.go

@ -1,16 +0,0 @@
package main
import (
"fmt"
"os"
"regexp"
"strings"
)
func main() {
if len(os.Args) == 2 {
re := regexp.MustCompile(`( +)`)
fmt.Print(re.ReplaceAllString(strings.Trim(os.Args[1], " "), " "))
}
fmt.Println()
}

21
test-go/solutions/comcheck_prog/main.go

@ -1,21 +0,0 @@
package main
import (
"fmt"
"os"
)
func main() {
safeWords := []string{"01", "galaxy", "galaxy 01"}
count := 0
for _, arg := range os.Args[1:] {
for _, s := range safeWords {
if s == arg {
count++
}
}
}
if count == 1 || count == 2 {
fmt.Println("Alert!!!")
}
}

55
test-go/solutions/costumeprofit_prog/main.go

@ -1,55 +0,0 @@
package main
import (
"fmt"
"os"
"strconv"
)
func min(numbers ...int) int {
min := numbers[0]
for _, i := range numbers {
if i < min {
min = i
}
}
return min
}
func max(numbers ...int) int {
max := numbers[0]
for _, i := range numbers {
if i > max {
max = i
}
}
return max
}
func costumeProfit(a, b, c, d, e, f int) int {
if d == min(a, b, c, d) {
return d * max(e, f)
}
if e > f {
ans := min(a, d) * e
d -= min(a, d)
ans += min(d, b, c) * f
return ans
}
ans := min(b, c, d) * f
d -= min(b, c, d)
ans += min(a, d) * e
return ans
}
func main() {
args := os.Args[1:]
a, _ := strconv.Atoi(args[0])
b, _ := strconv.Atoi(args[1])
c, _ := strconv.Atoi(args[2])
d, _ := strconv.Atoi(args[3])
e, _ := strconv.Atoi(args[4])
f, _ := strconv.Atoi(args[5])
fmt.Println(costumeProfit(a, b, c, d, e, f))
}

7
test-go/solutions/countdown_prog/main.go

@ -1,7 +0,0 @@
package main
import "fmt"
func main() {
fmt.Println(9876543210)
}

7
test-go/solutions/displaya_prog/main.go

@ -1,7 +0,0 @@
package main
import "fmt"
func main() {
fmt.Println("a")
}

7
test-go/solutions/displayalpham_prog/main.go

@ -1,7 +0,0 @@
package main
import "fmt"
func main() {
fmt.Println("aBcDeFgHiJkLmNoPqRsTuVwXyZ")
}

7
test-go/solutions/displayalrevm_prog/main.go

@ -1,7 +0,0 @@
package main
import "fmt"
func main() {
fmt.Println("zYxWvUtSrQpOnMlKjIhGfEdCbA")
}

21
test-go/solutions/displayfile_prog/main.go

@ -1,21 +0,0 @@
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("File name missing")
} else if len(os.Args) > 2 {
fmt.Println("Too many arguments")
} else {
b, err := ioutil.ReadFile(os.Args[1])
if err != nil {
panic(err)
}
os.Stdout.Write(b)
}
}

12
test-go/solutions/displayfirstparam_prog/main.go

@ -1,12 +0,0 @@
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) > 1 {
fmt.Println(os.Args[1])
}
}

13
test-go/solutions/displaylastparam_prog/main.go

@ -1,13 +0,0 @@
package main
import (
"fmt"
"os"
)
func main() {
size := len(os.Args)
if size > 1 {
fmt.Println(os.Args[size-1])
}
}

7
test-go/solutions/displayz_prog/main.go

@ -1,7 +0,0 @@
package main
import "fmt"
func main() {
fmt.Println("z")
}

50
test-go/solutions/doop_prog/main.go

@ -1,50 +0,0 @@
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
if len(os.Args) == 4 {
a, err := strconv.Atoi(os.Args[1])
if err != nil {
return
}
b, err := strconv.Atoi(os.Args[3])
if err != nil {
return
}
operator := os.Args[2]
switch operator {
case "+":
result := a + b
if (result > a) == (b > 0) {
fmt.Println(result)
}
case "-":
result := a - b
if (result < a) == (b > 0) {
fmt.Println(result)
}
case "*":
result := a * b
if a == 0 || (result/a == b) {
fmt.Println(result)
}
case "/":
if b == 0 {
fmt.Println("No division by 0")
} else {
fmt.Println(a / b)
}
case "%":
if b == 0 {
fmt.Println("No modulo by 0")
} else {
fmt.Println(a % b)
}
}
}
}

24
test-go/solutions/expandstr_prog/main.go

@ -1,24 +0,0 @@
package main
import (
"fmt"
"os"
"strings"
)
func deleteExtraSpaces(a []string) (res []string) {
for _, v := range a {
if v != "" {
res = append(res, v)
}
}
return
}
func main() {
if len(os.Args) == 2 {
arg := strings.Split(os.Args[1], " ")
arg = deleteExtraSpaces(arg)
fmt.Println(strings.Join(arg, " "))
}
}

16
test-go/solutions/firstword_prog/main.go

@ -1,16 +0,0 @@
package main
import (
"fmt"
"os"
"strings"
)
func main() {
if len(os.Args) == 2 {
s := strings.Split(strings.TrimSpace(os.Args[1]), " ")[0]
if s != "" {
fmt.Println(s)
}
}
}

47
test-go/solutions/fixthemain_prog/main.go

@ -1,47 +0,0 @@
package main
import "fmt"
const (
CLOSE = iota
OPEN
)
type Door struct {
State int
}
func CloseDoor(ptrDoor *Door) {
fmt.Println("Door Closing...")
ptrDoor.State = CLOSE
}
func OpenDoor(ptrdoor *Door) {
fmt.Println("Door Opening...")
ptrdoor.State = OPEN
}
func IsDoorOpened(ptrDoor *Door) bool {
fmt.Println("is the Door opened ?")
return ptrDoor.State == OPEN
}
func IsDoorClosed(ptrDoor *Door) bool {
fmt.Println("is the Door closed ?")
return ptrDoor.State == CLOSE
}
func main() {
var door Door
OpenDoor(&door)
if IsDoorClosed(&door) {
OpenDoor(&door)
}
if IsDoorOpened(&door) {
CloseDoor(&door)
}
if door.State == OPEN {
CloseDoor(&door)
}
}

72
test-go/solutions/flags_prog/main.go

@ -1,72 +0,0 @@
package main
import (
"fmt"
"os"
"sort"
"strings"
)
type helpMs struct {
flag string
shortenFlag string
handler string
}
func obtainValues(value, strsplit string) string {
values := strings.Split(value, "=")
return values[len(values)-1]
}
func setMs(flag, shortenFlag, handler string) *helpMs {
helpMs := &helpMs{
flag: flag,
shortenFlag: shortenFlag,
handler: handler,
}
return helpMs
}
func main() {
size := len(os.Args)
if size == 1 || os.Args[1] == "-h" || os.Args[1] == "--help" {
table := []helpMs{}
helpMs := setMs("--insert", "-i", "This flag inserts the string into the string passed as argument.")
table = append(table, *helpMs)
helpMs = setMs("--order", "-o", "This flag will behave like a boolean, if it is called it will order the argument.")
table = append(table, *helpMs)
for _, v := range table {
fmt.Println(v.flag)
fmt.Println(" ", v.shortenFlag)
fmt.Println(" ", v.handler)
}
} else if size <= 4 {
var runes []rune
strToInsert := ""
var order bool
for i := 1; i < size; i++ {
if strings.Contains(os.Args[i], "--insert") || strings.Contains(os.Args[i], "-i") {
strToInsert = obtainValues(os.Args[i], "=")
} else if strings.Contains(os.Args[i], "--order") || strings.Contains(os.Args[i], "-o") {
order = true
} else {
runes = []rune(os.Args[i])
}
}
if strToInsert != "" {
concatStr := string(runes) + strToInsert
runes = []rune(concatStr)
}
if order {
sort.Slice(runes, func(i, j int) bool {
return runes[i] < runes[j]
})
}
fmt.Println(string(runes))
}
}

35
test-go/solutions/fprime_prog/main.go

@ -1,35 +0,0 @@
package main
import (
"fmt"
"os"
"strconv"
)
func fprime(value int) {
if value == 1 {
return
}
divisionIterator := 2
for value > 1 {
if value%divisionIterator == 0 {
fmt.Print(divisionIterator)
value = value / divisionIterator
if value > 1 {
fmt.Print("*")
}
divisionIterator--
}
divisionIterator++
}
fmt.Println()
}
func main() {
if len(os.Args) == 2 {
if i, err := strconv.Atoi(os.Args[1]); err == nil {
fprime(i)
}
}
}

17
test-go/solutions/gcd_prog/main.go

@ -1,17 +0,0 @@
package main
import (
"fmt"
"os"
"strconv"
"github.com/01-edu/public/test-go/lib"
)
func main() {
if len(os.Args) == 3 {
a, _ := strconv.Atoi(os.Args[1])
b, _ := strconv.Atoi(os.Args[2])
fmt.Println(lib.GCD(a, b))
}
}

60
test-go/solutions/grouping_prog/main.go

@ -1,60 +0,0 @@
package main
import (
"fmt"
"os"
"strings"
"unicode"
)
func singleSearch(exp []string, text string) []string {
items := strings.Split(text, " ")
var result []string
for _, item := range items {
for _, word := range exp {
if strings.Contains(item, word) {
result = append(result, item)
}
}
}
return result
}
func simpleSearch(runes []rune, text string) []string {
exp := string(runes)
var result []string
if !strings.ContainsRune(exp, '|') {
helper := []string{exp}
result = append(singleSearch(helper, text))
} else {
expWords := strings.Split(exp, "|")
result = append(result, singleSearch(expWords, text)...)
}
return result
}
func brackets(regexp, text string) {
if text == "" || regexp == "" {
return
}
runes := []rune(regexp)
if runes[0] == '(' && runes[len(runes)-1] == ')' {
runes = runes[1 : len(runes)-1]
result := simpleSearch(runes, text)
for i, s := range result {
if !unicode.IsLetter(rune(s[len(s)-1])) {
s = s[0 : len(s)-1]
}
fmt.Printf("%d: %s\n", i+1, s)
}
}
}
func main() {
if len(os.Args) == 3 {
brackets(os.Args[1], os.Args[2])
}
}

7
test-go/solutions/hello_prog/main.go

@ -1,7 +0,0 @@
package main
import "fmt"
func main() {
fmt.Println("Hello World!")
}

51
test-go/solutions/hiddenp_prog/main.go

@ -1,51 +0,0 @@
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) != 3 {
return
}
first := os.Args[1]
second := os.Args[2]
if first == "" {
fmt.Println("1")
return
}
if second == "" {
fmt.Println("0")
return
}
i := 0
j := 0
count := 0
firstA := []rune(first)
secondA := []rune(second)
for i < len(first) {
for j < len(second) {
if firstA[i] == secondA[j] {
count++
i++
}
if i == len(first) {
break
}
j++
}
i++
}
if count == len(first) {
fmt.Println("1")
} else {
fmt.Println("0")
}
}

25
test-go/solutions/inter_prog/main.go

@ -1,25 +0,0 @@
package main
import (
"fmt"
"os"
"strings"
)
func result(s1 string, s2 string) string {
var rest []rune
for _, a := range s1 {
for _, b := range s2 {
if a == b && !strings.ContainsRune(string(rest), a) {
rest = append(rest, a)
}
}
}
return string(rest)
}
func main() {
if len(os.Args) == 3 {
fmt.Println(result(os.Args[1], os.Args[2]))
}
}

19
test-go/solutions/ispowerof2_prog/main.go

@ -1,19 +0,0 @@
package main
import (
"fmt"
"os"
"strconv"
)
// computes the logical bitwise AND of its operands.
func isPowerOf2(n int) bool {
return n != 0 && ((n & (n - 1)) == 0)
}
func main() {
if len(os.Args) == 2 {
nbr, _ := strconv.Atoi(os.Args[1])
fmt.Println(isPowerOf2(nbr))
}
}

16
test-go/solutions/lastword_prog/main.go

@ -1,16 +0,0 @@
package main
import (
"fmt"
"os"
"strings"
)
func main() {
if len(os.Args) == 2 {
words := strings.Fields(os.Args[1])
if len(words) > 0 {
fmt.Println(words[len(words)-1])
}
}
}

23
test-go/solutions/listat.go

@ -1,23 +0,0 @@
package solutions
// returs the node in a given position
func ListAt(l *NodeL, nbr int) *NodeL {
index := 0
count := 0
head := l
for head != nil {
index++
head = head.Next
}
if nbr <= index {
for l != nil {
if count == nbr {
return l
}
count++
l = l.Next
}
}
return nil
}

13
test-go/solutions/listclear.go

@ -1,13 +0,0 @@
package solutions
func ListClear(l *List) {
temp := l.Head
next := l.Head
for temp != nil {
next = temp.Next
temp = nil
temp = next
}
l.Head = nil
}

19
test-go/solutions/listfind.go

@ -1,19 +0,0 @@
package solutions
// finds the element and returns the first data from the node that is a string
func ListFind(l *List, ref interface{}, comp func(a, b interface{}) bool) *interface{} {
iterator := l.Head
for iterator != nil {
if comp(iterator.Data, ref) {
return &iterator.Data
}
iterator = iterator.Next
}
return nil
}
// defines for two elements the equality criteria
func CompStr(a, b interface{}) bool {
return a == b
}

28
test-go/solutions/listforeach.go

@ -1,28 +0,0 @@
package solutions
// applies a function in argument to each element of the linked list
func ListForEach(l *List, f func(*NodeL)) {
it := l.Head
for it != nil {
f(it)
it = it.Next
}
}
func Add2_node(node *NodeL) {
switch node.Data.(type) {
case int:
node.Data = node.Data.(int) + 2
case string:
node.Data = node.Data.(string) + "2"
}
}
func Subtract3_node(node *NodeL) {
switch node.Data.(type) {
case int:
node.Data = node.Data.(int) - 3
case string:
node.Data = node.Data.(string) + "-3"
}
}

43
test-go/solutions/listforeachif.go

@ -1,43 +0,0 @@
package solutions
// compare each element of the linked list to see if it is a String
func IsPositive_node(node *NodeL) bool {
switch node.Data.(type) {
case int, float32, float64, byte:
return node.Data.(int) > 0
case string, rune:
return false
}
return false
}
func IsNegative_node(node *NodeL) bool {
switch node.Data.(type) {
case int, float32, float64, byte:
return node.Data.(int) > 0
case string, rune:
return false
}
return false
}
func IsNumeric_node(node *NodeL) bool {
switch node.Data.(type) {
case int, float32, float64, byte:
return true
case string, rune:
return false
}
return false
}
// applies the function f on each string if the boolean function comp returns true
func ListForEachIf(l *List, f func(*NodeL), comp func(*NodeL) bool) {
it := l.Head
for it != nil {
if comp(it) {
f(it)
}
it = it.Next
}
}

15
test-go/solutions/listlast.go

@ -1,15 +0,0 @@
package solutions
// gives the last element of the list
func ListLast(l *List) interface{} {
if l.Head == nil {
return nil
}
for l.Head != nil {
if l.Head.Next == nil {
return l.Head.Data
}
l.Head = l.Head.Next
}
return l.Head.Data
}

10
test-go/solutions/listmerge.go

@ -1,10 +0,0 @@
package solutions
// merges the 2 lists in one (in the end of the first list)
func ListMerge(l1 *List, l2 *List) {
if l1.Head == nil {
l1.Head, l1.Tail = l2.Head, l2.Tail
return
}
l1.Tail.Next = l2.Head
}

22
test-go/solutions/listpushback.go

@ -1,22 +0,0 @@
package solutions
type NodeL struct {
Data interface{}
Next *NodeL
}
type List struct {
Head *NodeL
Tail *NodeL
}
func ListPushBack(l *List, data interface{}) {
n := &NodeL{Data: data}
if l.Head == nil {
l.Head = n
} else {
l.Tail.Next = n
}
l.Tail = n
}

14
test-go/solutions/listpushfront.go

@ -1,14 +0,0 @@
package solutions
// inserts node on the first position of the list
func ListPushFront(l *List, data interface{}) {
n := &NodeL{Data: data}
if l.Head == nil {
l.Head = n
return
}
n.Next = l.Head
l.Head = n
}

19
test-go/solutions/listremoveif.go

@ -1,19 +0,0 @@
package solutions
// removes all elements that are equal to the data_ref
func ListRemoveIf(l *List, data_ref interface{}) {
temp := l.Head
prev := l.Head
for temp != nil && temp.Data == data_ref {
l.Head = temp.Next
temp = l.Head
}
for temp != nil {
if temp.Data != data_ref {
prev = temp
}
prev.Next = temp.Next
temp = prev.Next
}
}

15
test-go/solutions/listreverse.go

@ -1,15 +0,0 @@
package solutions
func ListReverse(l *List) {
current := l.Head
prev := l.Head
prev = nil
for current != nil {
next := current.Next
current.Next = prev
prev = current
current = next
}
l.Head = prev
}

11
test-go/solutions/listsize.go

@ -1,11 +0,0 @@
package solutions
func ListSize(l *List) int {
count := 0
iterator := l.Head
for iterator != nil {
count++
iterator = iterator.Next
}
return count
}

28
test-go/solutions/listsort.go

@ -1,28 +0,0 @@
package solutions
func ListSort(l *NodeI) *NodeI {
head := l
if head == nil {
return nil
}
head.Next = ListSort(head.Next)
if head.Next != nil && head.Data > head.Next.Data {
head = move(head)
}
return head
}
func move(l *NodeI) *NodeI {
p := l
n := l.Next
ret := n
for n != nil && l.Data > n.Data {
p = n
n = n.Next
}
p.Next = l
l.Next = n
return ret
}

32
test-go/solutions/nbrconvertalpha_prog/main.go

@ -1,32 +0,0 @@
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
args := os.Args[1:]
if len(args) == 0 {
return
}
var upper bool
if args[0] == "--upper" {
upper = true
args = args[1:]
}
for _, arg := range args {
if nb, err := strconv.Atoi(arg); err != nil || nb < 1 || nb > 26 {
fmt.Print(" ")
} else {
if upper {
nb += 'A' - 1
} else {
nb += 'a' - 1
}
fmt.Printf("%c", rune(nb))
}
}
fmt.Println()
}

32
test-go/solutions/nenokku_prog/main.go

@ -1,32 +0,0 @@
package main
import (
"fmt"
"os"
"strings"
)
func main() {
var big string
args := os.Args[1:]
for _, arg := range args {
split := strings.Split(arg, " ")
ch := split[0]
small := split[1]
if ch == "x" {
break
}
if ch == "A" {
big += small
}
if ch == "?" {
if strings.Contains(big, small) {
fmt.Println("YES")
} else {
fmt.Println("NO")
}
}
}
}

7
test-go/solutions/onlya_prog/main.go

@ -1,7 +0,0 @@
package main
import "fmt"
func main() {
fmt.Print("a")
}

7
test-go/solutions/onlyz_prog/main.go

@ -1,7 +0,0 @@
package main
import "fmt"
func main() {
fmt.Print("z")
}

50
test-go/solutions/options_prog/main.go

@ -1,50 +0,0 @@
package main
import (
"fmt"
"os"
)
func printOptions(op [32]int, i int) {
for _, v := range op {
if i == 8 {
fmt.Print(" ")
i = 0
}
fmt.Print(v)
i++
}
fmt.Println()
}
func main() {
var options [32]int
pos := 1
size := len(os.Args)
if size < 2 {
fmt.Println("options: abcdefghijklmnopqrstuvwxyz")
} else {
for pos < size {
j := 1
if os.Args[pos][0] == '-' {
if os.Args[pos][1] == 'h' {
fmt.Println("options: abcdefghijklmnopqrstuvwxyz")
return
}
for j < len(os.Args[pos]) && os.Args[pos][j] >= 'a' && os.Args[pos][j] <= 'z' {
posOption := 'z' - os.Args[pos][j] + 6
options[posOption] = 1
j++
}
if j < len(os.Args[pos]) && os.Args[pos][j] <= 'a' && os.Args[pos][j] <= 'z' {
fmt.Println("Invalid Option")
return
}
j++
}
pos++
}
printOptions(options, 0)
}
}

10
test-go/solutions/paramcount_prog/main.go

@ -1,10 +0,0 @@
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println(len(os.Args) - 1)
}

20
test-go/solutions/piglatin_prog/main.go

@ -1,20 +0,0 @@
package main
import (
"fmt"
"os"
"strings"
)
func main() {
if len(os.Args) != 2 || os.Args[1] == "" {
return
}
s := os.Args[1]
vowel := strings.IndexAny(s, "aeiouAEIOU")
if vowel == -1 {
fmt.Println("No vowels")
} else {
fmt.Println(string(s[vowel:]) + string(s[:vowel]) + "ay")
}
}

22
test-go/solutions/pilot_prog/main.go

@ -1,22 +0,0 @@
package main
import "fmt"
type Pilot struct {
Name string
Life float32
Age int
Aircraft int
}
const Aircraft1 = 1
func main() {
donnie := Pilot{
Name: "Donnie",
Life: 100.0,
Age: 24,
Aircraft: Aircraft1,
}
fmt.Println(donnie)
}

22
test-go/solutions/point_prog/main.go

@ -1,22 +0,0 @@
package main
import "fmt"
type point struct {
x int
y int
}
func setPoint(ptr *point) {
ptr.x = 42
ptr.y = 21
}
func main() {
points := &point{}
setPoint(points)
fmt.Printf("x = %d, y = %d", points.x, points.y)
fmt.Println()
}

7
test-go/solutions/printalphabet_prog/main.go

@ -1,7 +0,0 @@
package main
import "fmt"
func main() {
fmt.Println("abcdefghijklmnopqrstuvwxyz")
}

8
test-go/solutions/printalphabetalt2_prog/main.go

@ -1,8 +0,0 @@
package main
import "fmt"
func main() {
fmt.Println("AbCdEfGhIjKlMnOpQrStUvWxYz")
fmt.Println("ZyXwVuTsRqPoNmLkJiHgFeDcBa")
}

8
test-go/solutions/printalphabetalt_prog/main.go

@ -1,8 +0,0 @@
package main
import "fmt"
func main() {
fmt.Println("aBcDeFgHiJkLmNoPqRsTuVwXyZ")
fmt.Println("zYxWvUtSrQpOnMlKjIhGfEdCbA")
}

7
test-go/solutions/printalphabetg_prog/main.go

@ -1,7 +0,0 @@
package main
import "fmt"
func main() {
fmt.Println("abcdefg")
}

7
test-go/solutions/printalt2_prog/main.go

@ -1,7 +0,0 @@
package main
import "fmt"
func main() {
fmt.Println("zaybxcwdveuftgshriqjpkolnm")
}

7
test-go/solutions/printalt_prog/main.go

@ -1,7 +0,0 @@
package main
import "fmt"
func main() {
fmt.Println("azbycxdwevfugthsirjqkplomn")
}

7
test-go/solutions/printaltu2_prog/main.go

@ -1,7 +0,0 @@
package main
import "fmt"
func main() {
fmt.Println("ZAYBXCWDVEUFTGSHRIQJPKOLNM")
}

7
test-go/solutions/printaltu_prog/main.go

@ -1,7 +0,0 @@
package main
import "fmt"
func main() {
fmt.Println("AZBYCXDWEVFUGTHSIRJQKPLOMN")
}

18
test-go/solutions/printbits_prog/main.go

@ -1,18 +0,0 @@
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
if len(os.Args) == 2 {
nbr, _ := strconv.Atoi(os.Args[1])
printBits(byte(nbr))
}
}
func printBits(octe byte) {
fmt.Printf("%08b", octe)
}

40
test-go/solutions/printchessboard_prog/main.go

@ -1,40 +0,0 @@
package main
import (
"fmt"
"os"
"strconv"
)
func solve(x, y int) {
for i := 0; i < x; i++ {
line := ""
for j := 0; j < y; j++ {
if i%2 == 0 && j%2 == 0 {
line += "#"
} else if i%2 == 0 && j%2 == 1 {
line += " "
} else if i%2 == 1 && j%2 == 1 {
line += "#"
} else {
line += " "
}
}
fmt.Println(line)
}
}
func main() {
args := os.Args[1:]
if len(args) != 2 {
fmt.Println("Error")
return
}
x, _ := strconv.Atoi(args[1])
y, _ := strconv.Atoi(args[0])
if x <= 0 || y <= 0 {
fmt.Println("Error")
} else {
solve(x, y)
}
}

7
test-go/solutions/printdigits_prog/main.go

@ -1,7 +0,0 @@
package main
import "fmt"
func main() {
fmt.Println("0123456789")
}

17
test-go/solutions/printhex_prog/main.go

@ -1,17 +0,0 @@
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
if len(os.Args) == 2 {
if i, err := strconv.Atoi(os.Args[1]); err == nil && i > 0 {
fmt.Printf("%x\n", i)
} else {
fmt.Println("ERROR")
}
}
}

12
test-go/solutions/printparams_prog/main.go

@ -1,12 +0,0 @@
package main
import (
"fmt"
"os"
)
func main() {
for _, a := range os.Args[1:] {
fmt.Println(a)
}
}

11
test-go/solutions/printprogramname_prog/main.go

@ -1,11 +0,0 @@
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
fmt.Println(filepath.Base(os.Args[0]))
}

17
test-go/solutions/printrevcomb_prog/main.go

@ -1,17 +0,0 @@
package main
import "fmt"
func main() {
for a := 9; a >= 2; a-- {
for b := a - 1; b >= 1; b-- {
for c := b - 1; c >= 0; c-- {
fmt.Printf("%d%d%d", a, b, c)
if a+b+c != 3 {
fmt.Print(", ")
}
}
}
}
fmt.Println()
}

7
test-go/solutions/printreversealphabet_prog/main.go

@ -1,7 +0,0 @@
package main
import "fmt"
func main() {
fmt.Println("zyxwvutsrqponmlkjihgfedcba")
}

8
test-go/solutions/printreversealphabetalt2_prog/main.go

@ -1,8 +0,0 @@
package main
import "fmt"
func main() {
fmt.Println("ZyXwVuTsRqPoNmLkJiHgFeDcBa")
fmt.Println("AbCdEfGhIjKlMnOpQrStUvWxYz")
}

8
test-go/solutions/printreversealphabetalt_prog/main.go

@ -1,8 +0,0 @@
package main
import "fmt"
func main() {
fmt.Println("zYxWvUtSrQpOnMlKjIhGfEdCbA")
fmt.Println("aBcDeFgHiJkLmNoPqRsTuVwXyZ")
}

7
test-go/solutions/printreversealphabetg_prog/main.go

@ -1,7 +0,0 @@
package main
import "fmt"
func main() {
fmt.Println("gfedcba")
}

33
test-go/solutions/printrot_prog/main.go

@ -1,33 +0,0 @@
package main
import (
"fmt"
"os"
)
func printAnswer(letter rune) {
answer := []rune{}
for i := letter; i <= 'z'; i++ {
answer = append(answer, i)
}
for j := 'a'; j < letter; j++ {
answer = append(answer, j)
}
fmt.Println(string(answer))
}
func main() {
if len(os.Args) == 2 {
letter := os.Args[1]
if len(letter) == 1 {
letterConverted := []rune(letter)
if letterConverted[0] >= 'a' && letterConverted[0] <= 'z' {
printAnswer(letterConverted[0])
}
} else {
fmt.Println()
}
} else {
fmt.Println()
}
}

87
test-go/solutions/raid3_prog/main.go

@ -1,87 +0,0 @@
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
// counts in the Cartesian coordinates x and y
func countXY(output []rune) (x, y int) {
countX := 0
countY := 0
flag := false
for _, s := range output {
if s == '\n' {
countY++
flag = true
} else if !flag {
countX++
}
}
return countX, countY
}
func determineInput(output []rune) {
x, y := countXY(output)
// the leftC and rightC -> position of the corners
// this will be to see what raid1 is being used
// for the lower left corner
leftC := ((x * y) + y - 1) - x
// for the lower right corner
rightC := (x * y) + y - 2
// for the upper right corner
rightUpC := x - 1
X := strconv.Itoa(x)
Y := strconv.Itoa(y)
result := isPipedWith(output, leftC, rightC, rightUpC, X, Y)
fmt.Println(strings.Join(result, " || "))
}
func isPipedWith(output []rune, leftC, rightC, rightUpC int, x, y string) []string {
result := []string{}
if output[0] == 'o' {
result = append(result, "[raid1a] ["+x+"] ["+y+"]")
} else if output[0] == '/' {
result = append(result, "[raid1b] ["+x+"] ["+y+"]")
} else if output[0] == 'A' {
if (output[rightUpC] == 'A' && output[rightC] == 'C') ||
(output[rightUpC] == 'A' && y == "1") ||
(x == "1" && y == "1") {
result = append(result, "[raid1c] ["+x+"] ["+y+"]")
}
if (output[rightUpC] == 'C' && output[leftC] == 'A') ||
(output[leftC] == 'A' && x == "1") ||
(x == "1" && y == "1") {
result = append(result, "[raid1d] ["+x+"] ["+y+"]")
}
if (output[leftC] == 'C' && x == "1") ||
(output[rightUpC] == 'C' && y == "1") ||
(output[rightUpC] == 'C' && output[leftC] == 'C') ||
(x == "1" && y == "1") {
result = append(result, "[raid1e] ["+x+"] ["+y+"]")
}
}
return result
}
func main() {
reader := bufio.NewReader(os.Stdin)
var output []rune
for {
input, _, err := reader.ReadRune()
if err != nil {
break
}
output = append(output, input)
}
if output[0] != 'o' && output[0] != '/' && output[0] != 'A' {
fmt.Println("Not a Raid function")
return
}
determineInput(output)
}

33
test-go/solutions/range_prog/main.go

@ -1,33 +0,0 @@
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
if len(os.Args) != 3 {
return
}
a, err := strconv.Atoi(os.Args[1])
if err != nil {
fmt.Println(err)
return
}
b, err := strconv.Atoi(os.Args[2])
if err != nil {
fmt.Println(err)
return
}
fmt.Print(a)
for b != a {
if a < b {
a++
} else {
a--
}
fmt.Print(" ", a)
}
fmt.Println()
}

64
test-go/solutions/rectangle_prog/main.go

@ -1,64 +0,0 @@
package main
import "fmt"
type point struct {
x int
y int
}
type rectangle struct {
upLeft point
downRight point
}
func defineRectangle(vPoint []point, n int) *rectangle {
xmin := vPoint[0].x
xmax := vPoint[0].x
ymin := vPoint[0].y
ymax := vPoint[0].y
ptr := &rectangle{}
for i := 0; i < n; i++ {
if vPoint[i].x < xmin {
xmin = vPoint[i].x
}
if vPoint[i].x > xmax {
xmax = vPoint[i].x
}
if vPoint[i].y < ymin {
ymin = vPoint[i].y
}
if vPoint[i].y > ymax {
ymax = vPoint[i].y
}
}
ptr.upLeft.x = xmin
ptr.upLeft.y = ymax
ptr.downRight.x = xmax
ptr.downRight.y = ymin
return ptr
}
func calcArea(ptr *rectangle) int {
return (ptr.upLeft.x - ptr.downRight.x) * (ptr.downRight.y - ptr.upLeft.y)
}
func main() {
vPoint := []point{}
rectangle := &rectangle{}
n := 7
for i := 0; i < n; i++ {
val := point{
x: i%2 + 1,
y: i + 2,
}
vPoint = append(vPoint, val)
}
rectangle = defineRectangle(vPoint, n)
fmt.Println("area of the rectangle:", calcArea(rectangle))
}

22
test-go/solutions/repeatalpha_prog/main.go

@ -1,22 +0,0 @@
package main
import (
"fmt"
"os"
"unicode"
)
func main() {
if len(os.Args) == 2 {
for _, r := range os.Args[1] {
fmt.Printf("%c", r)
if unicode.IsLetter(r) {
rep := unicode.ToLower(r) - 'a'
for i := 0; i < int(rep); i++ {
fmt.Printf("%c", r)
}
}
}
fmt.Println()
}
}

33
test-go/solutions/reverserange_prog/main.go

@ -1,33 +0,0 @@
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
if len(os.Args) != 3 {
return
}
a, err := strconv.Atoi(os.Args[1])
if err != nil {
fmt.Println(err)
return
}
b, err := strconv.Atoi(os.Args[2])
if err != nil {
fmt.Println(err)
return
}
fmt.Print(b)
for a != b {
if b < a {
b++
} else {
b--
}
fmt.Print(" ", b)
}
fmt.Println()
}

21
test-go/solutions/reversestrcap_prog/main.go

@ -1,21 +0,0 @@
package main
import (
"fmt"
"os"
"unicode"
)
func main() {
for _, arg := range os.Args[1:] {
arg := []rune(arg)
for j, r := range arg {
if j+1 == len(arg) || arg[j+1] == ' ' {
arg[j] = unicode.ToUpper(r)
} else {
arg[j] = unicode.ToLower(r)
}
}
fmt.Println(string(arg))
}
}

12
test-go/solutions/revparams_prog/main.go

@ -1,12 +0,0 @@
package main
import (
"fmt"
"os"
)
func main() {
for i := len(os.Args) - 1; i >= 1; i-- {
fmt.Println(os.Args[i])
}
}

20
test-go/solutions/revwstr_prog/main.go

@ -1,20 +0,0 @@
package main
import (
"fmt"
"os"
"strings"
)
func main() {
if len(os.Args) == 2 {
a := strings.Split(os.Args[1], " ")
for i := len(a) - 1; i >= 0; i-- {
fmt.Print(a[i])
if i != 0 {
fmt.Print(" ")
}
}
fmt.Println()
}
}

31
test-go/solutions/robottoorigin_prog/main.go

@ -1,31 +0,0 @@
package main
import (
"fmt"
"os"
)
func solve(s string) bool {
x := 0
y := 0
for _, r := range s {
switch r {
case 'L':
x--
case 'R':
x++
case 'U':
y++
case 'D':
y--
}
}
return x == 0 && y == 0
}
func main() {
if len(os.Args) == 2 {
fmt.Println(solve(os.Args[1]))
}
}

66
test-go/solutions/romannumbers_prog/main.go

@ -1,66 +0,0 @@
package main
import (
"fmt"
"os"
"strconv"
"strings"
)
type roman struct {
num int
romanDigit string
}
func main() {
if len(os.Args) == 2 {
nbr, err := strconv.Atoi(os.Args[1])
if err != nil || nbr >= 4000 || nbr == 0 {
fmt.Println("ERROR: can not convert to roman digit")
return
}
patter := []roman{
{num: 1000, romanDigit: "M"},
{num: 900, romanDigit: "CM"},
{num: 500, romanDigit: "D"},
{num: 400, romanDigit: "CD"},
{num: 100, romanDigit: "C"},
{num: 90, romanDigit: "XC"},
{num: 50, romanDigit: "L"},
{num: 40, romanDigit: "XL"},
{num: 10, romanDigit: "X"},
{num: 9, romanDigit: "IX"},
{num: 5, romanDigit: "V"},
{num: 4, romanDigit: "IV"},
{num: 1, romanDigit: "I"},
}
sumRoman, romandigit := print(nbr, patter)
fmt.Println(strings.TrimSuffix(sumRoman, "+"))
fmt.Println(romandigit)
}
}
func print(nbr int, patter []roman) (string, string) {
var sumRomanDigit, result string
for _, v := range patter {
for nbr >= v.num {
sumRomanDigit += v.romanDigit + "+"
result += v.romanDigit
nbr -= v.num
}
}
sumRomanDigit = formatsum(sumRomanDigit, patter)
return sumRomanDigit, result
}
func formatsum(a string, patter []roman) string {
result2 := strings.Split(a, "+")
for i, v := range result2 {
if len(v) == 2 {
result2[i] = fmt.Sprintf("(%s-%s)", string(result2[i][1]), string(result2[i][0]))
}
}
a = strings.Join(result2, "+")
return a
}

31
test-go/solutions/rostring_prog/main.go

@ -1,31 +0,0 @@
package main
import (
"fmt"
"os"
"strings"
)
func deleteExtraSpaces(a []string) []string {
var res []string
for _, v := range a {
if v != "" {
res = append(res, v)
}
}
return res
}
func main() {
if len(os.Args) == 2 {
words := strings.Split(os.Args[1], " ")
words = deleteExtraSpaces(words)
if len(words) >= 1 {
for _, v := range words[1:] {
fmt.Print(v, " ")
}
fmt.Print(words[0])
}
}
fmt.Println()
}

28
test-go/solutions/rot13_prog/main.go

@ -1,28 +0,0 @@
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) == 2 {
for _, r := range os.Args[1] {
if r >= 'a' && r <= 'z' {
if r >= 'a'+13 {
r -= 13
} else {
r += 13
}
} else if r >= 'A' && r <= 'Z' {
if r >= 'A'+13 {
r -= 13
} else {
r += 13
}
}
fmt.Printf("%c", r)
}
fmt.Println()
}
}

37
test-go/solutions/rotatevowels_prog/main.go

@ -1,37 +0,0 @@
package main
import (
"fmt"
"os"
"strings"
)
func main() {
var a1, a2, rev []rune
for _, arg := range os.Args[1:] {
for _, k := range arg {
if strings.ContainsRune("aeiouAEIOU", k) {
a1 = append(a1, k)
}
}
}
for i := len(a1) - 1; i >= 0; i-- {
rev = append(rev, a1[i])
}
m := 0
for i, arg := range os.Args[1:] {
for _, j := range arg {
if strings.ContainsRune("aeiouAEIOU", j) {
a2 = append(a2, rev[m])
m++
} else {
a2 = append(a2, j)
}
}
if i != len(os.Args)-1 {
a2 = append(a2, ' ')
}
}
fmt.Println(string(a2))
}

67
test-go/solutions/rpncalc_prog/main.go

@ -1,67 +0,0 @@
package main
import (
"fmt"
"os"
"strconv"
"strings"
)
func deleteExtraSpaces(a []string) (res []string) {
for _, v := range a {
if v != "" {
res = append(res, v)
}
}
return
}
func main() {
if len(os.Args) != 2 {
fmt.Println("Error")
return
}
var values []int
op := strings.Split(os.Args[1], " ")
op = deleteExtraSpaces(op)
for _, v := range op {
val, err := strconv.Atoi(v)
if err == nil {
values = append(values, val)
continue
}
n := len(values)
if n < 2 {
fmt.Println("Error")
return
}
switch v {
case "+":
values[n-2] += values[n-1]
values = values[:n-1]
case "-":
values[n-2] -= values[n-1]
values = values[:n-1]
case "*":
values[n-2] *= values[n-1]
values = values[:n-1]
case "/":
values[n-2] /= values[n-1]
values = values[:n-1]
case "%":
values[n-2] %= values[n-1]
values = values[:n-1]
default:
fmt.Println("Error")
return
}
}
if len(values) == 1 {
fmt.Println(values[0])
} else {
fmt.Println("Error")
}
}

18
test-go/solutions/searchreplace_prog/main.go

@ -1,18 +0,0 @@
package main
import (
"fmt"
"os"
"strings"
)
func main() {
if len(os.Args) == 4 {
fmt.Println(strings.Map(func(r rune) rune {
if r == []rune(os.Args[2])[0] {
return []rune(os.Args[3])[0]
}
return r
}, os.Args[1]))
}
}

16
test-go/solutions/sortedlistmerge.go

@ -1,16 +0,0 @@
package solutions
func SortedListMerge(l1 *NodeI, l2 *NodeI) *NodeI {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
if l1.Data <= l2.Data {
l1.Next = SortedListMerge(l1.Next, l2)
return l1
}
l2.Next = SortedListMerge(l1, l2.Next)
return l2
}

25
test-go/solutions/sortlistinsert.go

@ -1,25 +0,0 @@
package solutions
// structures for the linked lists
type NodeI struct {
Data int
Next *NodeI
}
func SortListInsert(l *NodeI, data_ref int) *NodeI {
n := &NodeI{Data: data_ref}
n.Next = nil
if l == nil || l.Data >= n.Data {
n.Next = l
return n
}
temp := l
for temp.Next != nil && temp.Next.Data < n.Data {
temp = temp.Next
}
n.Next = temp.Next
temp.Next = n
return l
}

Some files were not shown because too many files changed in this diff diff.show_more

Loading…
Cancel
Save