Top Banner
Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1 Contest Algorithms: 2. Java Features
74

Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Jan 21, 2016

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

1

Contest AlgorithmsJanuary 2016

Look at some features of Java used in many competition problems.

2. Java Features

Contest Algorithms: 2. Java Features

Page 2: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms: 2. Java Features

2

1. Multi-dimensional Arrays 2. Arrays class: sort, binary search, comparators 3. Strings 4. Regular Expressions 5. Bitwise Ops

Overview

Page 3: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms: 2. Java Features

3

Use a two-dimensional array to represent a matrix or a table.

1. Multi-dimensional Arrays (2D/3D)

Page 4: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

An array is the fastest way to do random access to data

But an array's size is fixed If it runs out of space, you have to create a new array and

copy everything over, which is slow

Array Features

Page 5: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms 5

import java.io.*;import java.util.*;

public class UseGraph // use Main in contests{ public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); // Scanner sc = new Scanner(new File("graphData.txt")); // for testing

int numVs = sc.nextInt(); int[][] adjMat = new int[numVs][]; // use numVs as no. of rows for (int i = 0; i < numVs; i++) { adjMat[i] = new int[numVs]; // create ith row array for (int j = 0; j < numVs; j++) // fill row adjMat[i][j] = sc.nextInt(); } :

Fill an Integer Matrix see UseGraph.javain Part 1

Page 6: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Two-dimensional Arrays

6

0 1 2 3 4

0

7

0 1 2 3 4

1 2 3 4

0 1 2 3 4 matrix[2][1] = 7;

matrix = new int[5][5];

3

7

0 1 2

0 1 2

int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} };

1

2

3

4

5

6

8

9

10

11

12

array.length == 4

array[0].length == 3

matrix.length == 5

matrix[0].length == 5

no. rows

no. columns

Page 7: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms: 2. Java Features

7

int[][] array = new int[4][3];array[0][0] = 1; array[0][1] = 2; array[0][2] = 3; array[1][0] = 4; array[1][1] = 5; array[1][2] = 6; array[2][0] = 7; array[2][1] = 8; array[2][2] = 9; array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;

int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};

==

Page 8: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

int[][] x = new int[3][4];

Lengths of Two-dimensional Arrays

8

x

x[0]

x[1]

x[2]

x[0][0] x[0][1] x[0][2] x[0][3] x[1][0] x[1][1] x[1][2] x[1][3] x[2][0] x[2][1] x[2][2] x[2][3]

x.length is 3

x[0].length is 4

x[1].length is 4

x[2].length is 4

Page 9: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};

9

array.lengtharray[0].lengtharray[1].lengtharray[2].lengtharray[3].length

array[4].length ArrayIndexOutOfBoundsException

Page 10: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Each row in a two-dimensional array is itself an array. So, the rows can have different lengths. Such an array is known as a ragged array.

int[][] matrix = { {1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5}};

Ragged Arrays

10

matrix.length is 5matrix[0].length is 5matrix[1].length is 4matrix[2].length is 3matrix[3].length is 2matrix[4].length is 1

Page 11: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

11

1 2 3 4 5

int[][] triangleArray = { {1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5} };

1 2 3 4 1 2 3 1 2 1 2

Page 12: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

for (int row = 0; row < matrix.length; row++) { for (int col = 0; col < matrix[row].length; col++) matrix[row][col] = (int)(Math.random() * 100);}

Initializing arrays with random values

12

Page 13: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

int total = 0;for (int row = 0; row < matrix.length; row++) { for (int col = 0; col < matrix[row].length; col++) total += matrix[row][col];}

Summing all elements

13

Page 14: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

for (int col = 0; col < matrix[0].length; col++) { int total = 0; for (int row = 0; row < matrix.length; row++) total += matrix[row][col]; System.out.println("Sum for column " + col + " is " + total);}

Summing elements by column

14

