Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions src/edu/macalester/comp124/stringtransformer/Scrambler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package edu.macalester.comp124.stringtransformer;

import acm.util.RandomGenerator;

/**
* Created by Marcus Ulmer on 2/27/14.
*/
public class Scrambler extends StringTransformer{
@Override
public String transform(String s) {
//deals with caps
boolean wordHasLeadingCap = false;
if (Character.isUpperCase(s.charAt(0))){
wordHasLeadingCap = true;
}
s= s.toLowerCase();
RandomGenerator generator = new RandomGenerator();
char[] wordArray;
wordArray = new char[s.length()]; //following pattern from JavaDoc for array
char[] scrambled;
scrambled = new char[s.length()];
//puts s into an array
for(int i=0; i < s.length();i++){
wordArray[i] = s.charAt(i);
}
//picks characters at random and puts them in the new array,
//then puts them at the end of their array and doesn't scan that far.
for(int i=0; i < s.length();i++){
int place = generator.nextInt(0,wordArray.length - (i+1));
scrambled[i] = wordArray[place];
//code based on template from <http://stackoverflow.com/questions/13766209/effective-swapping-of-elements-of-an-array-in-java>
char temp = wordArray[place]; //intended idea here is to put the used letters at the end of the string and then not read them -
wordArray[place] = wordArray[wordArray.length - (i+1)];
wordArray[wordArray.length - 1] = temp;
}
String scrambledWord = "";
for (int i=0; i < scrambled.length; i++){
scrambledWord += scrambled[i];
//checks if the word should be capitalised
if (wordHasLeadingCap && i == 0){
scrambledWord = scrambledWord.toUpperCase();
}
}

return scrambledWord;
}
@Override
public String toString() {
return "All scrambled.";
}
}
25 changes: 25 additions & 0 deletions test/edu/macalester/comp124/stringtransformer/ScramblerTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package edu.macalester.comp124.stringtransformer;

import org.junit.Test;

import static junit.framework.Assert.assertEquals;

/**
* Created by Marcus Ulmer on 2/27/14.
*/
public class ScramblerTest {
private final StringTransformer scrambler = new Scrambler();
/*I ended up doing mostly manual testing in a console program environment:
I had a bunch of errors with length vs. index of arrays, so that was more suited.
Couldn't figure out how to use || with strings, so testing options were pretty limited
due to randomness.*/
@Test
public void dealsWithCaps() {
assertEquals(("A"), scrambler.transform("A"));
}

@Test
public void preservesString() {
assertEquals("a", scrambler.transform("a"));
}
}