Skip to content

Instantly share code, notes, and snippets.

@ayoubzulfiqar
Last active December 6, 2023 11:02
Show Gist options
  • Save ayoubzulfiqar/f4946b34438954601bfc4a7b6e1fd6b0 to your computer and use it in GitHub Desktop.
Save ayoubzulfiqar/f4946b34438954601bfc4a7b6e1fd6b0 to your computer and use it in GitHub Desktop.
Advent of Code Implemented in [Go, TypeScript, Dart]

Advent of Code 2023: Day-2: Cube Conundrum

Code Go

Part -1

func CubeConundrum() int {
	// Open the file named "input.txt". If an error occurs, print the error and return 0.
	file, err := os.Open("input.txt")
	if err != nil {
		fmt.Println("Error opening file:", err)
		return 0
	}
	// Close the file when the function exits.
	defer file.Close()

	// Create a scanner to read the file line by line.
	scanner := bufio.NewScanner(file)

	// Initialize variables to keep track of the total and bufferCount.
	total := 0
	var bufferCount int

	// Loop through each line in the file.
	for i := 0; scanner.Scan(); i++ {
		// Get the current line.
		lines := scanner.Text()

		// Loop through each character in the line.
		for j := 0; j < len(lines); j++ {
			// If the character is a digit, update bufferCount accordingly.
			if lines[j] >= '0' && lines[j] <= '9' {
				bufferCount *= 10
				bufferCount += int(lines[j] - '0')
				continue
			}
			// If the character is a space, skip to the next character.
			if lines[j] == ' ' {
				continue
			}
			// Check the color of the current character and compare bufferCount.
			switch lines[j] {
			case 'r':
				if bufferCount > 12 {
					// If bufferCount exceeds the limit for red, exit the loop.
					goto exit
				}
			case 'g':
				if bufferCount > 13 {
					// If bufferCount exceeds the limit for green, exit the loop.
					goto exit
				}
			case 'b':
				if bufferCount > 14 {
					// If bufferCount exceeds the limit for blue, exit the loop.
					goto exit
				}
			}

			// Reset bufferCount for the next color.
			bufferCount = 0
		}
		// If the loop completes without exceeding any limits, update the total.
		total += i + 1
	exit:
	}

	// Print the total and return it.
	fmt.Println(total)
	return total
}

Part -2

// max returns the maximum value between two integers.
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

// CubeConundrumPower calculates the power based on color counts and buffer values.
func CubeConundrumPower() int {
	// Open the file named "input.txt". If an error occurs, print the error and return 0.
	file, err := os.Open("input.txt")
	if err != nil {
		fmt.Println("Error opening file:", err)
		return 0
	}
	// Close the file when the function exits.
	defer file.Close()

	// Create a scanner to read the file line by line.
	scanner := bufio.NewScanner(file)

	// Initialize variables to keep track of the power and bufferCount.
	power := 0
	var bufferCount int

	// Loop through each line in the file.
	for scanner.Scan() {
		// Initialize color counts for red, green, and blue.
		var redCount, greenCount, blueCount int = 0, 0, 0
		// Get the current line.
		lines := scanner.Text()

		// Loop through each character in the line.
		for j := 0; j < len(lines); j++ {
			// If the character is a digit, update bufferCount accordingly.
			if lines[j] >= '0' && lines[j] <= '9' {
				bufferCount *= 10
				bufferCount += int(lines[j] - '0')
				continue
			}
			// If the character is a space, skip to the next character.
			if lines[j] == ' ' {
				continue
			}
			// Check the color of the current character and update the corresponding color count.
			switch lines[j] {
			case 'r':
				redCount = max(redCount, bufferCount)
			case 'g':
				greenCount = max(greenCount, bufferCount)
			case 'b':
				blueCount = max(blueCount, bufferCount)
			}

			// Reset bufferCount for the next color.
			bufferCount = 0
		}

		// Update the power based on the product of color counts.
		power += redCount * greenCount * blueCount
	}

	// Print the power and return it.
	fmt.Println(power)
	return power
}

Code TypeScript

Part -1

import * as fs from 'fs';

function max(a: number, b: number): number {
  return a > b ? a : b;
}

function cubeConundrum(): number {
  try {
    // Read the contents of the file named "input.txt".
    const fileContent: string = fs.readFileSync('input.txt', 'utf-8');

    let total: number = 0;
    let bufferCount: number = 0;

    // Split the content into lines.
    const lines: string[] = fileContent.split('\n');

    for (let i = 0; i < lines.length; i++) {
      const line: string = lines[i];
      for (let j = 0; j < line.length; j++) {
        // If the character is a digit, update bufferCount accordingly.
        if (line[j] >= '0' && line[j] <= '9') {
          bufferCount *= 10;
          bufferCount += parseInt(line[j], 10);
          continue;
        }
        // If the character is a space, skip to the next character.
        if (line[j] === ' ') {
          continue;
        }
        // Check the color of the current character and compare bufferCount.
        switch (line[j]) {
          case 'r':
            if (bufferCount > 12) {
              // If bufferCount exceeds the limit for red, exit the loop.
              bufferCount = 0;
              break;
            }
            break;
          case 'g':
            if (bufferCount > 13) {
              // If bufferCount exceeds the limit for green, exit the loop.
              bufferCount = 0;
              break;
            }
            break;
          case 'b':
            if (bufferCount > 14) {
              // If bufferCount exceeds the limit for blue, exit the loop.
              bufferCount = 0;
              break;
            }
            break;
        }

        // Reset bufferCount for the next character.
        bufferCount = 0;
      }
      // If the loop completes without exceeding any limits, update the total.
      total += i + 1;
    }

    console.log(total);
    return total;
  } catch (error) {
    console.log('Error opening file:', error);
    return 0;
  }
}

