LMU ☀️ CMSI 185
COMPUTER PROGRAMMING
Practice

Reinforcement Questions

Do you like spaced repetition learning? Have you used Anki or Quizlet? Whether or not spaced repetition works for you, periodically working on flash-card like questions can be a lot of fun, and just may help you retain information. Here are a few problems tied to the course material. Visit them periodically, and feel free to use them in your own spaced repetition learning practice!

  1. JavaScript is a ________________ and p5.js is a ________________.
    Programming Language / Library.
  2. How do you import p5.js into your program?
    You place a “script element” into the HTML file that references the library.
  3. The element of a web browser in which you can draw shapes is called a ________________.
    Canvas.
  4. What is the difference between setup and draw?
    setup is called once, and then draw is (normally) called over and over again.
  5. What does the background function do?
    It fills the canvas with a single color.
  6. What is the first thing you normally do in setup?
    Call createCanvas. Many P5 variables are not available, and many functions won’t work at all, until createCanvas is called.
  7. How do you draw a line from the upper-left corner of the canvas to the lower-right?
    line(0, 0, width, height)
  8. How do you draw a line from the upper-right corner of the canvas to the lower-left?
    line(width, 0, 0, height)
  9. How do you draw a rectangle, filled with green and outlined in red, that is inset 20 pixels from the edges of the canvas?
    stroke('red'); fill('green'); rect(20, 20, width-40, height-40)
  10. What phrase do you Google to get documentation on P5?
    “P5 reference”
  11. What P5 function do you use to vary the thickness of lines and the outlines of 2-D shapes?
    strokeWeight
  12. How do you turn off outlining shapes in p5.js?
    noStroke().
  13. What is the difference between const and let in JavaScript?
    Variables bound with let can be re-bound to different values; those bound with const cannot.
  14. Why is it a good idea to bind a few variables, using meaningful names, at the top of your code?
    Doing so makes the code easier to “configure” (allowing for more creativity and easier debugging).
  15. What is the difference between a local and global variable in JavaScript?
    A local variable can only been seen inside the function in which it is declared; a global variable is accessible everywhere from the point of its definition onward.
  16. How do you animate in p5.js?
    Bind a global variable to a value used to position, size, or style a shape, then rebind the variable to a new value inside draw.
  17. p5.js was created by ________________.
    Lauren McCarthy.
  18. What is the difference between mouseIsPressed and mousePressed?
    The former is a boolean variable that says whether the mouse is current pressed; the latter is a function that is called whenever the mouse goes from not being pressed to being pressed.
  19. Explain the behavior of the following sketch (a) with the call to background commented out, and (b) uncommented.
      function draw() {
        // background('white')
        line(pmouseX, pmouseY, mouseX, mouseY)
      }
    
    If commented out, it “sketches”. When uncommented, you get a tailing effect as the mouse moves.
  20. The additive primary colors are ________________.
    Red, Green, and Blue.
  21. In the HSB color system, what does varying S from its maximum value down to zero do?
    Washes out the color, going from a vibrant, saturated color down to a grey-scale value.
  22. In the HSB color system, what does varying V from its maximum value down to zero do?
    It gets less and less bright, until it is black at V=0.
  23. Is a color fully transparent when its alpha value is zero or at its maxium?
    At zero. Fully transparenet at 0; fully opaque at 1.
  24. JavaScirpt objects are made of ________________.
    Properties.
  25. How do you add $x$ to the end of array $a$ in JavaScript?
    a.push(x)
  26. What JavaScript statement will reset the value of the $y$ property of object ball to the top of the canvas if the ball has gone below the bottom edge of the canvas?
    if (ball.y > height) { ball.y = 0 }
Stay Tuned

Many more to follow.