Page 15: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { int i1 = (int)(Math.random() * matrix.length); int j1 = (int)(Math.random() * matrix[i].length); // Swap matrix[i][j] with matrix[i1][j1] int temp = matrix[i][j]; matrix[i][j] = matrix[i1][j1]; matrix[i1][j1] = temp; }}

Random shuffling

15

Page 16: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

 double[][][] scores = new double[10][5][2];

16

Three-dimensional Arrays

Page 17: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms: 2. Java Features

17

Matrix.java contains methods for creating 2D matricies of doubles, adding, multiplying, taking powers, etc.

Also Gaussian Elimination

Basic Matrix Functions

see Matrix.java

Matrix(int M, int N)Matrix(double[][] data)Matrix(double[] arr, int side)

int getRows()int getCols()double[][] getData()

void setElem(int i, int j, double val)double getElem(int i, int j)

Matrix transpose()Matrix add(Matrix B)Matrix subtract(Matrix B)boolean eq(Matrix B)Matrix multiply(Matrix B)Matrix power(long exp)double[] flatten()Matrix solve(Matrix rhs)void print()

// static methodsMatrix random(int M, int N)Matrix identity(int N)

Page 18: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms: 2. Java Features

18

public static void main(String[] args) { double[][] d = { { 1, 2, 3 }, { 4, 5, 6 }, { 9, 1, 3} }; Matrix D = new Matrix(d); D.print(); System.out.println("Value at (0,1): " + D.getElem(0,1));

Matrix A = Matrix.random(5, 5); A.print();

Matrix B = A.transpose(); B.print();

Matrix C = Matrix.identity(5); C.print();

A.add(B).print(); B.multiply(A).print();

// shouldn't be equal since AB != BA in general System.out.println( A.multiply(B).eq(B.multiply(A)) );

Matrix b = Matrix.random(5, 1); b.print(); Matrix x = A.solve(b); x.print(); A.multiply(x).print(); } // end of main()

Usage

Page 19: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms: 2. Java Features

19

There's also a less fully-featured boolean matrix class see BoolMat.java

It illustrates how to implement 'add' and 'multiply' for boolean values

'add' uses boolean OR (||) multiply uses boolean AND (&&)

Boolean Matrix

Page 20: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

A set of static utility methods fill(): fill an array with a value equals(): compare two arrays for equality

Probably most useful are:

2. Arrays class

static void sort(Object [] a);

static void sort(Object [] a, Comparator c);

static int binarySearch(Object [] a, Object key);

static int binarySearch(Object [] a, Object key, Comparator c)

Page 21: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Sorts the objects into ascending order A stable sort:

equal elements are not reordered You can specify a range

fromIndex to toIndex-1 The objects need to have a Comparator class

or implement Comparable

Arrays.sort() see GenericSorting.java

Page 22: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

interface COMPARATOR<T> java.util

Methods

int compare(T x, T y) Compares its two arguments for order. Returns a negative integer, zero, or a positive integer to specify that x is less than, equal to, or greater than y.

boolean equals(Object obj) Returns true if this object equals obj and false otherwise.

The Comparator Interface

continued

Page 23: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Comparing Circlespublic class Circle{ private double xCenter, yCenter; private double radius;

public Circle(double x, double y, double r) { xCenter = x; yCenter = y; radius = r; }

public double getX() { return xCenter; }

:

see Circle.java

Page 24: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

public double getY() { return yCenter; }

public double getRadius() { return radius; }

public double getArea() { return Math.PI * radius * radius; }

: // more methods, but no comparison function

} // end of Circle class

Page 25: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Comparing Circle Radiipublic class RadiiComp implements Comparator<Circle>{ public int compare(Circle c1, Circle c2) { double radC1 = c1.getRadius(); double radC2 = c2.getRadius();

// returns < 0 if radC1 < radC2, // 0 if radC1 == radC2, // > 0 if radC1 > radC2 return (int)(radC1 – radC2); } // end of compare()

// equals() is inherited from Object superclass

} // end of RadiiComp class

see RadiiComp.java

Page 26: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Comparing Circle Positionspublic class DistComp implements Comparator<Circle>{ public int compare(Circle c1, Circle c2) { double c1Dist = (c1.getX() * c1.getX()) + (c1.getY() * c1.getY()); double c2Dist = (c2.getX() * c2.getX()) + (c2.getY() * c2.getY());

// returns < 0 if c1Dist < c2Dist, // 0 if c1Dist == c2Dist, // > 0 if c1Dist > c2Dist return (int)(c1Dist - c2Dist); } // end of compare()

// equals() is inherited from Object superclass} // end of DistComp class

see DistComp.java

Page 27: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Comparing Circles in Two WaysCircle c1 = new Circle(0, 0, 5); // (x,y),rCircle c2 = new Circle(3, 2, 7);

RadiiComp rComp = new RadiiComp();if (rComp.compare(c1, c2) < 0) System.out.println("Circle 1 is smaller than circle 2");

DistComp dComp = new DistComp();if (dComp.compare(c1, c2) < 0) System.out.println("Circle 1 is nearer to origin than circle 2");

Circle 1 is smaller than circle 2Circle 1 is nearer to origin than circle 2

see UseCircles.java

Page 28: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms: 2. Java Features

28

// sort(Object [] a, Comparator c)Circle[] circles = // ... add circle objects;

Arrays.sort(circles, new RadiiComp()); // circles will be sorted by ascending radii

Arrays.sort(circles, new DistComp()); // circles will be sorted by ascending distance from origin

Sorting Circlessee UseCircles.java

Page 29: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

static int binarySearch(Object [] a, Object key)static int binarySearch(Object [] a, Object key, Comparator c) Only usable on a sorted array If there are multiple equal elements, there is no

guarantee which one will be found Returns:

Index if found the key (-(insertion point) - 1) if key not found

Array.binarySearch()

Page 30: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms: 2. Java Features

30

int[] values = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int index = Arrays.binarySearch(values, 8); // find '8'

System.out.println("Index = " + index);

System.out.println("Value = " + values[index]);

OutputIndex = 7

Value = 8

Examples

Page 31: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms: 2. Java Features

31

int[] values = { 0, 2, 4, 8 };int index = Arrays.binarySearch(values, 400); // no such valueSystem.out.println(index);

Output-5 // -4 -1

Page 32: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms: 2. Java Features

32

Circle[] circles = // ... add circle objectsArrays.sort(circles, new DistComp()); // must be sorted before search

Circle c = new Circle(0, 0, 3); // (x,y),r

int idx = Arrays.binarySearch(circles, c, new DistComp()); // will try to find a circle that is same distance from origin as c

Search for a Circlesee UseCircles.java

Page 33: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

The Comparable Interface

The Comparable<T> interface is another way to compare objects.

The interface defines a single method:

public interface Comparable<T>{ int compareTo(T item); }

Page 34: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

compareTo() Meaning

compareTo() should return an integer that is negative, 0, or positive.

Meaning: obj.compareTo(item) < 0 when obj < item obj.compareTo(item) == 0 when obj == item obj.compareTo(item) > 0 when obj > item

Page 35: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Time24 Class with Comparablepublic class Time24 implements Comparable<Time24>{ . . . public int compareTo(Time24 item) //compares times { int time = hour*60 + minute; // use minutes int ttime = item.hour*60 + item.minute;

// compare, returning -1, 0, or 1 if (time < ttime) return -1; else if (time == ttime) return 0; else return 1; }}

Time24 t1 = new Time24(12,30);Time24 t2 = new Time24(15,10);int res = t1.compareTo(t2); // -1

see Time24.java

Page 36: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Comparator vs. Comparable

• Comparator.compare(T x, T y) comparison is done between two objects, x and y the method is implemented outside the T class

• Comparable.compareTo(T y) comparison is done between 'this' object and object y the method is implemented by the T class

Page 37: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Benefits of Comparator

The comparison code is in a separate place from the other code for a class.

1. This means that the same objects can be compared in different ways by defining different Comparators

see the two comparators for circles

Page 38: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

String message = new String("Welcome to Java");

String message = "Welcome to Java";

3. Strings

38

Page 39: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Escape Characters

n 39

How can you make a String that has quotes? String foo = "oh so cool"; String bar = "oh so \"cool\", more so";

Escape character is \ (the backslash)

Page 40: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

String s1 = new String("Welcome");String s2 = "welcome";

if (s1.equals(s2)) // s1 and s2 have the same contents if (s1 == s2

// s1 and s2 have the same reference

String Comparisons

40

Almost always, thisis the method you want.

Page 41: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

compareTo(Object object)

String s1 = new String("Welcome");

String s2 = "welcome";

if (s1.compareTo(s2) > 0) // s1 is greater than s2

else if (s1.compareTo(s2) == 0) // s1 and s2 have the same contents else // s1 is less than s2

41

Page 42: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Do not use message[0] Use message.charAt(index) Index starts from 0

Retrieving Individual Chars in a String

42

W e l c o m e t o J a v a

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

message

Indices

message.charAt(0) message.charAt(14) message.length() is 15

Page 43: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

String s1 = "Welcome to Java";String s2 = s1.substring(0, 11) + "HTML";

Extracting Substrings

43

W e l c o m e t o J a v a

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

message

Indices

message.substring(0, 11) message.substring(11)

Page 44: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

"Welcome".toLowerCase() returns a new string, welcome"Welcome".toUpperCase() returns a new string, WELCOME

" Welcome ".trim() returns a new string, Welcome

"Welcome".replace('e', 'A') returns a new string, WAlcomA"Welcome".replaceFirst("e", "AB") returns a new string, WABlcome"Welcome".replace("e", "AB") returns a new string, WABlcomAB"Welcome".replace("el", "AB") returns a new string, WABlcome

Converting, Replacing

44

Page 45: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

String[] tokens = "Java#HTML#Perl".split("#", 0);for (int i = 0; i < tokens.length; i++) System.out.print(tokens[i] + " ");

Splitting a String

45

Java HTML Perldisplays

Page 46: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

"Welcome to Java".indexOf('W') returns 0."Welcome to Java".indexOf('x') returns -1."Welcome to Java".indexOf('o', 5) returns 9.

"Welcome to Java".indexOf("come") returns 3."Welcome to Java".indexOf("Java", 5) returns 11."Welcome to Java".indexOf("java", 5) returns -1.

"Welcome to Java".lastIndexOf('a') returns 14.

Finding a Char or a Substring

46

Page 47: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

There are several valueOf() methods for converting a character, an array of characters, and numeric values into a string.

e.g.String.valueOf(5.44) "5.44"

Converting into a String

47

Page 48: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms: 2. Java Features

48

public static void main(String[] args) { if (args.length != 2) { System.out.println("Usage: java BaseChange <integer> <base>"); return; } int num = parseInt(args[0]); int base = parseInt(args[1]); if (base < 2) { System.out.println("Base cannot be < 2; using 16"); base = 16; } else if (base > Character.MAX_RADIX){ System.out.println("Base cannot be > " + Character.MAX_RADIX + "; using 16"); base = 16; } String baseVal = Integer.toString(num, base).toUpperCase(); System.out.println("Conversion of " + num + " to base " + base + " == " + baseVal);} // end of main()

Base Conversion (toString(n,radix))

see BaseChange.java

Page 49: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms: 2. Java Features

49

Execution

Page 50: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

The Character Class

50

java.lang.Character

+Character(value: char)

+charValue(): char

+compareTo(anotherCharacter: Character): int

+equals(anotherCharacter: Character): boolean

+isDigit(ch: char): boolean

+isLetter(ch: char): boolean

+isLetterOrDigit(ch: char): boolean

+isLowerCase(ch: char): boolean

+isUpperCase(ch: char): boolean

+toLowerCase(ch: char): char

+toUpperCase(ch: char): char

Constructs a character object with char value

Returns the char value from this object

Compares this character with another

Returns true if this character equals to another

Returns true if the specified character is a digit

Returns true if the specified character is a letter

Returns true if the character is a letter or a digit

Returns true if the character is a lowercase letter

Returns true if the character is an uppercase letter

Returns the lowercase of the specified character

Returns the uppercase of the specified character

Page 51: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

StringBuilder/StringBuffer can be used wherever a string is used

they are faster than String if you are doing a lot of string building

StringBuilder sb = new StringBuilder("hello");sb.add(" andrew");sb.add(" davison");

after the end of the building, convert to a String:String s = sb.toString();

StringBuilder and StringBuffer

51

Page 52: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms: 2. Java Features

52

Useful String Utilities

see StringFun.javaboolean isNullOrEmpty(String s)String toString(Exception e)String unquote(String s)String sort(String s) String removeAll(String s, char unwanted)String padRight(String s, int n) String padLeft(String s, int n) String getHexString(byte[] b)boolean onlyDigits(String s)boolean hasNDigits(String s, int n)boolean isBinary(String s)String stripControls(String s) String removeSpaceDups(String s)void appendToFile(String fnm, String s)String readAll(String fnm)ArrayList<String> toList(String[] arr)boolean contains(String[] arr, String s)String[] toArray(ArrayList<String> strsList)HashSet<String> toSet(String[] arr)

String reverse(String s)String[] reverse(String[] strs)String[] getWords(String s)String reverseWords(String s)String rotRight(String s)String rotLeft(String s)boolean isRotation(String s1, String s2) boolean isPalindrome(String s)String shift(String s, int shift) char shift(char ch, int shift)boolean isLetter(char ch)ArrayList<String> permutate(String s)boolean areAnagrams(String s1, String s2)String[] genSubsets(String s)int levDist(String s, String t)String join(String toJoin, Object[] listString join(String toJoin, List<String> list)String join(String toJoin, Set set)

Page 53: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms: 2. Java Features

53

public static void main(String[] args) { String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; String res = StringFun.reverse(s); System.out.println("Reverse: " + res);

s = "Could you pretty please reverse this sentence"; res = StringFun.reverseWords(s); System.out.println("Reverse Words: " + res );

String[] results = StringFun.getWords("Could you, if possible, help me!"); System.out.println("Words:"); for(String r : results) System.out.println(" " + r); :

Usage see StringFunTests.java

Page 54: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms: 2. Java Features

54

s = "superman"; System.out.println("Rotate right: " + StringFun.rotRight(s) ); System.out.println("Rotate left: " + StringFun.rotLeft(s) );

System.out.println("Is Palindrome: " + StringFun.isPalindrome("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); System.out.println("Is Palindrome: " + StringFun.isPalindrome("ABCDEFGHIJKKJIHGFEDCBA"));

results = StringFun.genSubsets("abcde"); System.out.println("Generate Subsets: {" + StringFun.join(", ", results) + "}");

int dist = StringFun.levDist("kitten", "sitting"); System.out.println("Edit Distance: " + dist); // 3

System.out.println("Rot4: " + StringFun.shift("andrew",4));

ArrayList<String> perms = StringFun.permutate("jim"); System.out.println("Permutations: {" + StringFun.join(", ", perms) + "}"); :

Page 55: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms: 2. Java Features

55

System.out.println("Remove all: " + StringFun.removeAll("algorithms", 'a'));

System.out.println("Pad right: \"" + StringFun.padRight("cat", 10) + "\"");

System.out.println("Is 5 digits: " + StringFun.hasNDigits("19745", 5));

String htxt = StringFun.readAll("hull1.txt"); System.out.println("Read all: \"" + htxt + "\"");

htxt = StringFun.stripControls(htxt); System.out.println("Read all: \"" + htxt + "\"");

htxt = StringFun.removeSpaceDups(htxt); System.out.println("Read all: \"" + htxt + "\""); } // end of main()

Page 56: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms: 2. Java Features

56

Page 57: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

A regular expression (regex) is a pattern for matching against a string.

You can use regular expressions for matching, replacing, and splitting strings.

4. Regular Expressions

57

Page 58: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Replacing and Splitting Strings

58

java.lang.String

+matches(regex: String): boolean

+replaceAll(regex: String, replacement: String): String

+replaceFirst(regex: String, replacement: String): String

+split(regex: String): String[]

Returns true if this string matches the pattern.

Returns a new string that replaces all matching substrings with the replacement.

Returns a new string that replaces the first matching substring with the replacement.

Returns an array of strings consisting of the substrings split by the matches.

Page 59: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

boolean b = "Java is fun".matches("Java.*");

String s = "Java Java Java".replaceAll("v\\w", "wi");

String s = "Java Java Java".replaceFirst("v\\w", "wi");

String[] s = "Java1HTML2Perl".split("\\d");

Examples

Page 60: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms: 2. Java Features

60

See the Pattern class documentation e.g. at https://docs.oracle.com/javase/8/docs/api/

java/util/regex/Pattern.html

Regex Documentation

Page 61: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

61

Regular Expression Matches Example x a specified character x Java matches Java . any single character Java matches J..a (ab|cd) a, b, or c ten matches t(en|im] [abc] a, b, or c Java matches Ja[uvwx]a [^abc] any character except Java matches Ja[^ars]a

a, b, or c [a-z] a through z Java matches [A-M]av[a-d] [^a-z] any character except Java matches Jav[^b-d] a through z [a-e[m-p]] a through e or Java matches m through p [A-G[I-M]]av[a-d] [a-e&&[c-p]] intersection of a-e Java matches with c-p [A-P&&[I-M]]av[a-d] \d a digit, same as [1-9] Java2 matches "Java[\\d]" \D a non-digit $Java matches "[\\D][\\D]ava" \w a word character Java matches "[\\w]ava" \W a non-word character $Java matches "[\\W][\\w]ava" \s a whitespace character "Java 2" matches "Java\\s2" \S a non-whitespace char Java matches "[\\S]ava" p* zero or more Java matches "[\\w]*" occurrences of pattern p p+ one or more Java matches "[\\w]+" occurrences of pattern p p? zero or one Java matches "[\\w]?Java" occurrence of pattern p Java matches "[\\w]?ava" p{n} exactly n Java matches "[\\w]{4}" occurrences of pattern p p{n,} at least n Java matches "[\\w]{3,}" occurrences of pattern p p{n,m} between n and m Java matches "[\\w]{1,9}" occurrences (inclusive)

Page 62: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Codeimport java.util.regex.*; public class RegexTest { public static void main(String args[]) { String pattern = "[a-z]+"; String text = "Now is the time";

Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(text); while (m.find()) System.out.println( text.substring( m.start(), m.end() ) ); }}

Output: owisthetime

see RegexTest.java

Page 63: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Test Rigpublic class TestRegex{ public static void main(String[] args) { if (args.length != 2) { System.out.println("Usage: java TestRegex string regExp"); System.exit(0); } System.out.println("Input: \"" + args[0] + "\""); System.out.println("Regular expression: \"" + args[1] + "\""); Pattern p = Pattern.compile(args[1]); Matcher m = p.matcher(args[0]); while (m.find()) System.out.println("Match \"" + m.group() + "\" at positions "+ m.start() + "-" + (m.end()-1)); } // end of main()} // end of TestRegex class

see TestRegex.java

Page 64: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

m.group() returns the string matched by the pattern usually used instead of String.substring()

Page 65: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.
Page 66: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

The Java tutorial on REs is very good: http://java.sun.com/docs/books/tutorial/

essential/regex/

Online tutorials: http://ocpsoft.com/opensource/

guide-to-regular-expressions-in-java-part-1/ and part-2

More Information on Regexs

Page 67: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms: 2. Java Features

67

"~" inverts a bit pattern

"<<" shifts a bit pattern to the left ">>" shifts a bit pattern to the right

">>>" shifts a zero into the leftmost pos, while the pos after ">>" depends on sign extension

& performs AND ^ performs OR |performs inclusive OR

5. Bitwise Operations

Page 68: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms: 2. Java Features

68

The most-significant-bit is on the left:10010110^ ^| |------- bit 0||-------------- bit 7

The value of bit 0 is 20, bit 1 is 21, ..., bit 7 is 27

A Word About Bit Order

Page 69: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms 69

c = a ^ b; /* 49 = 0011 0001 */ System.out.println("a ^ b = " + c );

c = ~a; /*-61 = 1100 0011 */ System.out.println("~a = " + c );

c = a << 2; /* 240 = 1111 0000 */ System.out.println("a << 2 = " + c );

c = a >> 2; /* 215 = 1111 */ System.out.println("a >> 2 = " + c );

c = a >>> 2; /* 215 = 0000 1111 */ System.out.println("a >>> 2 = " + c ); } // end of main()}

public class BitsTest { public static void main(String args[]) { int a = 60; /* 60 = 0011 1100 */ int b = 13; /* 13 = 0000 1101 */ int c = 0;

c = a & b; /* 12 = 0000 1100 */ System.out.println("a & b = " + c );

c = a | b; /* 61 = 0011 1101 */ System.out.println("a | b = " + c );

Code

a ^ b = 49~a = -61a << 2 = 240a >> 15a >>> 15

a & b = 12a | b = 61

see BitsTest.java

Page 70: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Bitwise Operations

Page 71: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms 71

Bitwise AND (&)

Bitwise inclusive OR(|) Bitwise exclusive OR(^)

Page 72: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms 72

Bitwise Assignment Ops

Page 73: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms 73

Work with binary numbers using Integer.parseInt() e.g. Integer.parseInt("101", 2);

creates an integer with the binary value of 101 (decimal 5).

Loop with binary:// loops from 5 up to and including 15for (int b = Integer.parseInt("0101",2); b <= Integer.parseInt("1111",2); b++) {

/* do stuff here */}

Using ParseInt

Page 74: Contest Algorithms January 2016 Look at some features of Java used in many competition problems. 2. Java Features 1Contest Algorithms: 2. Java Features.

Contest Algorithms 74

Low Level Bit Hacks You Absolutely Must Know http://www.catonmat.net/blog/low-level-bit-hacks-you-absolutely-

must-know/ 10 hacks, including: " Check if the integer is even or odd", "Test if the n-th bit

is set", "Set the n-th bit", "Unset the n-th bit", toggle the nth bit

Bit Twiddling Hacks https://graphics.stanford.edu/~seander/bithacks.html

Hacker's Delight, 2nd edHenry S. Warren

http://www.hackersdelight.org/

More Information on Bits BitFun.java