CS 199 EMP

Even More Practice

2 meetings every week Tuesday and Thursday

Each day has two timeslots for

  • Eastern timezones and American early risers

  • Eestern timezones and American afternoons

  • Make sure to keep up with the calendar

Format

  • 3 practice problems every session

  • focused on practical understanding of concepts covered recently in class

  • slides and material available after class

How to follow along

  • Small breakout rooms of working together

  • Work for 10-15 minutes together, feel free to use paper, whiteboards, online share tools.

  • Use the jeed playground on the 125 homepage for the interactive running

1) Function overloading

Function overloading is when you make different functions with the same name.

  • This is to deal with different types of and number of inputs

  • Different data types may be processed differently

int area(int l, int h) {
  return l * h;
}

float add(float l, float h) {
  return l * h
}

1) Function overloading (contd)

We distinguish functions via their signatures for overloading.

  • Signature = name + inputs(names, type, order)

  • area(int, int), area(float, float)

  • Note that having the return type different doesn't change the signatures. float area(int l, int h) and int area(int l, int h) are the same function as far as overloading is concerned.

  • Having the same type, order and number but different name does not work either. area(int a, int b) and area(int l, int h) are the same function as far as overloading is concerned.

1) Function overloading - Practice

Write two overloaded functions area to calculate the area of a circle and triangle

  • double area(double radius) - πr2\pi r^2. Feel free to use π=3.14159\pi = 3.14159

  • double area(double base, double height) - 12bh\frac{1}{2}bh

1) Function overloading - Starter code (10 minutes)

Feel free to try this in the homepage playground

double area(double radius) {
  return 0.0; // implement
}

double area(double base, double height) {
  return 0.0; // implement
}

2) Multidimensional arrays

  • Multidimensional arrays are just arrays where the elements are arrays.

int[][] idMatrix = {{1, 0},
                    {0, 1}};
double[][][] weightsForAI = {{{0.1, 0.2}, {0.2}}, 
                             {{0.3, 0.4}, {0.5}}};
                             

2) Multidimensional arrays - algorithms with them

  • For single dimensional arrays, often it pairs well with a for loop

  • For many dimensions we can use multiple nested for loops.

  • Loop variables we conventionally use i, j, k...

int[][] vals = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}};
for (int i = 0; i < vals.length; i++) {
  for (int j = 0; j < vals[i].length; j++) {
    System.out.print(vals[i][j] + " ");
  }
  System.out.println(); // newline
}

2) Multidimensional arrays - foreach loop

Sometimes when we don't need i, j or other counter variables we can use for each loops

int[][] vals = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}};
for (int[] subArr: vals) {
  for (int item: subArr) {
    System.out.print(item + " ");
  }
  System.out.println(); // newline
}

2) Multidimensional arrays - rows and cols

  • It's easy to start thinking of these as rows and columns, much like excel or graph paper

  • This works fine for 2d arrays where all sub arrays are the same length, but this falls part for 3d or 4d arrays, or when 'rows' have different lengths.

  • This can also limit your thinking in understanding what this data structure really is, which is simply arrays made of arrays.

2) Multidimensional array - Practice

  • Create a function double average(double[][] array) that takes the average of all the numbers in the array

  • Careful to make sure this works well with non rectuangular (sub arrays not equal) arrays. {{0.1}, {0.2, 0.3}} for example

2) Multidimensioanl array - Starter code (10 minutes)

double average(double[][] array) {
  return 0.0; // implement
}

double[][] arr = {{0.1}, {0.2, 0.3}};
System.out.println(average(arr));

3) String parsing

  • Strings are one of the most common data types programmings deal with because they represent any text

  • This file is a string, the code playground stores everything as a string, your email is a string.

  • Yet string are just text, so we need to often convert it to more useful data formats like int, double

3) String parsing - useful functions

These are the most useful functions you will use while dealing with this.

  • String substring(int begin) or String substring(int begin, int end) - begin is inclusive, end is exclusive - we use this to get a portion of a string out

  • String split(String delim) - splits a String based on what is given, commonly we split based on ,, :,\n (newline, note the \)

  • String trim() - removes starting and ending whitespace (so if a cat types it in we can deal with it)

  • String equals(String other) - use this to compare strings and not == (which sometimes fails)

3) String parsing - CSV

  • CSV Data file formats is super common in the real world for sending data by strings

  • Each entry is on a new line, you can use split them using \n

  • Each column is split by commas ,

3) String parsing - restaurant orders

  • Calculate the total revenue, each line has the name of the dish, price and number ordred

  • Return out the final result as a double

3) String parsing - starter code (15 minutes)

double calculateTotal(String csv) {
  return 0.0;
}

String orders = """
    Hot Dogs , 1, 67
    Sandwiches, 2, 321
    Fried Rice, 4, 542
    """;
System.out.println(calculateTotal(orders));

Solutions

Spoiler alert :P

1) Function overloading

double area(double radius) {
  return 3.14159 * radius * radius; // implement
}

double area(double base, double height) {
  return base * height / 2.0; // implement
}

2) Multidimensional arrays

double average(double[][] array) {
  double sum = 0.0;
  int ctr = 0;
  for (double[] s: array) {
    for (double num: s) {
      ctr++;
      sum += num;
    }
  }
  
  return sum / ctr;
}

double[][] arr = {{0.1}, {0.2, 0.3}};
System.out.println(average(arr));

3) CSV Parse

double calculateTotal(String csv) {
  double total = 0.0;
  String[] lines = csv.split("\n");
  for (String line: lines) {
    String[] parts = line.split(",");
    int price = Integer.parseInt(parts[1].trim());
    int qty = Integer.parseInt(parts[2].trim());
    total += price * qty;
  }
  
  return total;
}

String orders = """
    Hot Dogs , 1, 67
    Sandwiches, 2, 321
    Fried Rice, 4, 542
    """;
System.out.println(calculateTotal(orders));