Short Answer and Matching Questions

  1. Match the terms with their definitions, by writing the number of the definition next to the term.
    1. Expression _______
    2. Variable _______
    3. Statement _______
    4. || _______
    5. Function _______
    6. Loop _______
    7. Exception _______
    8. Argument _______
    9. % _______
    10. Applet _______
    11. Enum _______
    12. Codepoint _______
    13. Boolean _______
    14. Context _______
    15. Computing _______
    1. An object that you throw to signal that something is wrong
    2. The primitive type containing only the values true and false.
    3. The science of information processes
    4. A named storage location
    5. The “or-else” operator
    6. A user-defined type containing a fixed number of elements
    7. A JavaScript object used for drawing in a canvas
    8. The mathematical remainder operator
    9. A parameterized chunk of code that can be run
    10. A program designed to run inside of another (often a web browser)
    11. A chunk of code that is evaluated
    12. Code that produces an action
    13. Code that is executed repeatedly
    14. A value passed to a function
    15. The position of a character within a character set
  2. Show the fully-parenthesized form of each of the following expressions:
    1. 1 - 2 - (3 - 4 - 5) - 6
    2. ! x && y && z
    3. a < b > c == d > e
    4. typeof + 3
  3. Is first-guess a legal variable name in JavaScript? If not, why do you think such a name was banned? (Answer using complete sentences. Back up your answer. Concrete examples will most likely be helpful.)
  4. Write an expression that is true if and only if the value stored in variable $x$ is between 0 and 10 (inclusive).
  5. Evaluate the expression 'dog'.charAt(2).charAt(0) and explain the result.
  6. Draw a picture of the objects resulting from the following declaration:
    let p1 = {name: 'Alice'};
    let p2 = {name: 'Bob', manager: p1};
    p1.manager = p1;
    
    What is the value of p2.manager.manager.manager.name?
  7. Here is an attempt to write a script that computes the sum of the numbers from 1 to 10000, inclusive. However, there are three major problems. Identify the mistakes and explain how to correct them. (Note: find actual programming mistakes, not mistakes of style; do not pick on the names, the indentation, the formatting, or the lack of comments.)
    let sum;
    for (int i = 1; i < 10000; i++) {
      sum += i;
      console.log(`The sum from 1 to 10000 is ${sum}`);
    }
    
  8. Draw a picture of the array referred to by the variable a after executing the following:
    let a = [1,2,3,4]; a.unshift(a.pop());
    
  9. What is printed in the following script?
        let x = 1;
        let f = (y) => { console.log(x + y); }
        f(2);
    
    What would happen if the parameter $y$ were renamed to $x$?
  10. Suppose you were asked to write a function to take in an array and swap the first and second elements of the array (that’s right: actually change the array that was passed in!). You could write:
    function swapFirstTwoElementsOf(a) {
      let oldFirstElement = a[0];
      a[0] = a[1];
      a[1] = oldFirstElement;
    }
    
    This works. Then your friend comes along and says “oh hang on, I can do better” and writes this:
    function swapFirstTwoElementsOf(a) {
      a = [a[1],a[0]].concat(a.slice(2, a.length));
    }
    
    Does your friend’s function work? Why or why not? Be very specific. Use precise, technical language.

