add more stuff

This commit is contained in:
cediackermann 2026-05-18 08:58:34 +02:00
parent 767346f408
commit 04e76f1879
21 changed files with 570 additions and 279 deletions

20
.vscode/launch.json vendored
View file

@ -59,6 +59,26 @@
"target": "Aufgabe3",
"configuration": "release",
"preLaunchTask": "swift: Build Release Aufgabe3"
},
{
"type": "swift",
"request": "launch",
"args": [],
"cwd": "${workspaceFolder:m323}",
"name": "Debug 01_MapUebungen",
"target": "01_MapUebungen",
"configuration": "debug",
"preLaunchTask": "swift: Build Debug 01_MapUebungen"
},
{
"type": "swift",
"request": "launch",
"args": [],
"cwd": "${workspaceFolder:m323}",
"name": "Release 01_MapUebungen",
"target": "01_MapUebungen",
"configuration": "release",
"preLaunchTask": "swift: Build Release 01_MapUebungen"
}
]
}

View file

@ -24,5 +24,4 @@ public class Drei {
System.out.println(tipCalculator.getTipPercentage(names));
}
}

View file

@ -5,14 +5,12 @@ public class ShoppingCartFunctional {
/**
* Pure function that calculates the discount percentage based on the cart content.
*
* @param cart The list of items in the shopping cart.
* @return 5 if a book is present, 0 otherwise.
*/
public static double getDiscountPercentage(List<String> cart) {
return cart.stream()
.anyMatch(item -> item.toLowerCase().contains("book"))
? 5
: 0;
return cart.stream().anyMatch(item -> item.toLowerCase().contains("book")) ? 5 : 0;
}
public static void main(String[] args) {

View file

@ -1,144 +0,0 @@
import Foundation
// 3.1
func calculateSum(items: [Int]) -> Int {
var sum = 0
for item in items {
sum += item
}
return sum
}
let items = [1, 2, 3, 4, 5]
print(calculateSum(items: items))
// 3.2
func calculateAverage(items: [Int]) -> Int {
let sum = items.reduce(0, +)
if !items.isEmpty {
let avg = sum / items.count
return avg
}
return 0
}
print(calculateAverage(items: items))
// 3.3
func sortListAlphabetical(items: [String]) -> [String] {
let itemsCopy = items
return itemsCopy.sorted()
}
let stringItems = ["ABC", "CDF", "BDC"]
print(sortListAlphabetical(items: stringItems))
// 3.4
struct ComplexType {
var date = Date()
var priority: Int
var title: String
}
func sortComplexType(items: [ComplexType]) -> [ComplexType] {
let itemsCopy = items
return itemsCopy.sorted {
($0.date, $0.priority, $0.title) < ($1.date, $1.priority, $1.title)
}
}
let now = Date()
let calendar = Calendar.current
let sampleData = [
ComplexType(
date: now,
priority: 1,
title: "Submit Quarterly Report"
),
ComplexType(
date: calendar.date(byAdding: .day, value: -1, to: now)!,
priority: 2,
title: "Review Pull Request"
),
ComplexType(
date: calendar.date(byAdding: .day, value: 1, to: now)!,
priority: 1,
title: "Project Kickoff Meeting"
),
ComplexType(
date: now,
priority: 3,
title: "Update Documentation"
),
ComplexType(
date: calendar.date(byAdding: .hour, value: -5, to: now)!,
priority: 2,
title: "Check System Logs"
),
]
print(sortComplexType(items: sampleData))
// Aufgabe 3.5
struct Tree {
var branches: [Branch]
}
struct Branch {
var branches: [Branch]
var leaves: [Leaf]
}
struct Leaf {
var color: String
var name: String
}
let leafA = Leaf(color: "Green", name: "Oak Leaf Alpha")
let leafB = Leaf(color: "Yellow", name: "Oak Leaf Beta")
let leafC = Leaf(color: "Green", name: "Oak Leaf Gamma")
let smallBranch = Branch(
branches: [],
leaves: [leafC]
)
let mainBranch1 = Branch(
branches: [smallBranch], // Contains the sub-branch
leaves: [leafA]
)
let mainBranch2 = Branch(
branches: [],
leaves: [leafB]
)
let myTree = Tree(branches: [mainBranch1, mainBranch2])
func getLeaves(tree: Tree) -> [Leaf] {
var leaves = [Leaf]()
var stack = tree.branches
while !stack.isEmpty {
let currentBranch = stack.removeLast()
leaves.append(contentsOf: currentBranch.leaves)
stack.append(contentsOf: currentBranch.branches)
}
return leaves
}
let result = getLeaves(tree: myTree)
for leaf in result {
print("\(leaf.name) (\(leaf.color))")
}

View file

@ -1,30 +1,36 @@
// swift-tools-version: 6.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "m323",
platforms: [.macOS(.v15)],
targets: [
// Targets are the basic building blocks of a package, defining a module or a test suite.
// Targets can depend on other targets in this package and products from dependencies.
.executableTarget(
name: "m323"
name: "m323",
path: "Sources/m323"
),
.executableTarget(
name: "WeDontLikeCharA",
path: "02",
sources: ["WeDontLikeCharA.swift"]
path: "Sources/WeDontLikeCharA"
),
.executableTarget(
name: "Aufgabe3",
path: "03",
sources: ["Aufgabe3.swift"]
path: "Sources/Aufgabe3",
exclude: ["PureOrNotPure.md"]
),
.executableTarget(name: "01_MapUebungen", path: "Sources/Aufgabe4/01_MapUebungen"),
.executableTarget(name: "02_FilterUebungen", path: "Sources/Aufgabe4/02_FilterUebungen"),
.executableTarget(
name: "03_MapUndFilterUebungen", path: "Sources/Aufgabe4/03_MapUndFilterUebungen"),
.executableTarget(name: "04_FoldLeftUebungen", path: "Sources/Aufgabe4/04_FoldLeftUebungen"),
.executableTarget(name: "05_FlatMapUebungen", path: "Sources/Aufgabe4/05_FlatMapUebungen"),
.executableTarget(
name: "06_ForComprehensionsUebungen", path: "Sources/Aufgabe4/06_ForComprehensionsUebungen"),
.executableTarget(name: "LeetCode", path: "Sources/LeetCode"),
.testTarget(
name: "m323Tests",
dependencies: ["m323"]
),
],
swiftLanguageModes: [.v6]
]
)

