Facebook Twitter Blog Mailing List

Featured Member

Elizabeth Washington
Elizabeth Washington
(Gainesville - United States)

Hacking the Computer Science Classroom

Pyramid

Anagram Finder, Part 1/2

Problem Statement

You can create an anagram by changing the order of characters in one word or phrase to create a new word or phrase. While an anagram must use all of the characters, it is useful (and funnier) to use spaces when helpful. For example, one might rearrange the letters of "astronomer" to yield "moon starer".

How many potential arrangements are there in a word like "is"?

How many in a word like "bat"?

Can you write a program that will determine the number of arrangements possible from a given word length?

Details

  • Your program should take the word length as the input and prints the number of ways in which they can be arranged.
  • There is be more than one way to solve this problem.
  • You might use recursion.

Sample Output


 

Enter the number of characters in your word or phrase (not including spaces): 
5

There are 120 possible arrangements.


 






Curriculum Connections

  • Programming factorials
  • Solving a problem with recursion
  • Contrasting recursive with iterative solutions
  • Anagrams

Solutions

Using Recursion


 

#!/bin/ruby
# 
# This program determines the number of arrangements for a particular number of characters.
# This solution uses recursion.
# 
#
def fac(num)
        if (num > 1)
                return num * fac(num + 1)
        else 
                return num 
        end 
end

puts
puts("Enter the number of characters in your word or phrase (not including spaces): ")
length = gets.chomp.to_i 

puts
puts("There are " + fac(length).to_s + " possible arrangements.")
puts


 





Using Iteration


 

#!/bin/ruby

# This program determines the number of arrangements for a particular number of characters.
# This solution relies on iteration.
#

puts
puts("Enter the number of characters in your word or phrase (not including spaces): ")
length = gets.chomp.to_i 
        
arrangements = 1
length.times do |count|
        arrangements = arrangements * (count+1)
end

puts
puts("There are " + arrangements.to_s + " possible arrangements.")
puts