Programming Problems

  1. Write HTML and JavaScript to gets the mass of an object in kilograms from a text box and writes (as the user types) a nice message stating its energy content in petajoules. Use the formula $E=mc^2$, where $E$ is the energy content (in joules), $m$ is the mass (in kilograms), and $c$ is 299,792,458 m/s. By the way, a petajoule is one quadrillion ($10^{15}$) joules.
  2. Consider the following BMI script. Can we turn this into a one-liner by replacing the uses of the variables kilos and meters in the last line with their definitions from the first two lines? Why or why not?
    const kilos = prompt('Enter your weight in pounds') * 0.45359237;
    const meters = prompt('Enter your height in inches') * 0.0254;
    alert(`Your body mass index is ${kilos / (meters * meters)}`);
    
  3. Here is a script that determines how long it takes to grow 1000 dollars into 5000 dollars assuming an APR (annual percentage rate) of 5%, compounded yearly:
    let total = 1000;
    let year = 0;
    while (total < 5000) {
      year = year + 1;
      total = total * 1.05;
    }
    console.log(`It will take you ${year} years to get there.`);
    

    Modify the script so that it first prompts for the APR and then computes the amount of time required to grow 1000 dollars to 5000 dollars where the rate is compounded monthly. You may print the result in either months or years.

  4. Write a script that echos, as you type into a text box, whether or not the entered string contains either a backslash character or a Telugu letter ddha (U+0C22).
  5. Write a script that prompts for the abbreviation of a New England state and prints the capital of that state. The first line is:
    const capitals = {
      ME: 'Augusta', NH: 'Concord', VT: 'Montpelier',
      MA: 'Boston', CT: 'Hartford', RI: 'Providence'
    };
    
    So if your user inputs NH, your script should print Concord. If you want a point of extra credit, allow the user to enter data in any case, for example NH, Nh, nH, or nh for New Hampshire.
  6. Write a JavaScript function called dollarMessage that has one parameter representing a number of dollars and returns a string stating how many dollars this is. Here are some test cases:
        dollarMessage(5)     ⟶ "5 dollars"
        dollarMessage(1)     ⟶ "1 dollar"
        dollarMessage(7.244) ⟶ "7.244 dollars"
    
    Use a conditional expression, not an if-statement, to distinguish between writing dollar versus dollars.
  7. Write a function called sign that takes one parameter, a number, and returns -1 if the number is negative, 0 if the number is 0, 1 if the number is positive, and NaN if the parameter is not a number. Use an if-statement.
  8. Write a function called isSmallInteger which returns true if its sole parameter is an integer between -128 and 127, inclusive, and false otherwise. Your function body should have a single return statement in which you test that your parameter is not NaN, is an integer, is greater than or equal to -128, and is less than or equal to 127.
        isSmallInteger('dog') ⟶ false
        isSmallInteger(-129)  ⟶ false
        isSmallInteger(-128)  ⟶ true
        isSmallInteger(127)   ⟶ true
        isSmallInteger(128)   ⟶ false
        isSmallInteger(14.8)  ⟶ false
        isSmallInteger(14.0)  ⟶ true
    
  9. Write a function called isShortInteger which returns true if its sole parameter is an integer between -32768 and 32767, inclusive, and false otherwise. Your function body should have a single return statement in which you test that your parameter is not NaN, is an integer, is greater than or equal to -32768, and is less than or equal to 32767.
  10. Write a function called sumOfRange that takes in two parameters, $x$ and $y$, which should both be small integers (see the previous problem), and returns the sum of all of the integers in the range from $x$ (inclusive) to $y$ (exclusive). If either of $x$ or $y$ is not a small integer (call the function from the previous problem to check this!!!) then throw an exception. Example test cases for you:
        sumOfRange(5, 9)      ⟶ 5 + 6 + 7 + 8 = 26
        sumOfRange(-2, 4)     ⟶ -2 + -1 + 0 + 1 + 2 + 3 = 3
        sumOfRange(9, 5)      ⟶ 0 (because there are no numbers >=9 AND <5)
        sumOfRange(-99999, 0) ⟶ throws an exception
        sumOfRange(14, 'dog') ⟶ throws an exception
    
  11. Write a function called sumOfCodepoints which takes a string and returns the sum of each of the codepoints in the string.
  12. Write a function with no parameters that returns a two-element array containing two (possibly different) dice rolls.
  13. Write a function that returns a two-element array containing two possibly different) dice rolls for an $n$-sided die. You should read the phrase “$n$-sided” die as implying that $n$ should be a parameter of your function.
  14. Write a function called squares that takes in an array and returns a new array containing all the squares of the input array. Test cases:
        squares([1,7,-4])         ⟶ [1,49,16]
        squares([])               ⟶ []
        squares([true, -6, null]) ⟶ [1, 36, 0]
    
  15. Write a function called square that takes in an array of numbers and changes this array by replacing each element with its square. Test cases:
        let a = [1,7,-4];
        square(a);
        a                  ⟶ [1,49,16]
    
  16. Write a function that takes in one parameter and returns how many times you have to cut it in half to produce a value less than or equal to 1. Note that if the number is already 1 or less, you should immediately return 0. Use a while statement or a do-while statement. Some test cases for you:
        halfsies(1)         ⟶ 0
        halfsies(0)         ⟶ 0
        halfsies(-22.7)     ⟶ 0
        halfsies(2)         ⟶ 1
        halfsies(19)        ⟶ 5
        halfsies(7.225E102) ⟶ 342
    
  17. Write a function that produces the Fuddified version of the string. The Fuddified version of a string is the string with all r’s and l’s replaced with w’s.
  18. Write a function that accepts a non-negative integer between 1 and 10000 inclusive and returns the length of the Collatz sequence starting at that value. Throw an exception if the argument isn’t desirable.
        lengthOfCollatzSequence(1)  ⟶ 1
        lengthOfCollatzSequence(3)  ⟶ 8
        lengthOfCollatzSequence(4)  ⟶ 3
        lengthOfCollatzSequence(16) ⟶ 5
    
  19. Write a function to determine whether a given year is a leap year or not. Throw an exception if the year is earlier than 1582. Note: A year is a leap year if it is divisible by 4, but not 100, unless also by 400.
        isLeapYear(2000) ⟶ true
        isLeapYear(1940) ⟶ true
        isLeapYear(2100) ⟶ false
        isLeapYear(1987) ⟶ false
        isLeapYear(1381) ⟶ (throws an exception)
    
  20. Write a function that takes in a string $s$ and returns the string which is equivalent to $s$ but with all ASCII vowels removed. (ASCII characters are those Unicode characters whose codepoints are in the range 0..127 inclusive.)
        stripAsciiVowels('Hello, world') ⟶ 'Hll, wrld'
    
  21. Write a function that randomly permutes a string. By random we mean that each time you call the method for a given argument all possible permutations are equally likely (note that “random” is not the same as “arbitrary”.) For example:
        scramble('Hello, world') ⟶ 'w,dlroH elol'
    
  22. Write a function that produces powers of two starting at 1 and going up to some limit.
        powersOfTwo(70) ⟶ [1,2,4,8,16,32,64]
    
  23. Write a function that doubles up each item in an array. Here are test cases your function should satisfy:
        stutter([5,true,[3],'ha']) ⟶ [5,5,true,true,[3],[3],'ha','ha']
        stutter([{}, null])        ⟶ [{}, {}, null, null]
    
  24. Write a function that takes in a point object, that is, an object with an $x$ property and a $y$ property, and returns the quadrant of the point. In case you didn’t know, Quadrant 1 contains points with non-negative $x$ and non-negative $y$; quadrant 2 has points with negative $x$ and non-negative $y$; in quadrant three both $x$ and $y$ are negative; quadrant 4 has non-negative $x$ and negative $y$.
  25. Write a script that produces an array with successive prefixes of argument, starting with the first prefix, which is zero characters long. For example:
        prefixes('eich') ⟶ ['', 'e', 'ei', 'eic', 'eich']
        prefixes('')     ⟶ ['']
    
  26. Write a function that produces an array of powers of an arbitrary base starting at exponent 0 and going up to some limit. Throw an exception if the base is less than or equal to 1.
        powers(3, 400)  ⟶ [1,3,9,27,81,243]
        powers(-2, 17)  ⟶ throws an exception
        powers(3, -9)   ⟶ []
        powers(0.5, 22) ⟶ throws an exception
    
  27. Write a function that interleaves two arrays. If the arrays do not have the same length, the elements of the longer array should end up at the end of the result array.
        interleave(['a', 'b'], [1, 2, true, nil]) ⟶ ['a', 1, 'b', 2, true, nil]
        interleave(['a', 'b'], [])                ⟶ ['a', 'b']
    
  28. Write a function that takes in an array of arrays and returns whether or not the argument is a square matrix. A square matrix is an array with n elements, each of which is an $n$-element array.
  29. Suppose we have a bunch of objects representing people. Each object has three properties (at least): name, mother, and father. The value of the name property is a string, and the values of the mother and father properties are either other people objects, or are null. Write a function that takes in a person object and returns the array of all of the person’s (known) grandparents. Hint: the resulting array will have either 0, 1, 2, 3, or 4 values.
  30. Write a function that takes in two people objects (defined in the previous problem) and returns whether or not they are (known for sure to be) first cousins.
  31. Write a function that takes in a string and produces an object as follows. The string is made up of a number of “pairs” separated by | characters. Each pair has its two components separated internally with commas. You need to create a real JavaScript object from the string by treating each pair as a property name together with its value. If that was hard to understand, just "figure it out" from the following examples:
        objectify('a,dog|b,cat|z,rat') ⟶ {a: 'dog', b: 'cat', z: 'rat'}
        objectify('')                  ⟶ {}
        objectify('one,uno|two,dos')   ⟶ {one: 'uno', two: 'dos'}
    
  32. Write a script (using Canvas) that draws 20 randomly placed squares, each 30 pixels wide. Make sure each square fits completely in the canvas. The squares can be any color you choose, with any degree of transparency you choose.
  33. Write a function called take which takes an array $a$ and a number $n$ and returns a new array consisting of the first $n$ elements of $a$. If $n$ is greater than the length of $a$, return a copy of $a$.
  34. Write a function called drop which takes an array $a$ and a number $n$ and returns a new array consisting of all but the first $n$ elements of $a$. If $n$ is greater than the length of $a$, return an empty array.
  35. Write a function that removes "every nth character" of string. That is, given a string $s$ and a positive integer $n$ return the string like $s$ but with characters at positions 0, n, 2n, 3n, and so on, removed. Throw an exception if $n$ is not a positive integer.
    sift("javascript", 2) ⇒ "aacit"
    sift("python", -4) ⇒ throws an exception
    sift("coffeescript", 5) ⇒ "offescrit"
    sift("java", isNaN) ⇒ throws an exception