View file

@ -4,9 +4,9 @@
| ------- | -------------------- | ------------------------------------------------ | ----------------------------------- | ---------------- |
| 1.1 | Ja | Nein | Nein | impure |
| 1.2 | Ja | Ja | Ja | pure |
| 1.3 | Ja | ja | Ja | impure |
| 1.3 | Ja | ja | Ja | pure |
| 1.4 | Ja | Nein | Ja | impure |
| 1.5 | Ja | Ja | Ja | impure |
| 1.5 | Ja | Ja | Ja | pure |
| 1.6 | Ja | Ja | Nein | impure |
## Aufgabe 1.1
@ -40,11 +40,7 @@ console.log(add(2, 4)); // Ausgabe: 6
```js
function firstCharacter(str) {
if (!len(str) > 0) {
return str.charAt(0);
} else {
return "";
}
}
console.log(firstCharacter("Hello")); // Ausgabe: H
@ -68,11 +64,7 @@ console.log(multiplyWithRandom(10, Math.random())); // Ausgabe: Eine zufällige
```js
// Funktion zum Teilen einer Zahl durch eine andere
function divideNumbers(dividend, divisor) {
if (dividen != 0 && divisor != 0) {
return dividend / divisor;
} else {
return 0;
}
}
console.log(divideNumbers(10, 2)); // Ausgabe: 5

144
Sources/Aufgabe3/main.swift Normal file
View file

