├── .gitignore
├── README.md
├── go
├── algorithms
│ ├── binary_search.go
│ ├── binary_search_test.go
│ ├── matrix.go
│ └── matrix_test.go
├── challenges
│ └── arrays
│ │ ├── grading_students.go
│ │ ├── grading_students_test.go
│ │ ├── max_occurrences.go
│ │ ├── max_occurrences_test.go
│ │ ├── max_subarray.go
│ │ └── max_subarray_test.go
├── datastructures
│ ├── linked_list.go
│ └── linked_list_test.go
├── go.mod
└── main.go
└── java
├── pom.xml
└── src
├── main
└── java
│ └── iniciante
│ ├── algorithms
│ └── palindome
│ │ └── Palindome.java
│ ├── conditionals
│ ├── a
│ │ └── PrintIfMultiple.java
│ ├── b
│ │ ├── Toll.java
│ │ └── Vehicle.java
│ └── c
│ │ ├── AreaCalculation.java
│ │ ├── Circle.java
│ │ ├── Shape.java
│ │ ├── Square.java
│ │ └── Triangle.java
│ ├── loops
│ ├── a
│ │ └── IncreasingLoop.java
│ ├── b
│ │ └── DecreasingLoop.java
│ └── c
│ │ └── WhileLoop.java
│ └── string
│ └── operations
│ ├── a
│ └── CountAndCase.java
│ ├── b
│ └── Substring.java
│ └── c
│ └── StartsEndsWith.java
└── test
└── java
└── iniciante
├── algorithms
└── palindrome
│ └── PalindromeTest.java
├── conditionals
├── a
│ └── PrintIfMultipleTest.java
├── b
│ └── TollTest.java
└── c
│ └── AreaCalculationTest.java
├── loops
├── a
│ └── IncreasingLoopTest.java
├── b
│ └── DecreasingLoopTest.java
└── c
│ └── WhileLoopTest.java
└── string
└── operations
├── a
└── CountAndCaseTest.java
├── b
└── SubstringTest.java
└── c
└── StartsEndsWithTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | ##############################
2 | ## Java
3 | ##############################
4 | .mtj.tmp/
5 | *.class
6 | *.jar
7 | *.war
8 | *.ear
9 | *.nar
10 | hs_err_pid*
11 |
12 | ##############################
13 | ## Maven
14 | ##############################
15 | target/
16 | pom.xml.tag
17 | pom.xml.releaseBackup
18 | pom.xml.versionsBackup
19 | pom.xml.next
20 | pom.xml.bak
21 | release.properties
22 | dependency-reduced-pom.xml
23 | buildNumber.properties
24 | .mvn/timing.properties
25 | .mvn/wrapper/maven-wrapper.jar
26 |
27 | ##############################
28 | ## Gradle
29 | ##############################
30 | bin/
31 | build/
32 | .gradle
33 | .gradletasknamecache
34 | gradle-app.setting
35 | !gradle-wrapper.jar
36 |
37 | ##############################
38 | ## IntelliJ
39 | ##############################
40 | out/
41 | .idea/
42 | .idea_modules/
43 | *.iml
44 | *.ipr
45 | *.iws
46 |
47 | ##############################
48 | ## Eclipse
49 | ##############################
50 | .settings/
51 | bin/
52 | tmp/
53 | .metadata
54 | .classpath
55 | .project
56 | *.tmp
57 | *.bak
58 | *.swp
59 | *~.nib
60 | local.properties
61 | .loadpath
62 | .factorypath
63 |
64 | ##############################
65 | ## NetBeans
66 | ##############################
67 | nbproject/private/
68 | build/
69 | nbbuild/
70 | dist/
71 | nbdist/
72 | nbactions.xml
73 | nb-configuration.xml
74 |
75 | ##############################
76 | ## Visual Studio Code
77 | ##############################
78 | .vscode/
79 | .code-workspace
80 |
81 | ##############################
82 | ## OS X
83 | ##############################
84 | .DS_Store
85 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Testes Técnicos
2 |
3 | Testes técnicos para iniciantes.
4 |
5 | A explicação dos testes é em português, mas as variáveis, os nomes dos métodos e
6 | demais elementos dentro do software são em inglês.
7 |
8 | ## Como utilizar:
9 | 1. Crie uma nova branch a partir da `main`:
10 | `git checkout -b minhas_respostas`
11 | 2. Leia as instruções do teste e complete o código nos arquivos que possuem a anotação `// TODO`
12 | 3. Rode os testes da linguagem conforme instruções de cada linguagem abaixo
13 | 4. Não precisa fazer o push da sua branch para o repositório principal. Deixe local.
14 | 5. Atualize sua branch regularmente com os novos testes sempre que houver
15 | `git checkout main`
16 | `git pull`
17 | `git checkout minhas_repostas`
18 | `git merge main`
19 |
20 | ## Linguagens suportadas:
21 | - Java 11+
22 |
23 | ## Instruções para testes em Java
24 |
25 | ### Instalar Java 11 ou maior
26 |
27 | Verifique se o java está instalado em seu computador:
28 | `java -version`
29 |
30 | Caso não esteja instalado, seguir as instruções em
31 | > https://www.java.com/en/download/help/download_options.html
32 |
33 | ### Instalar maven:
34 |
35 | Maven é uma ferramenta que auxilia no uso de dependências, e ajuda a rodar os testes.
36 | Verifique se maven está instalado:
37 | `mvn -version`
38 |
39 | Caso não esteja instalado, seguir as instruções em
40 | > https://maven.apache.org/install.html
41 |
42 | ### Testes
43 |
44 | Para rodar os testes em java (a partir da raíz do projeto):
45 | `mvn test -f java`
46 |
47 | Os testes disponíveis são:
48 | - Condicionais
49 | - Loops
50 | - Manipulação de strings
51 | - Algorítmos
52 |
53 | Complete o código nos arquivos abaixo.
54 | Depois, para cada arquivo completado, rode os testes para verificar.
55 |
56 | #### Condicionais
57 | - src/java/iniciante/condicionals/a/PrintIfMultiple.java
58 | - src/java/iniciante/condicionals/b/Toll.java
59 | - src/java/iniciante/condicionals/c/AreaCalculation.java
60 |
61 | #### Loops
62 | - src/java/iniciante/loops/a/IncreasingLoop.java
63 | - src/java/iniciante/loops/b/DecreasingLoop.java
64 | - src/java/iniciante/loops/c/WhileLoop.java
65 |
66 | #### Manipulação de Strings
67 | - src/java/iniciante/string/operations/a/CountAndCase.java
68 | - src/java/iniciante/string/operations/b/Substring.java
69 | - src/java/iniciante/string/operations/c/StartsEndsWith.java
70 |
71 | #### Algorítmos
72 | - src/java/iniciante/algorithms/palindrome/Palindrome.java
73 |
74 | Os arquivos de teste ficam em
75 | - src/test/iniciante/{package}/{ClassName}Test.java
76 | - exemplo: src/test/iniciante/algorithms/palindrome/PalindromeTest.java
--------------------------------------------------------------------------------
/go/algorithms/binary_search.go:
--------------------------------------------------------------------------------
1 | package algorithms
2 |
3 | import "sort"
4 |
5 | // BinarySearch searches for a number in an ordered array
6 | // accepts the number to be found and an ordered array
7 | // return the index of the number, or -1 if not found
8 | func BinarySearch(number int, arr []int) int {
9 | min := 0
10 | max := len(arr) - 1
11 |
12 | for {
13 | if max < min {
14 | return -1
15 | }
16 |
17 | guess := (min + max) / 2
18 | if arr[guess] == number {
19 | return guess
20 | }
21 |
22 | if arr[guess] < number {
23 | min = guess + 1
24 | continue
25 | }
26 |
27 | max = guess - 1
28 | }
29 | }
30 |
31 | // BinarySearchInt32Unsorted searches for a number in an unordered array
32 | // accepts the number to be found and an unordered array
33 | // return the index of the number, or -1 if not found
34 | func BinarySearchInt32Unsorted(m []int32, number int32) int {
35 | sort.Slice(m, func(i, j int) bool {
36 | return m[i] < m[j]
37 | })
38 | i := sort.Search(len(m), func(i int) bool {
39 | return m[i] >= number
40 | })
41 | if i < len(m) && m[i] == number {
42 | return i
43 | }
44 | return -1
45 | }
46 |
--------------------------------------------------------------------------------
/go/algorithms/binary_search_test.go:
--------------------------------------------------------------------------------
1 | package algorithms
2 |
3 | import "testing"
4 |
5 | func TestBinarySearch(t *testing.T) {
6 | primes := []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}
7 | number := 67
8 | expected := 18
9 |
10 | result := BinarySearch(number, primes)
11 | if result != expected {
12 | t.Errorf("Error, expected %v, got %v", expected, result)
13 | }
14 | }
15 |
16 | func TestBinarySearchNotMatch(t *testing.T) {
17 | primes := []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}
18 | number := 38
19 | expected := -1
20 |
21 | result := BinarySearch(number, primes)
22 | if result != expected {
23 | t.Errorf("Error, expected %v, got %v", expected, result)
24 | }
25 | }
26 |
27 | func TestBinarySearchSingletonListMatch(t *testing.T) {
28 | primes := []int{2}
29 | number := 2
30 | expected := 0
31 |
32 | result := BinarySearch(number, primes)
33 | if result != expected {
34 | t.Errorf("Error, expected %v, got %v", expected, result)
35 | }
36 | }
37 |
38 | func TestBinarySearchSingletonListNotMatch(t *testing.T) {
39 | primes := []int{2}
40 | number := 10
41 | expected := -1
42 |
43 | result := BinarySearch(number, primes)
44 | if result != expected {
45 | t.Errorf("Error, expected %v, got %v", expected, result)
46 | }
47 | }
48 |
49 | func TestBinarySearchEmptyList(t *testing.T) {
50 | primes := make([]int, 0)
51 | number := 38
52 | expected := -1
53 |
54 | result := BinarySearch(number, primes)
55 | if result != expected {
56 | t.Errorf("Error, expected %v, got %v", expected, result)
57 | }
58 | }
59 |
60 | func TestBinarySearchNegativeNumbersMatch(t *testing.T) {
61 | primes := []int{-97, -89, -83, -79, -73, -71, -67, -61, -59, -53, -47, -43, -41, -37, -31, -29, -23, -19, -17, -13, -11, -7, -5, -3, -2}
62 | number := -67
63 | expected := 6
64 |
65 | result := BinarySearch(number, primes)
66 | if result != expected {
67 | t.Errorf("Error, expected %v, got %v", expected, result)
68 | }
69 | }
70 |
71 | func TestBinarySearchNegativeNumbersNotMatch(t *testing.T) {
72 | primes := []int{-97, -89, -83, -79, -73, -71, -67, -61, -59, -53, -47, -43, -41, -37, -31, -29, -23, -19, -17, -13, -11, -7, -5, -3, -2}
73 | number := -10
74 | expected := -1
75 |
76 | result := BinarySearch(number, primes)
77 | if result != expected {
78 | t.Errorf("Error, expected %v, got %v", expected, result)
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/go/algorithms/matrix.go:
--------------------------------------------------------------------------------
1 | package algorithms
2 |
3 | import (
4 | "math"
5 | )
6 |
7 | // FindCenters accepts a matrix and a radius,
8 | // and return all possible centers of the
9 | // matrix that fits in the radius.
10 | //
11 | // it is returned as a list of tuples
12 | // ex: [[2 2] [2 3] [3 2] [3 3]]
13 | // each tuple indicates the x and the y
14 | // indexes respectively
15 | func FindCenters(matrix [][]int, r int) [][]int {
16 | var centers [][]int
17 |
18 | // find the "horizontal" center (rows)
19 | xCenter := int(math.Ceil(float64(len(matrix))/2) - 1)
20 |
21 | // if the radius is bigger than the half
22 | // of the length, then return empty centers
23 | if xCenter-r < 0 {
24 | return centers
25 | }
26 |
27 | // find the "vertical" center (items of the rows)
28 | yCenter := int(math.Ceil(float64(len(matrix[xCenter]))/2) - 1)
29 |
30 | // if the radius is bigger than the half
31 | // of the length, then return empty centers
32 | if yCenter-r < 0 {
33 | return centers
34 | }
35 |
36 | // create placeholder for the indexes
37 | // and append the first xCenter and yCenter
38 | x := make([]int, 0)
39 | y := make([]int, 0)
40 | x = append(x, xCenter)
41 | y = append(y, yCenter)
42 |
43 | // scan x half up
44 | for i := xCenter - 1; i >= 0; i-- {
45 | if i-r < 0 {
46 | break
47 | }
48 | x = append(x, i)
49 | }
50 | // scan x half down
51 | for i := xCenter + 1; i < len(matrix); i++ {
52 | if i+r >= len(matrix) {
53 | break
54 | }
55 | x = append(x, i)
56 | }
57 |
58 | // scan y half left
59 | for i := yCenter - 1; i >= 0; i-- {
60 | if i-r < 0 {
61 | break
62 | }
63 | y = append(y, i)
64 | }
65 | // scan y half right
66 | for i := yCenter + 1; i < len(matrix[xCenter]); i++ {
67 | if i+r >= len(matrix[xCenter]) {
68 | break
69 | }
70 | y = append(y, i)
71 | }
72 |
73 | // build the response
74 | for _, v := range x {
75 | for _, vv := range y {
76 | centers = append(centers, []int{v, vv})
77 | }
78 | }
79 |
80 | return centers
81 | }
82 |
--------------------------------------------------------------------------------
/go/algorithms/matrix_test.go:
--------------------------------------------------------------------------------
1 | package algorithms
2 |
3 | import "testing"
4 |
5 | func TestMatrixFindCentersEven(t *testing.T) {
6 | m := [][]int{
7 | {1, 1, 1, 1, 1, 1},
8 | {2, 2, 2, 2, 2, 2},
9 | {3, 3, 3, 3, 3, 3},
10 | {4, 4, 4, 4, 4, 4},
11 | {5, 5, 5, 5, 5, 5},
12 | {6, 6, 6, 6, 6, 6},
13 | }
14 | radius := 2
15 | expected := [][]int{{2, 2}, {2, 3}, {3, 2}, {3, 3}}
16 | result := FindCenters(m, radius)
17 |
18 | for i, row := range expected {
19 | for j := range row {
20 | if result[i][j] != expected[i][j] {
21 | t.Errorf("Error, expected %v, got %v", expected, result)
22 | }
23 | }
24 | }
25 | }
26 |
27 | func TestMatrixFindCentersOdd(t *testing.T) {
28 | m := [][]int{
29 | {1, 1, 1, 1, 1, 1},
30 | {2, 2, 2, 2, 2, 2},
31 | {3, 3, 3, 3, 3, 3},
32 | {4, 4, 4, 4, 4, 4},
33 | {5, 5, 5, 5, 5, 5},
34 | }
35 | radius := 2
36 | expected := [][]int{{2, 2}, {2, 3}}
37 | result := FindCenters(m, radius)
38 |
39 | for i, row := range expected {
40 | for j := range row {
41 | if result[i][j] != expected[i][j] {
42 | t.Errorf("Error, expected %v, got %v", expected, result)
43 | }
44 | }
45 | }
46 | }
47 |
48 | func TestMatrixFindCentersLargeRadius(t *testing.T) {
49 | m := [][]int{
50 | {1, 1, 1, 1, 1, 1},
51 | {2, 2, 2, 2, 2, 2},
52 | {3, 3, 3, 3, 3, 3},
53 | {4, 4, 4, 4, 4, 4},
54 | {5, 5, 5, 5, 5, 5},
55 | }
56 | radius := 3
57 | expected := [][]int{}
58 | result := FindCenters(m, radius)
59 |
60 | if len(result) > 0 {
61 | t.Errorf("Error, expected %v, got %v", len(expected), len(result))
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/go/challenges/arrays/grading_students.go:
--------------------------------------------------------------------------------
1 | package arrays
2 |
3 | import "sort"
4 |
5 | func GradingStudents(grades []int32) []int32 {
6 | result := make([]int32, 0)
7 |
8 | // create ordered multiples
9 | multiples := make([]int32, 0)
10 | for i := int32(5); i <= 100; i += 5 {
11 | multiples = append(multiples, i)
12 | }
13 |
14 | // for each grade
15 | for _, g := range grades {
16 | // falling grade, append itself
17 | if g < 38 {
18 | result = append(result, g)
19 | continue
20 | }
21 |
22 | // search for the index in the multiples that v would fit
23 | r := int32(sort.Search(len(multiples), func(i int) bool {
24 | return multiples[int32(i)] >= g
25 | }))
26 |
27 | // apply rounding rules (negated)
28 | if int(r) == len(multiples) || multiples[r]-g >= 3 {
29 | result = append(result, g)
30 | continue
31 | }
32 | result = append(result, multiples[r])
33 | }
34 |
35 | return result
36 | }
37 |
--------------------------------------------------------------------------------
/go/challenges/arrays/grading_students_test.go:
--------------------------------------------------------------------------------
1 | package arrays
2 |
3 | import "testing"
4 |
5 | func TestGradingStudentsBaseCase(t *testing.T) {
6 | arr := []int32{73, 67, 38, 33}
7 | expected := []int32{75, 67, 40, 33}
8 |
9 | result := GradingStudents(arr)
10 | for i := 0; i < len(expected); i++ {
11 | if result[i] != expected[i] {
12 | t.Errorf("Error, expected %v, got %v", expected[i], result[i])
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/go/challenges/arrays/max_occurrences.go:
--------------------------------------------------------------------------------
1 | package arrays
2 |
3 | import "github.com/danielbonilha/testes-tecnicos/algorithms"
4 |
5 | // MaxOccurrences given an array, count the occurrences
6 | // of a given number and return it
7 | //
8 | // Example:
9 | //
10 | // Array: [1, 2, 2, 3, 3, 3, 3, 4, 4, 4]
11 | // Number: 3
12 | // Expected: 4 (occurrences)
13 | func MaxOccurrences(arr []int, number int) int {
14 | index := algorithms.BinarySearch(number, arr)
15 | if index == -1 {
16 | return 0
17 | }
18 |
19 | count := 1
20 |
21 | // count items to the left of the index
22 | for i := index - 1; i >= 0; i-- {
23 | if arr[i] != number {
24 | break
25 | }
26 | count += 1
27 | }
28 |
29 | // count items to the right of the index
30 | for i := index + 1; i < len(arr); i++ {
31 | if arr[i] != number {
32 | break
33 | }
34 | count += 1
35 | }
36 |
37 | return count
38 | }
39 |
--------------------------------------------------------------------------------
/go/challenges/arrays/max_occurrences_test.go:
--------------------------------------------------------------------------------
1 | package arrays
2 |
3 | import "testing"
4 |
5 | func TestMaxOccurrences(t *testing.T) {
6 | arr := []int{1, 2, 2, 3, 3, 3, 3, 4, 4, 4}
7 | number := 3
8 | expected := 4
9 |
10 | result := MaxOccurrences(arr, number)
11 | if result != expected {
12 | t.Errorf("Error, expected %v, got %v", expected, result)
13 | }
14 | }
15 |
16 | func TestMaxOccurrencesNotFound(t *testing.T) {
17 | arr := []int{1, 2, 2, 3, 3, 3, 3, 4, 4, 4}
18 | number := 5
19 | expected := 0
20 |
21 | result := MaxOccurrences(arr, number)
22 | if result != expected {
23 | t.Errorf("Error, expected %v, got %v", expected, result)
24 | }
25 | }
26 |
27 | func TestMaxOccurrencesEdgeCase(t *testing.T) {
28 | arr := []int{1, 2, 2, 3, 3, 3, 3, 4, 4, 4}
29 | number := 1
30 | expected := 1
31 |
32 | result := MaxOccurrences(arr, number)
33 | if result != expected {
34 | t.Errorf("Error, expected %v, got %v", expected, result)
35 | }
36 | }
37 |
38 | func TestMaxOccurrencesEmptyList(t *testing.T) {
39 | arr := []int{}
40 | number := 1
41 | expected := 0
42 |
43 | result := MaxOccurrences(arr, number)
44 | if result != expected {
45 | t.Errorf("Error, expected %v, got %v", expected, result)
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/go/challenges/arrays/max_subarray.go:
--------------------------------------------------------------------------------
1 | package arrays
2 |
3 | // MaxSubArray given an array, find the biggest
4 | // sum of contiguous elements and return it
5 | //
6 | // Example:
7 | //
8 | // arr := []int{1, -2, 2, -3, -3, 3, 3, -4, 4, 4, -5}
9 | // expected := 10 (sum of 3, 3, -4, 4, 4)
10 | func MaxSubArray(arr []int) int {
11 | max := 0
12 | current := 0
13 |
14 | for i := 0; i < len(arr); i++ {
15 | current = current + arr[i]
16 | if current > max {
17 | max = current
18 | }
19 | if current < 0 {
20 | current = 0
21 | }
22 | }
23 |
24 | return max
25 | }
26 |
--------------------------------------------------------------------------------
/go/challenges/arrays/max_subarray_test.go:
--------------------------------------------------------------------------------
1 | package arrays
2 |
3 | import "testing"
4 |
5 | func TestMaxSubArray(t *testing.T) {
6 | arr := []int{1, -2, 2, -3, -3, 3, 3, -4, 4, 4, -5}
7 | expected := 10
8 |
9 | result := MaxSubArray(arr)
10 | if result != expected {
11 | t.Errorf("Error, expected %v, got %v", expected, result)
12 | }
13 | }
14 |
15 | func TestMaxSubArraySingleton(t *testing.T) {
16 | arr := []int{1, -4, -5}
17 | expected := 1
18 |
19 | result := MaxSubArray(arr)
20 | if result != expected {
21 | t.Errorf("Error, expected %v, got %v", expected, result)
22 | }
23 | }
24 |
25 | func TestMaxSubArrayOnlyNegatives(t *testing.T) {
26 | arr := []int{-1, -2, -3, -4, -5}
27 | expected := 0
28 |
29 | result := MaxSubArray(arr)
30 | if result != expected {
31 | t.Errorf("Error, expected %v, got %v", expected, result)
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/go/datastructures/linked_list.go:
--------------------------------------------------------------------------------
1 | package datastructures
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | )
7 |
8 | type (
9 | LinkedList struct {
10 | head *item
11 | tail *item
12 | size int
13 | }
14 |
15 | item struct {
16 | data any
17 | previous *item
18 | next *item
19 | }
20 | )
21 |
22 | // NewLinkedList creates a new LinkedList
23 | // using the provided data at head node
24 | // Costs O(1)
25 | func NewLinkedList(data any) LinkedList {
26 | item := &item{
27 | data: data,
28 | previous: nil,
29 | next: nil,
30 | }
31 |
32 | return LinkedList{
33 | size: 1,
34 | head: item,
35 | tail: item,
36 | }
37 | }
38 |
39 | // InsertHead insert new data to the head
40 | // Costs O(1)
41 | func (l *LinkedList) InsertHead(data any) {
42 | // create an item with the data;
43 | // points to the head as next item
44 | // have no previous item
45 | newLinkedListItem := &item{
46 | data: data,
47 | previous: nil,
48 | next: l.head,
49 | }
50 | // assign the previous node of the head to the new item
51 | if l.head != nil {
52 | l.head.previous = newLinkedListItem
53 | }
54 | // assign the head to the new item
55 | l.head = newLinkedListItem
56 | l.size += 1
57 | }
58 |
59 | // InsertTail insert new data to the tail
60 | // Costs O(1)
61 | func (l *LinkedList) InsertTail(data any) {
62 | // create an item with the data
63 | // that points to the tail as previous item
64 | // and that has no next item
65 | newLinkedListItem := &item{
66 | data: data,
67 | previous: l.tail,
68 | next: nil,
69 | }
70 | // assign the next node of the tail to the new item
71 | if l.tail != nil {
72 | l.tail.next = newLinkedListItem
73 | }
74 | // assign the head to the new item
75 | l.tail = newLinkedListItem
76 | l.size += 1
77 | }
78 |
79 | // DeleteHead changes the head reference to the
80 | // second element of the list
81 | // Costs O(1)
82 | func (l *LinkedList) DeleteHead() error {
83 | if l.size == 0 {
84 | return errors.New("stack underflow")
85 | }
86 |
87 | if l.size == 1 {
88 | l.head = nil
89 | l.tail = nil
90 | l.size = 0
91 | return nil
92 | }
93 |
94 | l.head = l.head.next
95 | l.head.previous = nil
96 | l.size -= 1
97 |
98 | return nil
99 | }
100 |
101 | func (l *LinkedList) DeleteTail() error {
102 | if l.size == 0 {
103 | return errors.New("stack underflow")
104 | }
105 |
106 | if l.size == 1 {
107 | l.head = nil
108 | l.tail = nil
109 | l.size = 0
110 | return nil
111 | }
112 |
113 | l.tail = l.tail.previous
114 | l.tail.next = nil
115 | l.size -= 1
116 |
117 | return nil
118 | }
119 |
120 | func (l *LinkedList) Size() int {
121 | return l.size
122 | }
123 |
124 | func (l *LinkedList) Display() {
125 | node := l.head
126 | for node != nil {
127 | fmt.Println(node.data)
128 | node = node.next
129 | }
130 | }
131 |
--------------------------------------------------------------------------------
/go/datastructures/linked_list_test.go:
--------------------------------------------------------------------------------
1 | package datastructures
2 |
3 | import "testing"
4 |
5 | // tests if outcome is "Inserted" > "Original"
6 | func TestLinkedListInsertHead(t *testing.T) {
7 | n := NewLinkedList("Original")
8 | n.InsertHead("Inserted")
9 |
10 | // test length
11 | if n.Size() != 2 {
12 | t.Errorf("got %d; want %d", n.Size(), 2)
13 | }
14 |
15 | // test head is "Inserted"
16 | if n.head.data.(string) != "Inserted" {
17 | t.Errorf("got %s; want %s", n.head.data.(string), "Inserted")
18 | }
19 |
20 | // test tail is "Original"
21 | if n.tail.data.(string) != "Original" {
22 | t.Errorf("got %s; want %s", n.tail.data.(string), "Original")
23 | }
24 |
25 | // test head must not have a previous
26 | if n.head.previous != nil {
27 | t.Errorf("got %v; want nil", n.head.previous)
28 | }
29 |
30 | // test tail must not have a next
31 | if n.tail.next != nil {
32 | t.Errorf("got %v; want nil", n.tail.next)
33 | }
34 |
35 | // test head must have "Original" as next
36 | if n.head.next.data.(string) != "Original" {
37 | t.Errorf("got %v; want %s", n.head.next.data.(string), "Original")
38 | }
39 |
40 | // test tail must have "Inserted" as previous
41 | if n.tail.previous.data.(string) != "Inserted" {
42 | t.Errorf("got %v; want %s", n.tail.next.data.(string), "Inserted")
43 | }
44 | }
45 |
46 | // tests if outcome is "Original" > "Inserted"
47 | func TestLinkedListInsertTail(t *testing.T) {
48 | n := NewLinkedList("Original")
49 | n.InsertTail("Inserted")
50 |
51 | // test length
52 | if n.Size() != 2 {
53 | t.Errorf("got %d; want %d", n.Size(), 2)
54 | }
55 |
56 | // test head is "Original"
57 | if n.head.data.(string) != "Original" {
58 | t.Errorf("got %s; want %s", n.head.data.(string), "Original")
59 | }
60 |
61 | // test tail is "Inserted"
62 | if n.tail.data.(string) != "Inserted" {
63 | t.Errorf("got %s; want %s", n.tail.data.(string), "Inserted")
64 | }
65 |
66 | // test head must not have a previous
67 | if n.head.previous != nil {
68 | t.Errorf("got %v; want nil", n.head.previous)
69 | }
70 |
71 | // test tail must not have a next
72 | if n.tail.next != nil {
73 | t.Errorf("got %v; want nil", n.tail.next)
74 | }
75 |
76 | // test head must have "Inserted" as next
77 | if n.head.next.data.(string) != "Inserted" {
78 | t.Errorf("got %v; want %s", n.head.next.data.(string), "Inserted")
79 | }
80 |
81 | // test tail must have "Original" as previous
82 | if n.tail.previous.data.(string) != "Original" {
83 | t.Errorf("got %v; want %s", n.head.next.data.(string), "Original")
84 | }
85 | }
86 |
87 | // from original "First" > "Second" > "Third"
88 | // tests if outcome is "Second" > "Third"
89 | func TestLinkedListDeleteHeadWithThreeItems(t *testing.T) {
90 | n := NewLinkedList("Second")
91 | n.InsertHead("First")
92 | n.InsertTail("Third")
93 |
94 | err := n.DeleteHead()
95 | if err != nil {
96 | t.Errorf("got %s; want nil", err.Error())
97 | }
98 |
99 | // test length
100 | if n.Size() != 2 {
101 | t.Errorf("got %d; want %d", n.Size(), 2)
102 | }
103 |
104 | // test head is "Second"
105 | if n.head.data.(string) != "Second" {
106 | t.Errorf("got %s; want %s", n.head.data.(string), "Second")
107 | }
108 |
109 | // test tail is "Third"
110 | if n.tail.data.(string) != "Third" {
111 | t.Errorf("got %s; want %s", n.tail.data.(string), "Third")
112 | }
113 |
114 | // test head must not have a previous
115 | if n.head.previous != nil {
116 | t.Errorf("got %v; want nil", n.head.previous)
117 | }
118 |
119 | // test tail must not have a next
120 | if n.tail.next != nil {
121 | t.Errorf("got %v; want nil", n.tail.next)
122 | }
123 |
124 | // test head must have "Third" as next
125 | if n.head.next.data.(string) != "Third" {
126 | t.Errorf("got %v; want %s", n.head.next.data.(string), "Third")
127 | }
128 |
129 | // test tail must have "Second" as previous
130 | if n.tail.previous.data.(string) != "Second" {
131 | t.Errorf("got %v; want %s", n.tail.next.data.(string), "Second")
132 | }
133 | }
134 |
135 | // from original "First" > "Second" > "Third"
136 | // tests if outcome is "First" > "Second"
137 | func TestLinkedListDeleteTailWithThreeItems(t *testing.T) {
138 | n := NewLinkedList("Second")
139 | n.InsertHead("First")
140 | n.InsertTail("Third")
141 |
142 | err := n.DeleteTail()
143 | if err != nil {
144 | t.Errorf("got %s; want nil", err.Error())
145 | }
146 |
147 | // test length
148 | if n.Size() != 2 {
149 | t.Errorf("got %d; want %d", n.Size(), 2)
150 | }
151 |
152 | // test head is "First"
153 | if n.head.data.(string) != "First" {
154 | t.Errorf("got %s; want %s", n.head.data.(string), "First")
155 | }
156 |
157 | // test tail is "Second"
158 | if n.tail.data.(string) != "Second" {
159 | t.Errorf("got %s; want %s", n.tail.data.(string), "Second")
160 | }
161 |
162 | // test head must not have a previous
163 | if n.head.previous != nil {
164 | t.Errorf("got %v; want nil", n.head.previous)
165 | }
166 |
167 | // test tail must not have a next
168 | if n.tail.next != nil {
169 | t.Errorf("got %v; want nil", n.tail.next)
170 | }
171 |
172 | // test head must have "Second" as next
173 | if n.head.next.data.(string) != "Second" {
174 | t.Errorf("got %v; want %s", n.head.next.data.(string), "Second")
175 | }
176 |
177 | // test tail must have "First" as previous
178 | if n.tail.previous.data.(string) != "First" {
179 | t.Errorf("got %v; want %s", n.tail.next.data.(string), "First")
180 | }
181 | }
182 |
183 | func TestDisplayLinkedList(t *testing.T) {
184 | n := NewLinkedList("Second")
185 | n.InsertHead("First")
186 | n.InsertTail("Third")
187 |
188 | n.Display()
189 | }
190 |
--------------------------------------------------------------------------------
/go/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/danielbonilha/testes-tecnicos
2 |
3 | go 1.19
4 |
--------------------------------------------------------------------------------
/go/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "sort"
6 | "strconv"
7 | )
8 |
9 | func main() {
10 | timeConversion("12:05:45AM")
11 | }
12 |
13 | func timeConversion(s string) string {
14 | suffix := s[:]
15 | hourStr := s[:2]
16 | if suffix == "AM" {
17 | if hourStr == "12" {
18 | hourStr = "00"
19 | }
20 | return hourStr + s[2:len(s)-2]
21 | }
22 | hour, _ := strconv.Atoi(hourStr)
23 | if hour != 12 {
24 | hour += 12
25 | }
26 | hourStr = strconv.Itoa(hour)
27 | fmt.Println(hourStr + s[2:len(s)-2])
28 | return hourStr + s[2:len(s)-2]
29 | }
30 |
31 | func GuessingGame() {
32 | var s string
33 | fmt.Printf("Pick an integer from 0 to 100.\n")
34 | answer := sort.Search(100, func(i int) bool {
35 | fmt.Printf("Is your number <= %d? ", i)
36 | fmt.Scanf("%s", &s)
37 | return s != "" && s[0] == 'y'
38 | })
39 | fmt.Printf("Your number is %d.\n", answer)
40 | }
41 |
42 | func birthdayCakeCandles(candles []int32) int32 {
43 | if len(candles) == 0 {
44 | return 0
45 | }
46 | if len(candles) == 1 {
47 | return 1
48 | }
49 |
50 | sort.Slice(candles, func(i, j int) bool { return candles[i] < candles[j] })
51 | lastIndex := len(candles) - 1
52 | lastCandle := candles[lastIndex]
53 |
54 | count := int32(0)
55 | for i := lastIndex; candles[i] == lastCandle; i-- {
56 | count += 1
57 | }
58 | return count
59 | }
60 |
61 | func solution(queries [][]string) []string {
62 | db := NewDB()
63 | result := make([]string, 0)
64 |
65 | for _, q := range queries {
66 | if q[0] == "SET_OR_INC" {
67 | r := db.Set(q[1], q[2], q[3])
68 | result = append(result, r)
69 | continue
70 | }
71 |
72 | if q[0] == "GET" {
73 | r := db.Get(q[1], q[2])
74 | result = append(result, r)
75 | continue
76 | }
77 |
78 | if q[0] == "DELETE" {
79 | r := db.Delete(q[1], q[2])
80 | result = append(result, strconv.FormatBool(r))
81 | }
82 |
83 | if q[0] == "TOP_N_KEYS" {
84 | r := db.TopKeys(q[1])
85 | result = append(result, r)
86 | }
87 |
88 | }
89 | return result
90 | }
91 |
92 | type (
93 | DB interface {
94 | Get(key, field string) string
95 | Set(key, field, value string) string
96 | Delete(key, field string) bool
97 | TopKeys(n string) string
98 | }
99 |
100 | InMemoryDB struct {
101 | m map[string]map[string]string
102 | stats map[string]int
103 | }
104 | )
105 |
106 | func NewDB() DB {
107 | return &InMemoryDB{
108 | m: map[string]map[string]string{},
109 | stats: map[string]int{}}
110 | }
111 |
112 | func (db *InMemoryDB) Get(key, field string) string {
113 | record, ok := db.m[key]
114 | if !ok {
115 | return ""
116 | }
117 | value, ok := record[field]
118 | if !ok {
119 | return ""
120 | }
121 |
122 | return value
123 | }
124 |
125 | func (db *InMemoryDB) Set(key, field, value string) string {
126 | db.addStats(key)
127 | record, ok := db.m[key]
128 | if !ok {
129 | db.m[key] = map[string]string{
130 | field: value,
131 | }
132 | return value
133 | }
134 |
135 | vStr, ok := record[field]
136 | if !ok {
137 | db.m[key][field] = value
138 | return value
139 | }
140 |
141 | v, _ := strconv.Atoi(vStr)
142 | valueInt, _ := strconv.Atoi(value)
143 | total := strconv.Itoa(v + valueInt)
144 | db.m[key][field] = total
145 | return total
146 |
147 | }
148 |
149 | func (db *InMemoryDB) Delete(key, field string) bool {
150 | record, ok := db.m[key]
151 | if !ok {
152 | return false
153 | }
154 |
155 | _, ok = record[field]
156 | if !ok {
157 | return false
158 | }
159 |
160 | db.addStats(key)
161 | delete(record, field)
162 | if len(record) == 0 {
163 | delete(db.m, key)
164 | delete(db.stats, key)
165 | }
166 | return true
167 | }
168 |
169 | func (db *InMemoryDB) TopKeys(n string) string {
170 | var result string
171 |
172 | m := db.sortMap()
173 |
174 | i := 0
175 | nInt, _ := strconv.Atoi(n)
176 | for k, v := range m {
177 | if i == nInt {
178 | break
179 | }
180 | result = result + k + "(" + strconv.Itoa(v) + "), "
181 | i++
182 | }
183 | result = result[:len(result)-2]
184 | return result
185 | }
186 |
187 | func (db *InMemoryDB) addStats(key string) {
188 | stats, ok := db.stats[key]
189 | if !ok {
190 | db.stats[key] = 1
191 | } else {
192 | db.stats[key] = stats + 1
193 | }
194 | }
195 |
196 | type Pair struct {
197 | Key string
198 | Value int
199 | }
200 |
201 | type PairList []Pair
202 |
203 | func (p PairList) Len() int { return len(p) }
204 | func (p PairList) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
205 | func (p PairList) Less(i, j int) bool { return p[i].Value < p[j].Value }
206 |
207 | func (db *InMemoryDB) sortMap() map[string]int {
208 | p := make(PairList, len(db.stats))
209 | result := make(map[string]int)
210 |
211 | i := 0
212 | for k, v := range db.stats {
213 | p[i] = Pair{k, v}
214 | i++
215 | }
216 |
217 | sort.Sort(sort.Reverse(p))
218 | for _, k := range p {
219 | result[k.Key] = k.Value
220 | }
221 | db.stats = result
222 | return result
223 | }
224 |
--------------------------------------------------------------------------------
/java/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 | 4.0.0
6 |
7 | testes.tecnicos
8 | java
9 | 1.0-SNAPSHOT
10 |
11 | https://github.com/danielbonilha/testes-tecnicos
12 |
13 |
14 | UTF-8
15 | 11
16 | 11
17 | 11
18 |
19 |
20 |
21 |
22 | org.junit.jupiter
23 | junit-jupiter-api
24 | 5.7.2
25 | test
26 |
27 |
28 | org.junit.jupiter
29 | junit-jupiter-engine
30 | 5.7.2
31 | test
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 | maven-clean-plugin
40 | 3.1.0
41 |
42 |
43 | maven-resources-plugin
44 | 3.0.2
45 |
46 |
47 | maven-compiler-plugin
48 | 3.8.0
49 |
50 |
51 | maven-surefire-plugin
52 | 2.22.1
53 |
54 |
55 | maven-jar-plugin
56 | 3.0.2
57 |
58 |
59 | maven-install-plugin
60 | 2.5.2
61 |
62 |
63 | maven-deploy-plugin
64 | 2.8.2
65 |
66 |
67 | maven-site-plugin
68 | 3.7.1
69 |
70 |
71 | maven-project-info-reports-plugin
72 | 3.0.0
73 |
74 |
75 |
76 |
77 |
78 |
--------------------------------------------------------------------------------
/java/src/main/java/iniciante/algorithms/palindome/Palindome.java:
--------------------------------------------------------------------------------
1 | package iniciante.algorithms.palindome;
2 |
3 | public class Palindome {
4 | public Boolean isPalindrome(String text) {
5 | // TODO
6 | return null;
7 | }
8 | }
9 |
10 | /*
11 | # Problema
12 |
13 | Palindrome significa palíndromo, que é uma palavra ou frase
14 | que pode ser lida no seu sentido normal, da esquerda para a direita,
15 | bem como no sentido contrário, da direita para a esquerda,
16 | sem que haja mudança nas palavras que a formam e no seu significado.
17 |
18 | No sentido normal da frase, o palíndromo deverá ser lido da forma habitual.
19 | Na leitura de palíndromos do fim para o início deverão ser consideradas
20 | apenas as letras e números, sendo desconsiderados espaços entre palavras,
21 | maísculas e minúsculas, sinais de pontuação e de acentuação,
22 | bem como outros sinais gráficos.
23 |
24 | # Dicas
25 |
26 | Comece resolvendo pequenos problemas primeiro, tais como o
27 | de espaçamento e letras maiúsculas/minúsculas, depois parta
28 | para os problemas mais complexos como pontuação, acentuação
29 | e sinais gráficos.
30 |
31 | # Exemplos
32 | "A grama é amarga"
33 | */
--------------------------------------------------------------------------------
/java/src/main/java/iniciante/conditionals/a/PrintIfMultiple.java:
--------------------------------------------------------------------------------
1 | package iniciante.conditionals.a;
2 |
3 | public class PrintIfMultiple {
4 | public void printMultiples(int n) {
5 | // TODO
6 | }
7 | }
8 |
9 | /*
10 | # Problema
11 |
12 | Dado um número inteiro n:
13 | - Imprima "Multiplo de 3" se o número for múltiplo de 3, somente.
14 | - Imprima "Multiplo de 5" se o número for múltiplo de 5, somente.
15 | - Imprima "Multiplo de 3 e 5" se o número for múltiplo de 3 e 5.
16 | - Imprima "Nenhum multiplo" em qualquer outro caso.
17 |
18 | # Dicas
19 |
20 | Múltiplos, em programação, são calculados através do resto de uma divisão.
21 | Se a divisão de um número A por um outro número B tiver RESTO
22 | igual à 0 (zero), então o número A é múltiplo do número B.
23 |
24 | Em programação usa-se o operador % (modulus) para tal cálculo.
25 | O modulus retorna sempre o RESTO de uma divisão, e não o resultado da divisão.
26 |
27 | # Exemplos
28 | 15 % 3 retorna 0 (zero), pois o resultado da divisão de 15 por 3 tem ZERO de resto.
29 | 16 % 3 retorna 1 (um), pois o resultado da divisão de 16 por 3 tem UM de resto.
30 | */
--------------------------------------------------------------------------------
/java/src/main/java/iniciante/conditionals/b/Toll.java:
--------------------------------------------------------------------------------
1 | package iniciante.conditionals.b;
2 |
3 | public class Toll {
4 | public double calculateTollPayment(Vehicle vehicle) {
5 | // TODO
6 | return -1.00;
7 | }
8 | }
9 |
10 | /*
11 | Toll é um pedágio.
12 |
13 | # Problema:
14 |
15 | Dado um veículo, retorne o valor à ser pago no pedágio.
16 | Regras:
17 | - Veículos com 2 rodas não pagam pedágio.
18 | - Veículos de 4 rodas pagam R$5,20.
19 | - Veículos de 6 ou mais rodas pagam R$2,60 a cada 2 rodas, limitado à R$10,00.
20 | - Veículo oficiais não pagam pedágio, independente da quantidade de rodas.
21 |
22 |
23 | # Dicas:
24 |
25 | Analise a classe Vehicle. Os atributos da classe irão auxiliar
26 | nas tomadas de decisão.
27 |
28 | # Exemplos
29 | Um veículo não-oficial com 4 rodas retorna 5.20.
30 | */
--------------------------------------------------------------------------------
/java/src/main/java/iniciante/conditionals/b/Vehicle.java:
--------------------------------------------------------------------------------
1 | package iniciante.conditionals.b;
2 |
3 | public class Vehicle {
4 |
5 | // número de rodas
6 | private final int numberOfWheels;
7 |
8 | // se é ou não oficial
9 | private final boolean isOfficial;
10 |
11 | public Vehicle(int numberOfWheels, boolean isOfficial) {
12 | this.numberOfWheels = numberOfWheels;
13 | this.isOfficial = isOfficial;
14 | }
15 |
16 | public int getNumberOfWheels() {
17 | return numberOfWheels;
18 | }
19 |
20 | public boolean isOfficial() {
21 | return isOfficial;
22 | }
23 | }
--------------------------------------------------------------------------------
/java/src/main/java/iniciante/conditionals/c/AreaCalculation.java:
--------------------------------------------------------------------------------
1 | package iniciante.conditionals.c;
2 |
3 | public class AreaCalculation {
4 | private final double pi = 3.14;
5 | public double calcArea(Shape shape) {
6 | // TODO
7 | return -1.00;
8 | }
9 | }
10 |
11 | /*
12 | Shape é uma forma.
13 |
14 | Shape é definida como uma interface, que possui dois métodos:
15 | - int getMultiplier, que retorna um multiplicador.
16 | - int getMeasure, que retorna uma medida (um lado, no caso do quadrado e do
17 | triângulo, e um raio no caso do círculo).
18 |
19 | # Problema:
20 |
21 | Retorne área da forma vezes seu multiplicador.
22 | Se o multiplicador for menor ou igual à zero, lançar uma exception do
23 | tipo IllegalArgumentException.
24 |
25 | # Dicas:
26 |
27 | A forma (shape) pode ser um quadrado, um círculo ou um triângulo.
28 | Cada qual tem seu cálculo da área, baseado em sua medida (lado ou raio).
29 |
30 | A área de um quadrado é medida pela medida * 2.
31 | A área de um triângulo é medida pela medida * medida / 2.
32 | A área de um círculo é medida pela medida elevada ao quadrado * Pi.
33 |
34 | O valor de Pi já foi declarado para você.
35 |
36 | Em java, o valor de A ao quadrado Pode ser calculado pelo pacote Math.pow().
37 |
38 | Para descobrir qual o tipo da classe que representa a forma vc deve usar
39 | o "instanceof".
40 | */
41 |
--------------------------------------------------------------------------------
/java/src/main/java/iniciante/conditionals/c/Circle.java:
--------------------------------------------------------------------------------
1 | package iniciante.conditionals.c;
2 |
3 | public class Circle implements Shape {
4 | private final int measure;
5 | private final int multiplier;
6 |
7 | public Circle(int measure, int multiplier) {
8 | this.measure = measure;
9 | this.multiplier = multiplier;
10 | }
11 |
12 | @Override
13 | public int getMeasure() {
14 | return measure;
15 | }
16 |
17 | @Override
18 | public int getMultiplier() {
19 | return multiplier;
20 | }
21 | }
--------------------------------------------------------------------------------
/java/src/main/java/iniciante/conditionals/c/Shape.java:
--------------------------------------------------------------------------------
1 | package iniciante.conditionals.c;
2 |
3 | public interface Shape {
4 | int getMeasure();
5 | int getMultiplier();
6 | }
7 |
--------------------------------------------------------------------------------
/java/src/main/java/iniciante/conditionals/c/Square.java:
--------------------------------------------------------------------------------
1 | package iniciante.conditionals.c;
2 |
3 | public class Square implements Shape {
4 | private final int measure;
5 | private final int multiplier;
6 |
7 | public Square(int measure, int multiplier) {
8 | this.measure = measure;
9 | this.multiplier = multiplier;
10 | }
11 |
12 | @Override
13 | public int getMeasure() {
14 | return measure;
15 | }
16 |
17 | @Override
18 | public int getMultiplier() {
19 | return multiplier;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/java/src/main/java/iniciante/conditionals/c/Triangle.java:
--------------------------------------------------------------------------------
1 | package iniciante.conditionals.c;
2 |
3 | public class Triangle implements Shape {
4 | private final int measure;
5 | private final int multiplier;
6 |
7 | public Triangle(int measure, int multiplier) {
8 | this.measure = measure;
9 | this.multiplier = multiplier;
10 | }
11 |
12 | @Override
13 | public int getMeasure() {
14 | return measure;
15 | }
16 |
17 | @Override
18 | public int getMultiplier() {
19 | return multiplier;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/java/src/main/java/iniciante/loops/a/IncreasingLoop.java:
--------------------------------------------------------------------------------
1 | package iniciante.loops.a;
2 |
3 | import java.util.List;
4 |
5 | public class IncreasingLoop {
6 | public Integer sumItems(List items) {
7 | // TODO
8 | return -1;
9 | }
10 | }
11 |
12 | /*
13 | # Problema:
14 |
15 | Retorne a soma de todos os números maiores que '10' da lista 'items'.
16 |
17 | # Dicas:
18 |
19 | Será preciso realizar um loop sobre a lista, utilizando a notação
20 | for (int i = 0; i < items.size(); i++) { ... }
21 | ou
22 | for (int i : items) { ... }
23 |
24 | # Exemplos
25 | Items [0, 5, 10, 15, 20] retorna 45, pois é a soma de 10, 15 e 20.
26 | */
--------------------------------------------------------------------------------
/java/src/main/java/iniciante/loops/b/DecreasingLoop.java:
--------------------------------------------------------------------------------
1 | package iniciante.loops.b;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public class DecreasingLoop {
7 | public List reverseItems(List items) {
8 | List reversedItems = new ArrayList<>();
9 | // TODO
10 | return reversedItems;
11 | }
12 | }
13 |
14 | /*
15 | # Problema:
16 |
17 | Retorne uma nova lista de inteiros na ordem inversa da lista 'items'
18 |
19 | # Dicas:
20 |
21 | Será preciso realizar um loop decrescente sobre a lista, utilizando a notação
22 | for (int i = items.size() - 1; i >= 0; i--) { ... }
23 |
24 | Para adicionar um item na nova lista use 'reversedItems.add(...)'
25 |
26 | # Exemplos
27 | Items [0, 5, 10, 15, 20] retorna [20, 15, 10, 5, 0].
28 | */
--------------------------------------------------------------------------------
/java/src/main/java/iniciante/loops/c/WhileLoop.java:
--------------------------------------------------------------------------------
1 | package iniciante.loops.c;
2 |
3 | import java.util.Iterator;
4 |
5 | public class WhileLoop {
6 | public int countItems(Iterator items) {
7 | // TODO
8 | return -1;
9 | }
10 | }
11 |
12 | /*
13 | # Problema:
14 |
15 | Retorne a quantidade de items na lista.
16 |
17 | # Dicas:
18 |
19 | Será preciso utilizar a notação 'while (items.hasNext) { ... }'
20 | Iterator é uma interface, que possui os méteodos
21 | 'hasNext()', que retorna true ou false, se tiver ou não mais elementos na lista
22 | 'next()' que retora o próximo elemento da lista
23 |
24 | # Exemplos
25 | [0, 5, 10, 15, 20] retorna 5
26 | */
--------------------------------------------------------------------------------
/java/src/main/java/iniciante/string/operations/a/CountAndCase.java:
--------------------------------------------------------------------------------
1 | package iniciante.string.operations.a;
2 |
3 | public class CountAndCase {
4 | public String manipulate(String first, String second) {
5 | // TODO
6 | return "";
7 | }
8 | }
9 |
10 | /*
11 | Strings são palavras ou textos, compostas pela combinação de 1 ou mais caracteres.
12 | Case significa se a letra está maiúscula ou minúscula.
13 | "Uppercase" significa todas as letras são maiúsculas.
14 | "Lowercase" significa todas as letras são minúsculas.
15 |
16 | # Problema
17 |
18 | Dado uma String A e B, retorne uma ÚNICA string que concatene:
19 | - A soma da contagem de caracteres de cada string.
20 | - A primeira string com todas as letras maiúsculas.
21 | - A segunda string com a todas letra minúsculas.
22 |
23 | # Dicas
24 |
25 | Concatenar é juntar uma string com a outra.
26 | Concatenar "amora" com "abacaxi" resulta em "amoraabacaxi".
27 |
28 | O tamanho de uma string é calculado pelo método .lenght().
29 |
30 | Para converter todas as letras para maiúsculas utilize .toUpperCase().
31 | Para converter todas as letras para maiúsculas utilize .toLowerCase().
32 |
33 | # Exemplos
34 |
35 | String 1: Amora
36 | String 2: Abacaxi
37 |
38 | Retorna: 12AMORAabacaxi
39 | */
--------------------------------------------------------------------------------
/java/src/main/java/iniciante/string/operations/b/Substring.java:
--------------------------------------------------------------------------------
1 | package iniciante.string.operations.b;
2 |
3 | public class Substring {
4 | public String pieceOfString(String text) {
5 | // TODO
6 | return null;
7 | }
8 | }
9 |
10 | /*
11 | Strings são compostos por chars.
12 | Substrings partes de uma String, ou seja, um subconjunto de chars.
13 |
14 | # Problema
15 |
16 | Dado uma String A, retorne uma nova string sem as 3 primeiras letras, e sem as 2 últimas letras.
17 |
18 | # Dicas
19 |
20 | Cada char na String possui um índex. A contagem inicia no índex zero.
21 | A palavra "uva" possui 3 chars,
22 | sendo o char 0 correspondente à letra "u", o char 1 à letra "v" e o char 2 à letra "a".
23 |
24 | O método substring pode receber 1 ou 2 parâmetros.
25 | O primeiro parâmetro é o index inicial (incluso), e o segundo o índex final (não incluso).
26 |
27 | Se um índice for utilizado e a palavra não conter o índice (por ser pequena), uma
28 | java.lang.StringIndexOutOfBoundsException será lançada.
29 |
30 | # Exemplos
31 |
32 | "uva".substring(1) retorna "va", pois o índice 1 indica o início na letra "v".
33 | "uva".substring(1,2) retorna "v", pois o índice 1 indica o início na letra "v",
34 | e o índice 2 indica o final da palavra na letra "u", mas de forma exlusiva (exclui a letra u).
35 | */
--------------------------------------------------------------------------------
/java/src/main/java/iniciante/string/operations/c/StartsEndsWith.java:
--------------------------------------------------------------------------------
1 | package iniciante.string.operations.c;
2 |
3 | public class StartsEndsWith {
4 | // inicia com vogal?
5 | public Boolean startsWith(String text) {
6 | // TODO
7 | return null;
8 | }
9 |
10 | // terminal com vogal?
11 | public Boolean endsWith(String text) {
12 | // TODO
13 | return null;
14 | }
15 | }
16 |
17 | /*
18 | # Problema
19 |
20 | Dado uma String A, verifique, no primeiro método,
21 | se ele inicia com uma vogal.
22 |
23 | No segundo método, se termina com vogal.
24 |
25 | Retorne true ou false.
26 |
27 | # Dicas
28 |
29 | Utilize os métodos "startsWith()" e "endsWith".
30 |
31 | # Exemplos
32 |
33 | "uva".startsWith("u") retorna true.
34 | */
--------------------------------------------------------------------------------
/java/src/test/java/iniciante/algorithms/palindrome/PalindromeTest.java:
--------------------------------------------------------------------------------
1 | package iniciante.algorithms.palindrome;
2 |
3 | import iniciante.algorithms.palindome.Palindome;
4 | import iniciante.conditionals.b.Toll;
5 | import iniciante.conditionals.b.Vehicle;
6 | import org.junit.jupiter.api.Test;
7 |
8 | import static org.junit.jupiter.api.Assertions.assertEquals;
9 |
10 | public class PalindromeTest
11 | {
12 | private final Palindome palindrome = new Palindome();
13 |
14 | @Test
15 | public void simpleTest()
16 | {
17 | Boolean expected = true;
18 | String text = "arara";
19 |
20 | Boolean result = palindrome.isPalindrome(text);
21 | assertEquals(expected, result);
22 | }
23 |
24 | @Test
25 | public void upperCasedTest()
26 | {
27 | Boolean expected = true;
28 | String text = "Osso";
29 |
30 | Boolean result = palindrome.isPalindrome(text);
31 | assertEquals(expected, result);
32 | }
33 |
34 | @Test
35 | public void withSpacesTest()
36 | {
37 | Boolean expected = true;
38 | String text = "a grama é amarga";
39 |
40 | Boolean result = palindrome.isPalindrome(text);
41 | assertEquals(expected, result);
42 | }
43 |
44 | @Test
45 | public void withNumbersTest()
46 | {
47 | Boolean expected = true;
48 | String text = "20/02/2002";
49 |
50 | Boolean result = palindrome.isPalindrome(text);
51 | assertEquals(expected, result);
52 | }
53 |
54 | @Test
55 | public void complexPhraseTest()
56 | {
57 | Boolean expected = true;
58 | String text = "Aí, Lima falou: 'Olá, família!'";
59 |
60 | Boolean result = palindrome.isPalindrome(text);
61 | assertEquals(expected, result);
62 | }
63 |
64 |
65 | @Test
66 | public void notPalindromeTest()
67 | {
68 | Boolean expected = false;
69 | String text = "Não sou palíndromo";
70 |
71 | Boolean result = palindrome.isPalindrome(text);
72 | assertEquals(expected, result);
73 | }
74 | }
--------------------------------------------------------------------------------
/java/src/test/java/iniciante/conditionals/a/PrintIfMultipleTest.java:
--------------------------------------------------------------------------------
1 | package iniciante.conditionals.a;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.BeforeEach;
5 | import org.junit.jupiter.api.Test;
6 |
7 | import java.io.ByteArrayOutputStream;
8 | import java.io.PrintStream;
9 |
10 | import static org.junit.jupiter.api.Assertions.assertEquals;
11 |
12 | public class PrintIfMultipleTest {
13 | private final PrintStream standardOut = System.out;
14 | private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream();
15 | private final PrintIfMultiple printIfMultiple = new PrintIfMultiple();
16 |
17 | @BeforeEach
18 | public void setUp() {
19 | System.setOut(new PrintStream(outputStreamCaptor));
20 | }
21 |
22 | @AfterEach
23 | public void tearDown() {
24 | System.setOut(standardOut);
25 | }
26 |
27 | @Test
28 | public void multipleOf3Only()
29 | {
30 | printIfMultiple.printMultiples(6);
31 | assertEquals("Multiplo de 3", outputStreamCaptor.toString().trim());
32 | }
33 |
34 | @Test
35 | public void multipleOf5Only()
36 | {
37 | printIfMultiple.printMultiples(20);
38 | assertEquals("Multiplo de 5", outputStreamCaptor.toString().trim());
39 | }
40 |
41 | @Test
42 | public void multipleOf3And5()
43 | {
44 | printIfMultiple.printMultiples(30);
45 | assertEquals("Multiplo de 3 e 5", outputStreamCaptor.toString().trim());
46 | }
47 |
48 | @Test
49 | public void multipleOfNone()
50 | {
51 | printIfMultiple.printMultiples(11);
52 | assertEquals("Nenhum multiplo", outputStreamCaptor.toString().trim());
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/java/src/test/java/iniciante/conditionals/b/TollTest.java:
--------------------------------------------------------------------------------
1 | package iniciante.conditionals.b;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import static org.junit.jupiter.api.Assertions.assertEquals;
6 |
7 | public class TollTest
8 | {
9 | private final Toll toll = new Toll();
10 |
11 | @Test
12 | public void citizenBike()
13 | {
14 | double expectedPayment = 0.00;
15 | Vehicle citizenBike = new Vehicle(2, false);
16 |
17 | double actualPayment = toll.calculateTollPayment(citizenBike);
18 | assertEquals(expectedPayment, actualPayment);
19 | }
20 |
21 | @Test
22 | public void policeBike()
23 | {
24 | double expectedPayment = 0.00;
25 | Vehicle policeBike = new Vehicle(2, true);
26 |
27 | double actualPayment = toll.calculateTollPayment(policeBike);
28 | assertEquals(expectedPayment, actualPayment);
29 | }
30 |
31 | @Test
32 | public void familyCar()
33 | {
34 | double expectedPayment = 5.20;
35 | Vehicle familyCar = new Vehicle(4, false);
36 |
37 | double actualPayment = toll.calculateTollPayment(familyCar);
38 | assertEquals(expectedPayment, actualPayment);
39 | }
40 |
41 | @Test
42 | public void policeCar()
43 | {
44 | double expectedPayment = 0.00;
45 | Vehicle policeCar = new Vehicle(4, true);
46 |
47 | double actualPayment = toll.calculateTollPayment(policeCar);
48 | assertEquals(expectedPayment, actualPayment);
49 | }
50 |
51 | @Test
52 | public void nonOfficial6WheelsTruck()
53 | {
54 | double expectedPayment = 7.80;
55 | Vehicle nonOfficial6WheelTruck = new Vehicle(6, false);
56 |
57 | double actualPayment = toll.calculateTollPayment(nonOfficial6WheelTruck);
58 | assertEquals(expectedPayment, actualPayment, 0.001);
59 | }
60 |
61 | @Test
62 | public void official6WheelsTruck()
63 | {
64 | double expectedPayment = 0.00;
65 | Vehicle nonOfficial6WheelTruck = new Vehicle(6, true);
66 |
67 | double actualPayment = toll.calculateTollPayment(nonOfficial6WheelTruck);
68 | assertEquals(expectedPayment, actualPayment);
69 | }
70 |
71 | @Test
72 | public void nonOfficial8WheelsTruck()
73 | {
74 | double expectedPayment = 10.0;
75 | Vehicle nonOfficial6WheelTruck = new Vehicle(8, false);
76 |
77 | double actualPayment = toll.calculateTollPayment(nonOfficial6WheelTruck);
78 | assertEquals(expectedPayment, actualPayment);
79 | }
80 |
81 | @Test
82 | public void official8WheelsTruck()
83 | {
84 | double expectedPayment = 0.0;
85 | Vehicle nonOfficial6WheelTruck = new Vehicle(8, true);
86 |
87 | double actualPayment = toll.calculateTollPayment(nonOfficial6WheelTruck);
88 | assertEquals(expectedPayment, actualPayment);
89 | }
90 |
91 | }
--------------------------------------------------------------------------------
/java/src/test/java/iniciante/conditionals/c/AreaCalculationTest.java:
--------------------------------------------------------------------------------
1 | package iniciante.conditionals.c;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import static org.junit.jupiter.api.Assertions.assertEquals;
6 | import static org.junit.jupiter.api.Assertions.assertThrows;
7 |
8 | public class AreaCalculationTest
9 | {
10 | private final AreaCalculation area = new AreaCalculation();
11 |
12 | @Test
13 | public void squareArea()
14 | {
15 | double expectedArea = 200.0;
16 | Square square = new Square(10, 2);
17 |
18 | double result = area.calcArea(square);
19 | assertEquals(expectedArea, result);
20 | }
21 |
22 | @Test
23 | public void triangleArea()
24 | {
25 | double expectedArea = 250.0;
26 | Triangle square = new Triangle(10, 5);
27 |
28 | double result = area.calcArea(square);
29 | assertEquals(expectedArea, result);
30 | }
31 |
32 | @Test
33 | public void circleArea()
34 | {
35 | double expectedArea = 392.5;
36 | Circle square = new Circle(5, 5);
37 |
38 | double result = area.calcArea(square);
39 | assertEquals(expectedArea, result);
40 | }
41 |
42 | @Test
43 | public void invalidShape()
44 | {
45 | Square square = new Square(5, 0);
46 | assertThrows(IllegalArgumentException.class, () -> area.calcArea(square));
47 | }
48 | }
--------------------------------------------------------------------------------
/java/src/test/java/iniciante/loops/a/IncreasingLoopTest.java:
--------------------------------------------------------------------------------
1 | package iniciante.loops.a;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import java.util.Arrays;
6 | import java.util.List;
7 |
8 | import static org.junit.jupiter.api.Assertions.assertEquals;
9 |
10 | public class IncreasingLoopTest
11 | {
12 | private final IncreasingLoop loop = new IncreasingLoop();
13 |
14 | @Test
15 | public void listOne()
16 | {
17 | int expected = 0;
18 | List items = Arrays.asList(1, 2, 3, 4, 5);
19 |
20 | int result = loop.sumItems(items);
21 | assertEquals(expected, result);
22 | }
23 |
24 | @Test
25 | public void listTwo()
26 | {
27 | int expected = 150;
28 | List items = Arrays.asList(10, 20, 30, 40, 50);
29 |
30 | int result = loop.sumItems(items);
31 | assertEquals(expected, result);
32 | }
33 |
34 | @Test
35 | public void listThree()
36 | {
37 | int expected = 10;
38 | List items = Arrays.asList(-10, -5, 0, 5, 10);
39 |
40 | int result = loop.sumItems(items);
41 | assertEquals(expected, result);
42 | }
43 |
44 | }
--------------------------------------------------------------------------------
/java/src/test/java/iniciante/loops/b/DecreasingLoopTest.java:
--------------------------------------------------------------------------------
1 | package iniciante.loops.b;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import java.util.Arrays;
6 | import java.util.List;
7 |
8 | import static org.junit.jupiter.api.Assertions.assertEquals;
9 |
10 | public class DecreasingLoopTest
11 | {
12 | private final DecreasingLoop loop = new DecreasingLoop();
13 |
14 | @Test
15 | public void listOne()
16 | {
17 | List expected = Arrays.asList(5, 4, 3, 2, 1);
18 | List items = Arrays.asList(1, 2, 3, 4, 5);
19 |
20 | List result = loop.reverseItems(items);
21 | assertEquals(expected, result);
22 | }
23 |
24 | @Test
25 | public void listTwo()
26 | {
27 | List expected = Arrays.asList(-5, 10, -1, 0, 15, -100);
28 | List items = Arrays.asList(-100, 15, 0, -1, 10, -5);
29 |
30 | List result = loop.reverseItems(items);
31 | assertEquals(expected, result);
32 | }
33 | }
--------------------------------------------------------------------------------
/java/src/test/java/iniciante/loops/c/WhileLoopTest.java:
--------------------------------------------------------------------------------
1 | package iniciante.loops.c;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import java.util.Arrays;
6 | import java.util.Collections;
7 | import java.util.List;
8 |
9 | import static org.junit.jupiter.api.Assertions.assertEquals;
10 |
11 | public class WhileLoopTest
12 | {
13 | private final WhileLoop loop = new WhileLoop();
14 |
15 | @Test
16 | public void listOne()
17 | {
18 | int expected = 5;
19 | List items = Arrays.asList(1, 2, 3, 4, 5);
20 |
21 | int result = loop.countItems(items.iterator());
22 | assertEquals(expected, result);
23 | }
24 |
25 | @Test
26 | public void listTwo()
27 | {
28 | int expected = 0;
29 | List items = Collections.emptyList();
30 |
31 | int result = loop.countItems(items.iterator());
32 | assertEquals(expected, result);
33 | }
34 |
35 | }
--------------------------------------------------------------------------------
/java/src/test/java/iniciante/string/operations/a/CountAndCaseTest.java:
--------------------------------------------------------------------------------
1 | package iniciante.string.operations.a;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import static org.junit.jupiter.api.Assertions.assertEquals;
6 |
7 | public class CountAndCaseTest
8 | {
9 | private final CountAndCase manipulation = new CountAndCase();
10 |
11 | @Test
12 | public void twoWords()
13 | {
14 | String expectedString = "12AMORAabacaxi";
15 |
16 | String result = manipulation.manipulate("Amora", "Abacaxi");
17 | assertEquals(expectedString, result);
18 | }
19 |
20 | @Test
21 | public void twoEmptyWords()
22 | {
23 | String expectedString = "0";
24 |
25 | String result = manipulation.manipulate("", "");
26 | assertEquals(expectedString, result);
27 | }
28 | }
--------------------------------------------------------------------------------
/java/src/test/java/iniciante/string/operations/b/SubstringTest.java:
--------------------------------------------------------------------------------
1 | package iniciante.string.operations.b;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import static org.junit.jupiter.api.Assertions.assertEquals;
6 |
7 | public class SubstringTest
8 | {
9 | private final Substring manipulation = new Substring();
10 |
11 | @Test
12 | public void tenChars()
13 | {
14 | String expectedString = "erati";
15 |
16 | String result = manipulation.pieceOfString("generation");
17 | assertEquals(expectedString, result);
18 | }
19 |
20 | @Test
21 | public void zeroChars()
22 | {
23 | String expectedString = "";
24 |
25 | String result = manipulation.pieceOfString("");
26 | assertEquals(expectedString, result);
27 | }
28 | }
--------------------------------------------------------------------------------
/java/src/test/java/iniciante/string/operations/c/StartsEndsWithTest.java:
--------------------------------------------------------------------------------
1 | package iniciante.string.operations.c;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import static org.junit.jupiter.api.Assertions.assertEquals;
6 |
7 | public class StartsEndsWithTest
8 | {
9 | private final StartsEndsWith manipulation = new StartsEndsWith();
10 |
11 | @Test
12 | public void aStart()
13 | {
14 | Boolean expected = true;
15 |
16 | Boolean result = manipulation.startsWith("abacaxi");
17 | assertEquals(expected, result);
18 | }
19 |
20 | @Test
21 | public void bStart()
22 | {
23 | Boolean expected = false;
24 |
25 | Boolean result = manipulation.startsWith("banana");
26 | assertEquals(expected, result);
27 | }
28 |
29 | @Test
30 | public void uStart()
31 | {
32 | Boolean expected = true;
33 |
34 | Boolean result = manipulation.startsWith("uva");
35 | assertEquals(expected, result);
36 | }
37 |
38 | @Test
39 | public void emptyStart()
40 | {
41 | Boolean expected = false;
42 |
43 | Boolean result = manipulation.startsWith("");
44 | assertEquals(expected, result);
45 | }
46 |
47 | @Test
48 | public void aEnd()
49 | {
50 | Boolean expected = true;
51 |
52 | Boolean result = manipulation.endsWith("banana");
53 | assertEquals(expected, result);
54 | }
55 |
56 | @Test
57 | public void rEnd()
58 | {
59 | Boolean expected = false;
60 |
61 | Boolean result = manipulation.endsWith("comer");
62 | assertEquals(expected, result);
63 | }
64 |
65 | @Test
66 | public void uEnd()
67 | {
68 | Boolean expected = true;
69 |
70 | Boolean result = manipulation.endsWith("cupuaçu");
71 | assertEquals(expected, result);
72 | }
73 |
74 | @Test
75 | public void emptyEnd()
76 | {
77 | Boolean expected = false;
78 |
79 | Boolean result = manipulation.endsWith("");
80 | assertEquals(expected, result);
81 | }
82 | }
--------------------------------------------------------------------------------