Commit a9f88644 authored by Siyu Zhang's avatar Siyu Zhang
Browse files

update rest

parent 32138bae
import java.util.*;
import java.io.*;
public class Lab10
{
public static void main (String[] args) throws Exception
{
BufferedReader infile = new BufferedReader (new FileReader(args[0]));
HashSet<String> hash = new HashSet<String>();
while (infile.ready())
{
String word = infile.readLine();
if (!hash.add(word))
{
System.out.println("NOT UNIQUE");
System.exit(0);
}
}
infile.close();
System.out.println("UNIQUE");
}
}
\ No newline at end of file
import java.io.*;
import java.util.*;
public class Timing
{
public static void main( String[] args ) throws Exception
{
final long MILLISEC_PER_SEC=1000;
final long SEC_PER_MIN = 60;
long startTime = System.currentTimeMillis();
// ....ALL YOUR MAIN CODE IN HERE
BufferedReader infile = new BufferedReader (new FileReader(args[0]));
//HashSet<String> hash = new HashSet<String>(); //small.txt: runtime: 1 millisec large.txt: runtime: 1 sec and 804 millisec (thousandths)
//ArrayList<String> arr = new ArrayList<String>(); //small.txt: runtime: 191 millisec large.txt: runtime: infinite!!!!!!!
TreeSet<String> tree = new TreeSet<String>(); //small.txt: runtime: 2 millisec large.txt: runtime: 2 sec and 51 millisec (thousandths)
while (infile.ready())
{
String word = infile.readLine();
//if (arr.contains(word))
if (!tree.add(word))
//if (!hash.add(word))
{
System.out.println("NOT UNIQUE!");
long stopTime = System.currentTimeMillis();
long elapsedMillisec = stopTime-startTime;
long elapsedSec = elapsedMillisec/MILLISEC_PER_SEC;
long elapsedMin = elapsedSec/SEC_PER_MIN;
elapsedMillisec %= MILLISEC_PER_SEC;
System.out.format("\nYour program took %d min and %s sec and %d millisec (thousandths) to execute\n",elapsedMin,elapsedSec, elapsedMillisec);
System.exit(0);
}
//arr.add(word);
/*BufferedReader infile = new BufferedReader (new FileReader(args[0]));
String prev = infile.readLine();
while (infile.ready())
{
String next = infile.readLine();
if (prev.equals(next))
{
System.out.println("NOT UNIQUE!");
System.exit(0);
}
prev = next;
}
System.out.println("UNIQUE");*/
}
infile.close();
System.out.println("UNIQUE");
// THE VARY LAST CHUNK OF CODE IN YOUR MAIN *****REMOVE BEFORE HANDIN*****
long stopTime = System.currentTimeMillis();
long elapsedMillisec = stopTime-startTime;
long elapsedSec = elapsedMillisec/MILLISEC_PER_SEC;
long elapsedMin = elapsedSec/SEC_PER_MIN;
elapsedMillisec %= MILLISEC_PER_SEC;
System.out.format("\nYour program took %d min and %s sec and %d millisec (thousandths) to execute\n",elapsedMin,elapsedSec, elapsedMillisec);
}
}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
import java.io.*;
import java.util.*;
public class Exercise1
{
public static void main( String args[] )
{
if (args.length < 1)
{
System.out.println("\nYou must enter an input filename on cmd line!\n");
System.exit(0);
}
String infileName = args[0];
Scanner infile = null;
do
{
try
{
infile = new Scanner ( new File(infileName) );
break;
}
catch (FileNotFoundException fnfe)
{
System.out.print("Bad filename :=( Enter a valid input file name: ");
Scanner scanner = new Scanner(System.in);
infileName = scanner.next();
}
}
while (true);
int tokenCnt=0;
while (infile.hasNext())
{
String token = infile.next();
System.out.printf("%d: %s\n", tokenCnt++, token);
}
}
} //End Lab11
\ No newline at end of file
import java.io.*;
import java.util.*;
public class Exercise2
{
public static void main( String args[] )
{
Scanner kbd = new Scanner(System.in);
do
{
try
{
System.out.print("Enter a number between 1 and 100 ");
int x = kbd.nextInt();
if (x < 1 || x > 100)
{
throw new Exception("Out of Range Exception. Must be in 1..100\n");
}
System.out.printf("You entered %d\n", x );
break;
}
catch (InputMismatchException e)
{
System.out.print("Input not a number. Try again.\n");
kbd.next();
}
catch (Exception e)
{
System.out.println(e);
}
}
while (true);
} //END main
} //EOF
\ No newline at end of file
Hello World
3.14159
save the whales
1319 Mockingbird Lane
\ No newline at end of file
12
34 56 78
31 42
55
7
// Lab2.java
import java.io.*; // BufferedReader
import java.util.*; // Scanner to read from a text file
public class Lab2
{
public static void main (String args[]) throws Exception // we NEED this 'throws' clause
{
// ALWAYS TEST FIRST TO VERIFY USER PUT REQUIRED CMD ARGS
if (args.length < 3)
{
System.out.println("\nusage: C:\\> java Lab2 <input file name> <lo> <hi>\n\n");
// i.e. C:\> java Lab2 P2input.txt 1 30
System.exit(0);
}
// grab args[0] and store into a String var named infile
String infileName = args[0];
// grab args[1] and conver to int then store into a var named lo
int lo = Integer.parseInt(args[1]);
// grab args[2] and conver to int then store into a var named hi
int hi = Integer.parseInt(args[2]);
// STEP #1: OPEN THE INPUT FILE AND COMPUTE THE MIN AND MAX. NO OUTPUT STATMENTS ALLOWED
Scanner infile = new Scanner( new File(infileName) );
int min, max;
min = max = infile.nextInt(); // WE ASSUME INPUT FILE HAS AT LEAST ONE VALUE
while ( infile.hasNextInt() )
{
int num1 = infile.nextInt();
if (! infile.hasNextInt())
{
if (num1 > max)
max = num1;
else if (num1 < min)
min = num1;
break;
}
int num2 = infile.nextInt();
if (num1 > num2)
{
if (num1 > max)
max = num1;
if (num2 < min)
min = num2;
}
else
{
if (num1 < min)
min = num1;
if (num2 > max)
max = num2;
}
// YOUR CODE HERE FIND THE MIN AND MAX VALUES OF THE FILE
// USING THE LEAST POSSIBLE NUMBER OF COMPARISONS
// ASSIGN CORRECT VALUES INTO min & max INTHIS LOOP.
// MY CODE BELOW WILL FORMAT THEM TO THE SCREEN
// DO NOT WRITE ANY OUTPUT TO THE SCREEN
}
System.out.format("min: %d max: %d\n",min,max); // DO NOT REMOVE OR MODIFY IN ANY WAY
// STEP #2: DO NOT MODIFY THE REST OF MAIN. USE THIS CODE AS IS
// WE ARE TESTING EVERY NUMBER BETWEEN LO AND HI INCLUSIVE FOR
// BEING PRIME AND/OR BEING PERFECT
for ( int i=lo ; i<=hi ; ++i)
{
System.out.print( i );
if ( isPrime(i) ) System.out.print( " prime ");
if ( isPerfect(i) ) System.out.print( " perfect ");
System.out.println();
}
} // END MAIN
// *************** YOU FILL IN THE METHODS BELOW **********************
// RETURNs true if and only if the number passed in is perfect
static boolean isPerfect( int n )
{
int sum = 0;
for (int p = 1; p < n; p++)
{
if (n % p == 0)
sum += p;
}
return n == sum; // (just to make it compile) YOU CHANGE AS NEEDED
}
// RETURNs true if and only if the number passed in is prime
static boolean isPrime( int n )
{
// (just to make it compile) YOU CHANGE AS NEEDED
for (int div = 2; div <= n; div++)
{
if (div == n)
return true;
if (n % div == 0)
break;
}
return false;
}
} // END Lab2 CLASS
\ No newline at end of file
This diff is collapsed.
31 145 70 5 27 103 71 140 8 162 98 153 8 109 103 31 145 157 27 90 75 19 23 25 69
\ No newline at end of file
/* Lab3.java InsertInOrder */
import java.util.*;
import java.io.*;
public class Lab3
{
static final int INITIAL_CAPACITY = 5;
public static void main( String args[] ) throws Exception
{
if (args.length < 1 )
{
System.out.println("\nusage: C:\\> java Lab3 L3input.txt\n");
System.exit(0);
}
Scanner infile = new Scanner( new File( args[0] ) );
int[] arr = new int[INITIAL_CAPACITY];
int count= 0;
while (infile.hasNextInt())
{
if ( count == arr.length ) arr = upSize( arr );
insertInOrder( arr, count, infile.nextInt() );
++count; //通过count来计算放入的个数or初始化的个数,但是下标值是count-1
}
infile.close();
printArray( "SORTED ARRAY: ", arr, count );
}
static void printArray( String caption, int[] arr, int count )
{
System.out.print( caption );
for( int i=0 ; i<count ;++i )
System.out.print(arr[i] + " " );
System.out.println();
}
static void insertInOrder( int[] arr, int count, int key ) //插入指定key
{
int i;
for (i = count - 1; i >= 0; i--)
{
if (key > arr[i]) //如果key比array从小到大sorted后最后一个还大,就说明是最大的,break直接把key赋给array最后一个的位置,
{
break;
}
arr[i + 1] = arr [i]; //如果不就arr[i]向右移一位,for循环后找到key适合的位置,break 把key放入正确的位置上
}
arr[i + 1] = key;
}
static int[] upSize( int[] fullArr ) //两倍扩容
{
int[] newArr = new int[fullArr.length * 2];
for (int i = 0; i < fullArr.length; i++)
newArr[i] = fullArr[i]; //deep copy
return newArr;
}
} // END LAB3
\ No newline at end of file
import java.util.*;
import java.io.*;
public class Lab4
{
public static void main(String[] args) throws Exception
{
if (args.length < 1)
{
System.out.println("\nusage: C:\\> java Lab4 jumbles.txt\n");
System.exit(0);
}
BufferedReader infile = new BufferedReader( new FileReader(args[0]) );
ArrayList<String> wordList = new ArrayList<String>();
while (infile.ready())
{
wordList.add(infile.readLine());
}
infile.close();
Collections.sort(wordList); //collections类的一个静态方法,所以可以通过类名直接访问此方法
//ArrayList是Collections类的一个子类
for (String word : wordList)
{
System.out.println(word + " " + canonical(word));
}
}
static String canonical(String word) //通过此方法,把单词变成按照字母顺序排列的形式
{
char[] letters = word.toCharArray(); //先通过ArrayList里面toCharArray的方法把字符串转换成一个个char字母并放入
//char 数组中
Arrays.sort(letters); //通过Array类中的Arrays.sort()静态方法来排序char数组里面的字母,所以可以通过类名直接访问此方法
String newWord = new String(letters); //通过new一个String,把char转换为一个String的单词
return newWord;
}
}
\ No newline at end of file
nwae
eslyep
rpeoims
ettniner
ahicryrhe
dica
dobol
nyegtr
cukklen
warllc
addej
baltoc
mycall
dufil
preko
dupled
yaldde
lasia
nekel
laurib
lappor
couph
celer
ettorp
wardty
iddec
pypin
hartox
perrim
gluhc
irrpo
braney
meefal
lubly
noper
dobeny
kutbec
shewo
alvan
annaab
mopsie
nokte
rodug
rebisc
hoybis
milit
pudmy
hucnah
genjal
\ No newline at end of file
/*
Coin.java THIS IS THE ONLY FILE YOU HAND IN
THERE IS NO MAIN METHOD IN THIS CLASS!
*/
import java.util.Random;
public class Coin
{
private final int HEADS = 1; //声明常量HEADS和TAILS
private final int TAILS = 0;
private int numHeads, numTails;
private Random r;
public int getNumHeads()
{
return numHeads;
}
public int getNumTails()
{
return numTails;
}
private void setNumHeads(int h)
{
numHeads = h;
}
private void setNumTails(int t)
{
numTails = t;
}
public void reset() //重置游戏的方法
{
setNumHeads(0);
setNumTails(0);
}
public Coin(int n) //full constructor 将Coin(seed)放入Random中,让产生的随机数相同
{
r = new Random(n);
setNumHeads(0);
setNumTails(0);
}
public String flip()
{
int test = r.nextInt(2); //结果是1或者2,50%的几率
if (test == TAILS)
{
setNumTails(getNumTails() + 1); //加一是因为原本是0
return "T";
}
else
{
setNumHeads(getNumHeads() + 1);
return "H";
}
}
} // END COIN CLASS
\ No newline at end of file
/*
CoinTester.java - tests the Coin class by
constructing variables and calling it's methods
DO NOT MODIFY. DO NOT HAND IN. WE WILL USE THIS FILE TO TEST YOUR COIN CLASS
*/
import java.util.Random;
public class CoinTester
{
public static void main( String args[] )
{
Coin coin1 = new Coin( 17 ); // 17 is the SEED
Coin coin2 = new Coin( 13 ); // 13 is the SEED
// FLIP COIN1, PRINT RESULTS
System.out.println("\nFlipping Coin1 20 times.");
for (int i=0 ; i<20 ; ++i)
System.out.print( coin1.flip() + " " ); // Equal chance of head or tail
System.out.println();
System.out.println("# heads: " + coin1.getNumHeads() +
" # tails: " + coin1.getNumTails() );
coin1.reset(); // sets numHeads and numTails back to zero;
// FLIP COIN2, PRINT RESULTS
System.out.println("\nFlipping Coin2 10 times.");
for (int i=0 ; i<10 ; ++i)
System.out.print( coin2.flip() + " " ); // Equal chance of head or tail
System.out.println();
System.out.println("# heads: " + coin2.getNumHeads() +
" # tails: " + coin2.getNumTails() );
coin2.reset(); // sets numHeads and numTails back to zero;
// FLIP COIN1 AGAIN, PRINT RESULTS
System.out.println("\nFlipping Coin1 again 35 times.");
for (int i=0 ; i<35 ; ++i)
System.out.print( coin1.flip() + " " ); // Equal chance of head or tail
System.out.println();
System.out.println("# heads: " + coin1.getNumHeads() +
" # tails: " + coin1.getNumTails() );
coin1.reset(); // sets numHeads and numTails back to zero;
Random ran = new Random(17);
int r1 = ran.nextInt(10);
for (int i = 0; i < 10; i++)
{
System.out.println(r1);
}
}// END main
}//EOF
\ No newline at end of file
public class MyString
{
private char[] letters;
public MyString( String other )
{
this.letters = other.toCharArray(); //将String变成char数组
// MUST BE DEEP COPY: USE REAL STRING'S BUILT IN METHOD
// TO RETURN A DEEP COPY OF THE THE UNDERLYING CHAR ARRAY
}
public MyString( MyString other )// DONT do this -> letters = other.letters BECUASE THAT IS SHALLOW COpY!!!
{
this.letters = new char [other.length()]; //建一个和other长度一样的letters char数组
for (int i = 0; i < other.length(); i++) //deep copy将每个值一个个放入this.letters的数组里
{
this.letters[i] = other.letters[i];
}
}
public int length() //返回数组大小
{
int count = this.letters.length;
return count;
}
public char charAt(int index) //返回放入的index对应的letters数组中的char
{
return this.letters[index]; // THE null CHAR
}
int compareTo(MyString other)
{
for (int i = 0; i < this.length(); i++) //通过index一个个比较char数组中对应字母是否相同,仅限this长度大于other长度的时候
{
if (i >= other.length()) //看i和other长度比较,大于等于的情况都说明this长度大于other,因为i<this.length
return 1;
if (this.letters[i] > other.letters[i]) //this和other相同index对比ascii,this大返回1,否则返回-1
return 1;
if (this.letters[i] < other.letters[i])
return -1;
}