@ -0,0 +1,144 @@
import Foundation
// 3.1
func calculateSum(items: [Int]) -> Int {
var sum = 0
for item in items {
sum += item
}
return sum
}
let items = [1, 2, 3, 4, 5]
print(calculateSum(items: items))
// 3.2
func calculateAverage(items: [Int]) -> Int {
let sum = items.reduce(0, +)
if !items.isEmpty {
let avg = sum / items.count
return avg
}
return 0
}
print(calculateAverage(items: items))
// 3.3
func sortListAlphabetical(items: [String]) -> [String] {
let itemsCopy = items
return itemsCopy.sorted()
}
let stringItems = ["ABC", "CDF", "BDC"]
print(sortListAlphabetical(items: stringItems))
// 3.4
struct ComplexType {
var date = Date()
var priority: Int
var title: String
}
func sortComplexType(items: [ComplexType]) -> [ComplexType] {
let itemsCopy = items
return itemsCopy.sorted {
($0.date, $0.priority, $0.title) < ($1.date, $1.priority, $1.title)
}
}
let now = Date()
let calendar = Calendar.current
let sampleData = [
ComplexType(
date: now,
priority: 1,
title: "Submit Quarterly Report"
),
ComplexType(
date: calendar.date(byAdding: .day, value: -1, to: now)!,
priority: 2,
title: "Review Pull Request"
),
ComplexType(
date: calendar.date(byAdding: .day, value: 1, to: now)!,
priority: 1,
title: "Project Kickoff Meeting"
),
ComplexType(
date: now,
priority: 3,
title: "Update Documentation"
),
ComplexType(
date: calendar.date(byAdding: .hour, value: -5, to: now)!,
priority: 2,
title: "Check System Logs"
),
]
print(sortComplexType(items: sampleData))
// Aufgabe 3.5
struct Tree {
var branches: [Branch]
}
struct Branch {
var branches: [Branch]
var leaves: [Leaf]
}
struct Leaf {
var color: String
var name: String
}
let leafA = Leaf(color: "Green", name: "Oak Leaf Alpha")
let leafB = Leaf(color: "Yellow", name: "Oak Leaf Beta")
let leafC = Leaf(color: "Green", name: "Oak Leaf Gamma")
let smallBranch = Branch(
branches: [],
leaves: [leafC]
)
let mainBranch1 = Branch(
branches: [smallBranch], // Contains the sub-branch
leaves: [leafA]
)
let mainBranch2 = Branch(
branches: [],
leaves: [leafB]
)
let myTree = Tree(branches: [mainBranch1, mainBranch2])
func getLeaves(tree: Tree) -> [Leaf] {
var leaves = [Leaf]()
var stack = tree.branches
while !stack.isEmpty {
let currentBranch = stack.removeLast()
leaves.append(contentsOf: currentBranch.leaves)
stack.append(contentsOf: currentBranch.branches)
}
return leaves
}
let result = getLeaves(tree: myTree)
for leaf in result {
print("\(leaf.name) (\(leaf.color))")
}

View file

@ -0,0 +1,30 @@
//
// 01_MapUebungen.swift
// m323
//
// Created by cediackermann on 18.05.2026.
//
// Aufgabe 1
let numberList = [1, 2, 3, 4, 5]
func doubleListItems(numbers: [Int]) -> [Int] {
let doubleList = numbers.map { $0 * 2 }
return doubleList
}
print(doubleListItems(numbers: numberList))
// Aufgabe 2
let nameList = ["Alice", "Bob", "Charlie"]
func makeUpperCase(list: [String]) -> [String] {
let upperCaseList = list.map { $0.uppercased() }
return upperCaseList
}
print(makeUpperCase(list: nameList))
// Aufgabe 3

View file

@ -0,0 +1,26 @@
//
// main.swift
// m323
//
// Created by cediackermann on 18.05.2026.
//
// Aufgabe 1
let numberList = [1, 2, 3, 4, 5]
func getEvenNumbers(list: [Int]) -> [Int] {
let filteredList = list.filter { $0 % 2 == 0 }
return filteredList
}
print(getEvenNumbers(list: numberList))
let nameList = ["Alice", "Bob", "Charlie", "Diana"]
func getLongStrings(list: [String]) -> [String] {
let filteredList = list.filter { $0.count > 4 }
return filteredList
}
print(getLongStrings(list: nameList))

View file

@ -0,0 +1,62 @@
import Foundation
//
// main.swift
// m323
//
// Created by cediackermann on 18.05.2026.
//
// Aufgabe 1
struct Employee {
var name: String
var department: String
var salary: Int
}
let employees: [Employee] = [
Employee(name: "Max Mustermann", department: "IT", salary: 50000),
Employee(name: "Erika Musterfrau", department: "Marketing", salary: 45000),
Employee(name: "Klaus Klein", department: "IT", salary: 55000),
Employee(name: "Julia Gross", department: "HR", salary: 40000),
]
func extractHighEarningITPersonnel(employees: [Employee]) -> [Employee] {
let highEarningITPersonnel = employees.filter {
$0.department == "IT" && $0.salary >= 50000
}
let updatedPersonnel = highEarningITPersonnel.map { employee -> Employee in
var updatedEmployee = employee // Create a mutable copy
let firstName = updatedEmployee.name.split(separator: " ", maxSplits: 1).first ?? ""
updatedEmployee.name = firstName.uppercased()
return updatedEmployee
}
return updatedPersonnel
}
print(extractHighEarningITPersonnel(employees: employees))
// Aufgabe 2
let courseList = [
"Programmierung in Scala",
"Datenbanken",
"Webentwicklung mit JavaScript",
"Algorithmen und Datenstrukturen",
]
func filterCourses(courses: [String]) -> [String] {
let processedCourses =
courses
.filter { !$0.contains("Daten") }
.map {
$0.replacingOccurrences(of: " ", with: "")
}
.sorted()
.sorted(by: >)
return processedCourses
}
print(filterCourses(courses: courseList))