// Call the function to execute the TypeScript code.
cubeConundrum();

Part -2

import * as fs from 'fs';

// Function to find the maximum of two numbers
function max(a: number, b: number): number {
  return a > b ? a : b;
}

// Function to calculate power based on color counts and buffer values
function cubeConundrumPower(): number {
  try {
    // Read the contents of the file named "input.txt".
    const fileContent: string = fs.readFileSync('input.txt', 'utf-8');

    let power: number = 0;
    let bufferCount: number = 0;

    // Split the content into lines.
    const lines: string[] = fileContent.split('\n');

    for (let i = 0; i < lines.length; i++) {
      let redCount: number = 0, greenCount: number = 0, blueCount: number = 0;
      const line: string = lines[i];

      for (let j = 0; j < line.length; j++) {
        // If the character is a digit, update bufferCount accordingly.
        if (line[j] >= '0' && line[j] <= '9') {
          bufferCount *= 10;
          bufferCount += parseInt(line[j], 10);
          continue;
        }
        // If the character is a space, skip to the next character.
        if (line[j] === ' ') {
          continue;
        }
        // Check the color of the current character and update the corresponding color count.
        switch (line[j]) {
          case 'r':
            redCount = max(redCount, bufferCount);
            break;
          case 'g':
            greenCount = max(greenCount, bufferCount);
            break;
          case 'b':
            blueCount = max(blueCount, bufferCount);
            break;
        }

        // Reset bufferCount for the next character.
        bufferCount = 0;
      }

      // Update the power based on the product of color counts.
      power += redCount * greenCount * blueCount;
    }

    console.log(power);
    return power;
  } catch (error) {
    console.log('Error opening file:', error);
    return 0;
  }
}

// Call the function to execute the TypeScript code.
cubeConundrumPower();

Code Dart

part -1

import 'dart:io';

int cubeConundrum() {
  try {
    // Open the file named "input.txt".
    File file = File("test.txt");
    // Check if the file exists.
    if (!file.existsSync()) {
      print("Error: File 'test.txt' not found.");
      return 0;
    }
    List<String> lines = file.readAsLinesSync();

    int total = 0;
    int bufferCount = 0;
    bool shouldExit = false;

    for (int i = 0; i < lines.length && !shouldExit; i++) {
      String line = lines[i];
      for (int j = 0; j < line.length; j++) {
        // If the character is a digit, update bufferCount accordingly.
        if (line[j].codeUnitAt(0) >= '0'.codeUnitAt(0) &&
            line[j].codeUnitAt(0) <= '9'.codeUnitAt(0)) {
          bufferCount *= 10;
          bufferCount += int.parse(line[j]);
          continue;
        }
        // If the character is a space, skip to the next character.
        if (line[j] == ' ') {
          continue;
        }
        // Check the color of the current character and compare bufferCount.
        switch (line[j]) {
          case 'r':
            if (bufferCount > 12) {
              shouldExit = true;
            }
            break;
          case 'g':
            if (bufferCount > 13) {
              shouldExit = true;
            }
            break;
          case 'b':
            if (bufferCount > 14) {
              shouldExit = true;
            }
            break;
        }

        // Reset bufferCount for the next color.
        bufferCount = 0;
      }
      // If the loop completes without exceeding any limits, update the total.
      if (!shouldExit) {
        total += i + 1;
      }
    }

    print(total);
    return total;
  } catch (error) {
    print('Error opening file: $error');
    return 0;
  }
}

Part 2

import 'dart:io';

int max(int a, int b) {
  return a > b ? a : b;
}

int cubeConundrumPower() {
  try {
    // Open the file named "input.txt".
    File file = File("text.txt");
    List<String> lines = file.readAsLinesSync();

    int power = 0;
    int bufferCount = 0;

    for (String line in lines) {
      int redCount = 0, greenCount = 0, blueCount = 0;

      for (int j = 0; j < line.length; j++) {
        // If the character is a digit, update bufferCount accordingly.
        if (line.codeUnitAt(j) >= '0'.codeUnitAt(0) &&
            line.codeUnitAt(j) <= '9'.codeUnitAt(0)) {
          bufferCount *= 10;
          bufferCount += int.parse(line[j]);
          continue;
        }
        // If the character is a space, skip to the next character.
        if (line[j] == ' ') {
          continue;
        }
        // Check the color of the current character and compare bufferCount.
        switch (line[j]) {
          case 'r':
            redCount = max(redCount, bufferCount);
            break;
          case 'g':
            greenCount = max(greenCount, bufferCount);
            break;
          case 'b':
            blueCount = max(blueCount, bufferCount);
            break;
        }

        // Reset bufferCount for the next color.
        bufferCount = 0;
      }

      // Update the power based on the product of color counts.
      power += redCount * greenCount * blueCount;
    }

    print(power);
    return power;
  } catch (error) {
    print('Error opening file: $error');
    return 0;
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment