Counter

tags: counter up-counter down-counter

Counter is a variable used to count something. It is usually initialized to zero and then incremented when some criteria is met.

Counting with Array

Write a program to count the number of times a character appears in a given word.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def character_count(word, character)
  letters = word.chars
  count = 0
  
  for letter in letters
    if letter == character
      count += 1
    end
  end

  return count
end

p character_count('banana', 'a')

This program illustrates a basic building block: counter. The counter variable count is initialized to 0 and it is incremented whenever there is a match in the word for the given character that needs to be counted.

After the loop terminates the counter variable has the number of occurrences of the given character in the word.

The string needs to be converted to a sequence of character by using the chars method. This returns an array of characters. After the conversion an index which is an integer value is used to select an item in the sequence, such as a character in the input string.

Counting with Linked List

A while loop can be used for counting. The example code shows how to count the number of nodes in a linked list.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def count(node)
  counter = 0
  current = node
  
  while !current.nil?
    counter += 1
    current = current.next
  end
  
  return counter
end

It is a good practice to use a current pointer that moves through the linked list instead of changing the input object passed to the count method.

Recursive Counting in Linked List

The base case is reached when we reach the end of the linked list. The input to the count recursive function traverses the linked list one node at a time.

1
2
3
4
5
6
7
def count(node)
  if node.nil?
    return 0
  end
  
  return count(node.next) + 1
end

The counter can be classified as either up counter or down counter. For example counting from 1 to 10 is up counter and counting down from 10 to 1 is down counter. In some languages you can use the for loop to count both up and down. In Ruby down counter is provided by downto method.