githubEdit

PE1 (AY23/24)

Problems

1. Mirror

My solution is to use char** cs1010_read_word_array(size_t k).

#include "cs1010.h"

int main()
{
  size_t n = cs1010_read_size_t();
  char **left_half = cs1010_read_word_array(n);
  if (left_half == NULL)
  {
    return 1;
  }
  for (size_t i = 0; i < n; i += 1)
  {
    char *temp = left_half[i];
    long length = 0;
    while (*temp != '\0')
    {
      putchar(*temp);
      length += 1;
      temp += 1;
    }
    for (long j = length - 1; j >= 0; j -= 1)
    {
      putchar(left_half[i][j]);
    }
    cs1010_println_string("");
  }
  for (size_t i = 0; i < n; i += 1)
  {
    free(left_half[i]);
  }
  free(left_half);
}

2. Nigh

This question reminds us the importance of counting the frequency of each digit in a number, which appears in Ex3 Q4arrow-up-right before.

3. Alternate

This question teaches us an important point: when traversing from end to the start of a string, it is always recommended to cast the loop index to be long! Since size_t will always be 0 and we still need to zero index element, so it will be hard for us to define when to stop!

After reading the comments, I feel like my solution is a bit more elegant.

4. Grammar

This is actually a Sliding Window problem.

But I use a recursive method when doing this question at the first time

5. Pirate

This problem is similar to Ex5 Q6arrow-up-right

  1. For Captains, we notice that the captains are all in the diagonal of the 2-D matrix whose value is not -1 (Suppose I initialise all the elements to -1)

  2. For counting crew numbers, we use the recursive thinking, start from the captain, once we find a crew, treat the crew as a new "captain" and find its crew. Until we have iterated every row in each function call. We are done

After reading the comments, I feel the method using a 2-D array is more elegant.

Last updated