Skip to content

Commit

Permalink
DayNineteen
Browse files Browse the repository at this point in the history
  • Loading branch information
ayoubzulfiqar committed Dec 19, 2024
1 parent 515faae commit d384a94
Show file tree
Hide file tree
Showing 4 changed files with 272 additions and 0 deletions.
92 changes: 92 additions & 0 deletions 2024/Go/Day19/part_1.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package main

import (
"bufio"
"fmt"
"os"
"strings"
)

func possibleDesign() int {
// Open the input file
file, err := os.Open("input.txt")
if err != nil {
fmt.Println("Error opening file:", err)
return 0
}
defer file.Close()

// Read the file line by line
scanner := bufio.NewScanner(file)
var lines []string
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Println("Error reading file:", err)
return 0
}

// Check for non-empty input
if len(lines) < 2 {
fmt.Println("Invalid input: not enough lines")
return 0
}

// Parse available pieces and targets
available := strings.Split(lines[0], ",")
targets := lines[1:]

// Trim spaces around available pieces
for i := range available {
available[i] = strings.TrimSpace(available[i])
}

// Memoization map to store results of sub-problems
memo := make(map[string]bool)

// Recursive function to check if a target is possible
var isPossible func(string) bool
isPossible = func(target string) bool {
// Base case: empty target is always possible
if target == "" {
return true
}

// Check memoization map
if val, exists := memo[target]; exists {
return val
}

// Try matching each available part
for _, start := range available {
if strings.HasPrefix(target, start) {
if isPossible(target[len(start):]) {
memo[target] = true
return true
}
}
}

// If no match, mark as impossible
memo[target] = false
return false
}

// Count the number of possible targets
//try answer = 0 if doesn't work in your case
answer := -1
for _, target := range targets {
if isPossible(target) {
answer++
}
}

// Print and return the result
fmt.Println(answer)
return answer
}

// func main() {
// possibleDesign()
// }
88 changes: 88 additions & 0 deletions 2024/Go/Day19/part_2.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package main

import (
"bufio"
"fmt"
"os"
"strings"
)

func differentWaysToMakeDesign() int {
// Open the input file
file, err := os.Open("input.txt")
if err != nil {
fmt.Println("Error opening file:", err)
return 0
}
defer file.Close()

// Read the file line by line
scanner := bufio.NewScanner(file)
var lines []string
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Println("Error reading file:", err)
return 0
}

// Check for non-empty input
if len(lines) < 2 {
fmt.Println("Invalid input: not enough lines")
return 0
}

// Parse available pieces and targets
available := strings.Split(lines[0], ", ")
targets := lines[1:]

// Trim spaces around available pieces
for i := range available {
available[i] = strings.TrimSpace(available[i])
}

// Memoization map to store results of sub-problems
memo := make(map[string]int)

// Recursive function to count the number of ways to construct the target
var numWays func(string) int
numWays = func(target string) int {
// Base case: empty target has exactly one way to be constructed (by doing nothing)
if target == "" {
return 1
}

// Check memoization map
if val, exists := memo[target]; exists {
return val
}

// Count all possible ways
totalWays := 0
for _, start := range available {
if strings.HasPrefix(target, start) {
totalWays += numWays(target[len(start):])
}
}

// Store the result in the memo map
memo[target] = totalWays
return totalWays
}

// Compute the total number of ways for all targets
// try answer = 0 in your case if it does not work
answer := -1
for _, target := range targets {
answer += numWays(target)
}

// Print and return the result
fmt.Println(answer)
return answer
}

// func main() {
// differentWaysToMakeDesign()
// }
53 changes: 53 additions & 0 deletions 2024/Python/Day19/part_1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import functools
from typing import List, Tuple


def loadInput(filePath: str) -> Tuple[List[str], List[str]]:
"""
Load the input data from a file.
Args:
file_path (str): Path to the input file.
Returns:
Tuple[List[str], List[str]]: Available substrings and target strings.
"""
try:
with open(filePath, "r") as f:
available, targets = f.read().strip().split("\n\n")
available_substrings = available.split(", ")
target_strings = targets.splitlines()
return available_substrings, target_strings
except FileNotFoundError:
raise FileNotFoundError(f"Input file {filePath} not found.")
except ValueError:
raise ValueError(
"Input file format is incorrect. Ensure it contains two sections separated by a blank line."
)


def countPossibleDesigns(file_path: str) -> int:
"""
Counts how many target strings can be constructed using available substrings.
Args:
file_path (str): Path to the input file.
Returns:
int: Number of target strings that can be constructed.
"""
available_substrings, target_strings = loadInput(file_path)

@functools.lru_cache(None)
def is_possible(target: str) -> bool:
if not target:
return True
for start in available_substrings:
if target.startswith(start):
if is_possible(target[len(start) :]):
return True
return False

result = sum(is_possible(target) for target in target_strings)
print(result)
return result


# if __name__ == "__main__":
# countPossibleDesigns("input.txt")
39 changes: 39 additions & 0 deletions 2024/Python/Day19/part_2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import functools
from typing import List, Tuple


def loadInput(filePath: str) -> Tuple[List[str], List[str]]:
try:
with open(filePath, "r") as f:
available, targets = f.read().strip().split("\n\n")
available_substrings = available.split(", ")
target_strings = targets.splitlines()
return available_substrings, target_strings
except FileNotFoundError:
raise FileNotFoundError(f"Input file {filePath} not found.")
except ValueError:
raise ValueError(
"Input file format is incorrect. Ensure it contains two sections separated by a blank line."
)


def differentWaysToMakeDesign(filePath: str) -> int:
availableSubstrings, targetStrings = loadInput(filePath)

@functools.lru_cache(None)
def numWays(target: str) -> int:
if not target:
return 1
total_ways = 0
for start in availableSubstrings:
if target.startswith(start):
total_ways += numWays(target[len(start) :])
return total_ways

result = sum(numWays(target) for target in targetStrings)
print(result)
return result


# if __name__ == "__main__":
# differentWaysToMakeDesign("input.txt")

0 comments on commit d384a94

Please sign in to comment.