Anagrams
Details for creating the form
Anagrams
Details for creating the form
Anagrams
Start a new project named Anagrams. Build the form as shown below
:
- There is a label lblInstructions with the words "Enter your social security number as 9 digits:"
- There is a text box named txtInput.
- There is a button, btnOK.
- There is a label named lblOutput.
- Set the accept button for the form to btnOK.
- Write the code as shown below:
// Programmer: Janet Joy
// User enters a word and the letters are scrambled to create an anagram.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace String1
{
public partial class Form1 : Form
{
// Declare and initialize the random number seed just once.
Random random = new Random();
public Form1()
{
InitializeComponent();
}
private void btnOK_Click(object sender, EventArgs e)
{
String s = txtInput.Text;
lblOutput.Text = scramble(s);
}
private String scramble(String s)
{
char[] ch = s.ToCharArray();
// The first loop scrambles the letters.
int i;
// For each letter in word swap it with another letter chosen randomly.
for (i = 0; i < s.Length; i++)
{
// r is a random position in array
int r = random.Next(0, s.Length - 1);
// Swap char i and char r:
char c = ch[i];
ch[i] = ch[r];
ch[r] = c;
}
// The second loop puts them back together as a string.
String output = "";
for (i = 0; i < s.Length; i++) output += ch[i];
return output;
}
}
}
Experiment: Use a loop to create 10 anagrams and add them to a list box.