View file

@ -0,0 +1,26 @@
//
// main.swift
// m323
//
// Created by cediackermann on 18.05.2026.
//
// Aufgabe 1
let numberList = [1, 2, 3, 4, 5]
func foldLeft(list: [Int]) -> Int {
return list.reduce(0, +)
}
print(foldLeft(list: numberList))
// Aufgabe 2
let stringList = ["Hallo", " ", "Welt", "!"]
func foldStringsLeft(list: [String]) -> String {
return list.reduce("", +)
}
print(foldStringsLeft(list: stringList))

View file

@ -0,0 +1,33 @@
import Foundation
//
// main.swift
// m323
//
// Created by cediackermann on 18.05.2026.
//
// Aufgabe 1
let list: [[Int]] = [[1, 2], [3, 4], [5, 6]]
func getFlatMap(list: [[Int]]) -> [Int] {
return list.flatMap { $0 }
}
print(getFlatMap(list: list))
// Aufgabe 2
let dictionary: [String: [String]] = [
"Max": ["Blau", "Grün"],
"Anna": ["Rot"],
"Julia": ["Gelb", "Blau", "Grün"],
]
func getDistinctColors(list: [String: [String]]) -> [String] {
let flattenedColors = list.flatMap { $0.1 }
return Array(Set(flattenedColors))
}
print(getDistinctColors(list: dictionary))

View file

@ -0,0 +1,26 @@
//
// main.swift
// m323
//
// Created by cediackermann on 18.05.2026.
//
// Aufgabe 1
for number in 1...10 {
print(number * number)
}
// Aufgabe 2
let evenNumbers: [Int] = {
var numbers: [Int] = []
for number in 1...20 {
if number % 2 == 0 {
numbers.append(number)
}
}
return numbers
}()
print(evenNumbers)

View file

@ -0,0 +1 @@
05_FlatMapUebungen

View file

@ -0,0 +1,58 @@
import Foundation
//
// LeetCode.swift
// m323
//
// Created by cediackermann on 18.05.2026.
//
class LeetCode {
func hammingWeight(_ n: Int) -> Int {
var weight = 0
let quotient = n / 2
weight += n % 2
let roundedQuotient = floor(Double(quotient))
if roundedQuotient != 0 {
weight += hammingWeight(Int(roundedQuotient))
}
return weight
}
func singleNumber(_ nums: [Int]) -> Int {
var result = 0
for num in nums {
result ^= num
}
return result
}
func containsDuplicate(_ nums: [Int]) -> Bool {
return nums.count != Set(nums).count
}
func sortedSquares(_ nums: [Int]) -> [Int] {
return nums.map { $0 * $0 }.sorted()
}
func productExceptSelf(_ nums: [Int]) -> [Int] {
var result = [Int](repeating: 1, count: nums.count)
var prefix = [Int](repeating: 1, count: nums.count)
var suffix = [Int](repeating: 1, count: nums.count)
var runningProduct = 1
for i in 0..<nums.count {
prefix[i] = runningProduct
runningProduct *= nums[i]
}
runningProduct = 1
for i in stride(from: nums.count - 1, through: 0, by: -1) {
suffix[i] = runningProduct
runningProduct *= nums[i]
result[i] = prefix[i] * suffix[i]
}
return result
}
}

View file

@ -0,0 +1,13 @@
//
// main.swift
// m323
//
// Created by cediackermann on 18.05.2026.
//
let code = LeetCode()
// print(code.hammingWeight(2_147_483_645))
// print(code.singleNumber([4, 1, 2, 1, 2]))
// print(code.containsDuplicate([1, 2, 3, 4]))
print(code.productExceptSelf([-1, 1, 0, -3, 3]))

View file

@ -1,4 +1,5 @@
import Testing
@testable import m323
@Test func example() async throws {