Practice Problems for Experience

Introduction

This page has a bunch of problem statements which describe programs that you can implement for the joy of practicing your craft. Remember that when you implement them, several things should happen; DON'T JUST JUMP INTO THE CODE RIGHT AWAY unless the problem is so trivial that you can do it in a line or two of code.

Problem Set

  1. Program 1A: Write a JavaScript program to count from one number to another by an increment other than one. In other words, count from 7 to 146 by threes. Assign each value to an array element. Make the starting, ending, and offset values user inputs from the "prompt" function, and the output can be done with simply "alert( arrayName );".
  2. Program 1B: Start with the version above but convert the script runner version into a function. Call the function from the script runner.
  3. Program 1C: Start with version two and save the code to a file called "counter.js". Connect the program to a web page. Start off with just one button on the page to run your function which will still have the prompts in it to get the values and produce the output in the alert box.
  4. Program 1D: Continue with the web page development, making the web page have the three entry fields, and the output go to an element on the web page. The output HTML element can be a paragraph (<p id='output'></p>) or a div tag (<div id='output'></div>) or some other type of element of your choosing like a header <h5 id='output'></h5> or some such.
  5. Program 2A: Write a JavaScript program that will prompt the user for a web link. The user should input an URL into the prompt box, and should be told to make sure to enter the "http://" part of the URL. Use the JavaScript built-in "confirm()" function to ask the user an "are you sure question". If the "OK" button is clicked, use the "document.location()" function to change to the requested page. If the "Cancel" button is clicked, do nothing.
  6. Program 2B: Start with the previous version but convert the script runner version into a function. Call the function from the script runner.
  7. Program 2C: Design a web page which displays a picture of your choice. Make the web page picture a clickable link to any other web page. You may find some help for this from http://www.javascriptkit.com/howto/show.shtml
  8. Program 2D: Combine programs 2B and 2C to make the clickable image call your JavaScript function. Make sure to include the "confirm()" so the user can cancel out if s/he doesn't want to leave the current page.
  9. Develop a JavaScript program that will determine the gross pay for each of three employees. The company pays "straight time" for the first 40 hours worked by each employee and pays "time-and-a-half" for all hours worked in excess of 40 hours. You are given a list of the employees of the company, the number of hours each employee worked last week and the hourly rate of each employee. Your program should input this information for each employee, determine the employee's gross pay and output XHTML text that displays the employee's gross pay. Use prompt dialogs to input the data.
  10. A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, (a*a) + (b*b) = (c*c). For example, (3*3) + (4*4) = 9 + 16 = 25 = (5*5), so the Pythagorean triple is 3, 4, 5. Another one is 5, 12, 13.
    There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product a*b*c.
  11. [the one we did in class] A simple substitution cypher uses the numbers 1 - 26 to represent the letters of the alphabet, A - Z. When a message is encoded, a specific value called an "offset" is added to each letter in the message, ignoring case. Values greater than 26 are "wrapped around"; for example, if the offset is 5, the letter X would be calculated by 24 + 5 = 29 - 26 = 3 and would then be replaced in the message by the letter C. Develop a function to take a string and an offset as input, which will return the encoded message string as its output. Develop a web page that has two boxes for input, one for the message and one for the offset, and a button which produces the encoded message at the bottom of the page when it is clicked.
    (The solution for this one is developed step-by-step here.)
  12. A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:

      012 021 102 120 201 210

    Write a program in a web page to produce all the lexicographic permutations of the letters A, B, C, D, and E. Write the output on a separate web page.
  13. Repeat the previous problem, but make the page take in a user-input list of characters of varying length. Characters can include letters, numbers, or any of the symbol characters on the keyboard. Make the input from the text box be a list that is separated by spaces (space-dilimited list). Write the output onto the web page. Then see if you can make your program handle a phrase of words or a sentence instead of a list of single characters.
  14. One cubic foot can be visualized as a box that is one foot high, one foot wide, and one foot deep. A cubic meter is similar, but with meters instead of feet as the measurement. One meter is 39.37 inches long. Write a program in a web page which will calculate the number of cubic feet in a user-input area. Use three input boxes, one each for height, width, and length, and a button to activate the calculation. Display the volume in both cubic feet and cubic meters.
  15. Write a web page JavaScript program to output the following:

    all the numbers from 1 to 100, with the exception that:
    for multiples of 3, print "FIZZ" instead of the number
    for multiples of 5, print "BUZZ" instead of the number
    for multiples of 3 AND 5, print "FIZZBUZZ" instead of the number
  16. Re-do the web page and JavaScript for FIZZBUZZ to produce the output in an HTML table, so that it fits onto the web page in such a way that the user doesn't need to scroll to see the results. For example, there could be ten columns of ten rows, or perhaps 5 columns of 20 rows. Including a header for the columns would be nice.....
  17. Here are seven from Dr. Toal's email of practice problems for his 2013 final exam:
    • Write a function called isSmallInteger() which returns true if its sole parameter is an integer between -128 and 127, inclusive, and false otherwise. Examples:
      • isSmallInteger("dog") => false
      • isSmallInteger(-129) => false
      • isSmallInteger(-128) => true
      • isSmallInteger(127) => true
      • isSmallInteger(128) => false
      • isSmallInteger(14.8) => false
      • isSmallInteger(14.0) => true

    • Write a function called sumOfCodepoints which takes a string and returns the sum of each of the codepoints in the string. Hint: The method you are looking for is charCodeAt. We covered code points in chapter 3 - review if you need to do so.

    • Write a function that produces powers of two starting at 1 and going up to some limit. Examples:
      1. powersOfTwo(70) => [1,2,4,8,16,32,64]
      2. powersOfTwo(4) => [1,2,4]
      3. powersOfTwo(-4) => []

    • What is alerted in the following script?
             var x = 1;
             var f = function (y) {alert(x + y);}
             f(2);
                           

      What would happen if the parameter y were renamed to x? Why?

    • Write a function that takes in a number representing an amount of money in U.S. cents and returns an array containing the smallest number of quarters, dimes, nickels, and pennies, respectively that make up this amount. You can the somewhat famous algorithm for "making change" that U.S. kids (used to?) learn in elementary school. Examples:
      1. change(30) ? => [1,0,1,0]
      2. change(97) => [3,2,0,2]
      3. change(0) => [0,0,0,0]

    • Write a function to return the number of zeros in a given array. Examples:
      1. numberOfZeros([1,2,3]) ? => 0
      2. numberOfZeros([0,9,-3,0]) => 2
      3. change(0) => [0,0,0,0]

    • The usual way to count the number of occurrences of a particular character in a string is to use a for-loop that iterates through the array and increments a counter variable everytime it sees the desired the character. A fancier, though slower solution, uses split, filter and length. Write a function that returns the number of occurrences of a given character in a string, using only a single return statement using these three functions. Hint: Call split("") to turn a string into an array of characters to which you can apply the filter.
  18. Implement a "character counter" web page interface which contains a text area (like the one in the script runner) into which the user can type text. In the footer area of the page, show a count of how many characters have been typed into the text area. As the user types each character, update the count to present a real-time total. Be sure to handle backspaces and deletions.
  19. Implement a web page and JavaScript set up which allows changing the colors on the page. Include a drop-down list or a set of radio buttons to select page background, element background, and text color. Also include buttons to select the color to be set, with a minimum of the seven rainbow colors, white, and black.
  20. Implement a web page form for input of user information, and a JavaScript program to validate the user input. The page should include first name, middle initial, last name, street number and name, city, state, zip code, and telephone number. The following conditions must apply:
    • first name and last name cannot be blank
    • street number and name must contain at least one numeric digit
    • city, state, and zip code cannot be blank
    • zip code may have either 5 digits or be "zip-plus-four" format
    • telephone number is optional, but if included must have proper 10-digit format
  21. Write a web page which takes a string in one text box and a number in a second text box, and outputs the string to the web page over and over for the number of times specified, each time on a separate line down the page. If the number is bigger than 11, show the itemized numbers in front of each entry. For example, if the string is "Hello, world!" and the number is seven, the program should output:
          Hello, world!
          Hello, world!
          Hello, world!
          Hello, world!
          Hello, world!
          Hello, world!
          Hello, world!
                     
  22. Write a web page which takes in a word or phrase and produces a listing to the web page which uses the standard NATO phonetic alphabet words for each letter. For example, entering the word "hello" will produce the listing:
          HOTEL
          ECHO
          LIMA
          LIMA
          OSCAR
                     
    ....and the phrase "blah blah" will produce:
          bravo
          lima
          alpha
          hotel
          bravo
          lima
          alpha
          hotel
                     
    There is no distinction required for upper or lower case letters, so you may treat them however you want. For a complete listing of the NATO alphabet, see the web page at: http://en.wikipedia.org/wiki/NATO_phonetic_alphabet
  23. Do the same thing as in the previous problem, but produce the listing in the Morse code rather than the NATO code. Use whatever characters you wish for the dots and the dashes, as long as the web page specifies what you are using so the user can tell one from the other. For example, you might want to use the period for the dot and the underscore for the dash, or the star for the dot and the tilde for the dash. For example, the international distress code of "SOS" would be:
          ***
          ~~~
          ***
                     
    A listing of the Morse code is on the same page as the wikipedia link above.
  24. Imagine a digital clock which uses lights instead of numbers. There are three rows of lights, with the top row indicating hours, the middle row indicating minutes, and the bottom row indicating seconds. The lights count in binary, with the right-most light in each row being the least-significant bit.
    Create a web page and JavaScript program which takes input from the user in the form of a time string of the format "HH:MM:SS" (for hours, minutes, and seconds, two numbers each) and translates each value into its binary digit representation which is then displayed on the page.
    For example, the input "12:34:56" would be displayed on the page as:
          Hours:   0 0 1 1 0 0
          Minutes: 1 0 0 0 1 0
          Seconds: 1 1 1 0 0 0
                     
    Don't forget error checking the input values. You can decide for yourself whether to accept military time formats (i.e., "13:24:35" is 24 minutes and 35 seconds past 1 PM).
  25. Repeat the previous problem, but instead of ones and zeros, make the page display graphics of lit and unlit lights of some kind. You can use any graphic you'd like: bulbs, LEDs, happy faces, fruit, cars, dogs and cats, or anything else that strikes your fancy.
  26. The decimal number 585 = 1001001001 (binary), is palindromic in both number systems (bases). Other examples are 33 = 100001 and 99 = 1100011. Remember that single-digit numbers are considered palindromic; i.e., 5 = 101 is in this set of numbers.
    Find all numbers, less than ten thousand, which are palindromic in both decimal (base 10) and binary (base 2), then find their sum. Output the numbers and the sum on a web page. Note that the palindromic number, in either base, may NOT include leading zeros.
    You can write a helper function which returns true if its input is a palindrome, and there are several other possibilities for helper functions as well...
  27. Let "D0" (read as "Dee-zero") be the two-letter string "Fa". Then for each successive string value of "D" we perform a substitution as follows:
          "a" -> "aRbFR"
          "b" -> "LFaLb"
                     
    Thus for D0 = "Fa", we get D1 = "FaRbFR" and D2 = "FaRbFRRLFaLbFR". This process is known as grammar production in some circles.
    Write a JavaScript function to produce the resulting string for D10 and write it to the output area of a web page. Also output the total count of L added to the total count of R in the string produced. For example, D3 would be the string shown with the count of R as follows:
          D3 -> "FaRbFRRLFaLbFRRLFaRbFRLLFaLbFR"
          "R" count = 7
                     
  28. We all know the numbers 2, 3, 5, 7, 11, 13, .... are prime numbers, and there are many more. The science of figuring out very large prime numbers is a very important part of many encryption algorithms used in commerce on the Internet.
    Write a program that runs in a web page to take a user-input number and list the first prime numbers up to that count, as well as their sum. For example, if the user enters the number "8", the program will produce the output:
          2, 3, 5, 7, 11, 13, 17, 19  .....which has the sum 77
                     
    What is the output for the 15th prime number? The 23rd? What is the sum of the first 37 primes? You may wish to write a "helper" function to determine if a number is prime (if you haven't already done so!).
  29. From "Python for Everyone" by Cay Horstmann and Rance D Necaise, ISBN 978-1-118-62613-9
    Business P2.36: [note: also a homework problem for CMSI 185] An online bank wants you to create a program that shows prospective customers how their deposits will grow. Your program should read the initial balance and the annual interest rate. Interest is compounded monthly. Write a program in Python to print out the balances after the first three months. Here is a sample run:
          Initial balance: 1000
          Annual interest rate in percent: 6.0
          After first month: 1005.00
          After second month: 1010-03
          After third month: 1015.08
                     
  30. Re-write the Python program above in Javascript, making a web page that takes input from text boxes on the page, and outputs the results to an "output area" at the bottom of the web page. You'll also need a button to perform the conversion. An alternative is to look up how to get the page to trigger the function when the "Enter" key is pressed while the cursor is in one [or any] of the text boxes. The output on the bottom of the web page should look like the example. Try to make the number of months be a variable using a text entry box as well.
  31. From "Python for Everyone" by Cay Horstmann and Rance D Necaise, ISBN 978-1-118-62613-9
    Business P2.37: [note: also a homework problem for CMSI 185] A video club wants to reward its best members with a discount based on the member's number of movie rentals and the number of new members referred by that member. The discount is in percent and is equal to the sum of the rentals and the referrals, but it cannot exceed 75 percent. Write a Python program to calculate the value of the discount. Here is a sample run:
          Enter the number of movie rentals: 56
          Enter the number of members referred: 3
          The discount is equal to: 59.00 percent
                     
  32. From "Python for Everyone" by Cay Horstmann and Rance D Necaise, ISBN 978-1-118-62613-9
    Science P2.87: Consider the following circuit [see diagram below]. Write a program that reads the resistances of the three resistors in the circuit and computes the total resistance for the circuit. Look up the formula for two parallel resistances; once that value is calculated, the series resistor is just added to that value.



  33. From "Python for Everyone" by Cay Horstmann and Rance D Necaise, ISBN 978-1-118-62613-9
    Science P2.39: [note: also a homework problem for CMSI 185] The "dew point" temperature Td can be calculated (approximately) from teh relative humidity RH and the actual temperature T by the formula:

       Td = (b * f(T, RH)) / (a - f(T, RH))   where:
    
       f(T, RH) = ((a * T) / (b + T)) + ln( RH )
       a = 17.27
       b = 237.7 degrees C
             

    Write a program that reads the relative humidity (a value between 0 and 1) and the temperature in degrees Celcius, and prints the dew point value. Use the Python function "log()" to compute the natural logarithm (the "ln" in the equation). Check your calculation with a few of the values located at this page.

  34. From "Python for Everyone" by Cay Horstmann and Rance D Necaise, ISBN 978-1-118-62613-9
    Science P2.43: [note: also a homework problem for CMSI 185] According to the Coulomb force law, the electric force between two charged particles of charge Q1 and Q2 Coulombs, that are a distance r meters apart, is given by the formula
    F = (Q1Q2) / 4 * Π * e * r². Write a program in Python that calculates and displays the force on a pair of charged particles, based on the user input of Q1 and Q2 Coulombs, and r meters.
  35. From "Python for Everyone" by Cay Horstmann and Rance D Necaise, ISBN 978-1-118-62613-9
    Text Example 3.2, page 131: Two circles may intersect at a single point, at two points, or at an unlimited number of pionts when the two circles are coincident. If the circles do NOT intersect, one circle may be inside the other, or they may be entirely separate. Your task is to write a Python program that obtains the parameters for two circles and reports whether they intersect. For each circle, the inputs should be the X and Y coordinates (on a Cartesian grid) of the center point, and the radius of the circle. The output should be one and only one of the possible configurations listed above, as well as the distance between the two center points.
  36. From "Python for Everyone" by Cay Horstmann and Rance D Necaise, ISBN 978-1-118-62613-9
    Text Example 3.2, page 131: Calculating the tip when you go to a restaurant is not difficult, but YOUR restaurant wants to suggest a tip according to the service diners receive. Write a program that calculates a tip according to the diner's satisfaction as follows:
    • Ask for the total of the check
    • Ask for the diner's satisfaction level using values 1 [totally satisfied] to 3 [totally dissatisfied]
    • If the diner is totally satisfied [value 1], calculate a 20 percent tip
    • If the diner is satisfied [value 2], calculate a 15 percent tip
    • If the diner is dissatisfied [value 3], calculate a 10 percent tip
    • Report the satisfaction level in words, and the tip in dollars and cents
  37. (There will be more problems added here over time.)
  38. (There will be more problems added here over time.)
  39. (There will be more problems added here over time.)
  40. (There will be more problems added here over time.)