Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
The way statements are sequenced and combined in a program determines the computed result. Programs incorporate iteration and selection constructs to represent repetition and make decisions to handle varied input values.
Evaluate expressions that manipulate strings.
String concatenation joins together two or more strings end-to-end to make a new string.
A substring is part of an existing string.
Programs can be used to process data, which allows users to discover information and create new knowledge.
Extract information from data using a program.
Programs can be used to process data to acquire information.
Tables, diagrams, text, and other visual tools can be used to communicate insight and knowledge gained from data.
Search tools are useful for efficiently finding information.
Data filtering systems are important tools for finding information and recognizing patterns in data.
Programs such as spreadsheets help efficiently organize and find trends in information.
Some processes that can be used to extract or modify information from data include the following:
transforming every element of a data set, such as doubling every element in a list, or adding a parent’s email to every student record
filtering a data set, such as keeping only the positive numbers from a list, or keeping only students who signed up for band from a record of all the students
combining or comparing data in some way, such as adding up a list of numbers, or finding the student who has the highest GPA
Explain how programs can be used to gain insight and knowledge from data.
Programs are used in an iterative and interactive way when processing information to allow users to gain insight and knowledge about data.
Programmers can use programs to filter and clean digital data, thereby gaining insight and knowledge.
Combining data sources, clustering data, and classifying data are parts of the process of using programs to gain insight and knowledge from data.
Insight and knowledge can be obtained from translating and transforming digitally represented information.
Patterns can emerge when data are transformed using programs.
Based on the Understanding by Design® (Wiggins and McTighe) model, the AP Computer Science Principles Course and Exam Description provides a clear and detailed description of the course requirements necessary for student success. The course is designed to be equivalent to a first-semester introductory college computing course. The major areas of study in the course are organized around big ideas that encompass ideas foundational to studying computer science.
The AP Computer Science Principles course framework is organized into five big ideas.
Big Idea
Exam Weighting
Big Idea 1: Creative Development
10%–13%
Big Idea 2: Data
17%–22%
The AP Computer Science Principles course framework included in the course and exam description outlines distinct skills from computational thinking practices that students should practice and develop throughout the year—skills that will help them learn to think and act like computer scientists. Emphasis is placed on creativity and collaboration as pedagogical strategies to be used to develop a diverse, appealing, and inclusive classroom environment.
This website is written by Mr. Cheng, a high school computer science teacher and adjunct professor. He can be reached at mcheng @ appinventor.net He is available for consulting and tutoring.
Programmers break down problems into smaller and more manageable pieces. By creating procedures and leveraging parameters, programmers generalize processes that can be reused. Procedures allow programmers to draw upon existing code that has already been tested, allowing them to write programs more quickly and with more confidence.
For errors in an algorithm or program:
a. Identify the error.
b. Correct the error.
A logic error is a mistake in the algorithm or program that causes it to behave incorrectly or unexpectedly.
A syntax error is a mistake in the program where the rules of the programming language are not followed.
A run-time error is a mistake in the program that occurs during the execution of a program. Programming languages define their own run time errors.
An overflow error is an error that occurs when a computer attempts to handle a number that is outside of the defined range of values.
The following are effective ways to find and correct errors:
test cases
hand tracing
visualizations
debuggers
adding extra output statement(s)
Identify inputs and corresponding expected outputs or behaviors that can be used to check the correctness of an algorithm or program.
In the development process, testing uses defined inputs to ensure that an algorithm or program is producing the expected outcomes. Programmers use the results from testing to revise their algorithms or programs.
Defined inputs used to test a program should demonstrate the different expected outcomes that are at or just beyond the extremes (minimum and maximum) of input data.
Program requirements are needed to identify appropriate defined inputs for testing.
For simulations:
a. Explain how computers can be used to represent real-world phenomena or outcomes.
b. Compare simulations with real-world contexts.
Simulations are abstractions of more complex objects or phenomena for a specific purpose.
A simulation is a representation that uses varying sets of values to reflect the changing state of a phenomenon.
Simulations often mimic real-world events with the purpose of drawing inferences, allowing investigation of a phenomenon without the constraints of the real world.
The process of developing an abstract simulation involves removing specific details or simplifying functionality.
Simulations can contain bias derived from the choices of real-world elements that were included or excluded.
Simulations are most useful when real-world events are impractical for experiments (e.g., too big, too small, too fast, too slow, too expensive, or too dangerous).
Simulations facilitate the formulation and refinement of hypotheses related to the objects or phenomena under consideration.
Random number generators can be used to simulate the variability that exists in the real world.
For nested selection:
a. Write nested conditional statements.
b. Determine the result of nested conditional statements.
Nested conditional statements consist of conditional statements within conditional statements.
Computing innovations can reflect existing human biases because of biases written into the algorithms or biases in the data used by the innovation.
Programmers should take action to reduce bias in algorithms used for computing innovations as a way of combating existing human biases.
Biases can be embedded at all levels of software development.
Developers create and innovate using an iterative design process that is userfocused, that incorporates implementation/feedback cycles, and that leaves ample room for experimentation and risk-taking.
Describe the purpose of a computing innovation.
The purpose of computing innovations is to solve problems or to pursue interests through creative expression.
An understanding of the purpose of a computing innovation provides developers with an improved ability to develop that computing innovation.
Explain how a program or code segment functions.
A program is a collection of program statements that performs a specific task when run by a computer. A program is often referred to as software.
A code segment is a collection of program statements that is part of a program.
A program needs to work for a variety of inputs and situations.
The behavior of a program is how a program functions during execution and is often described by how a user interacts with it.
A program can be described broadly by what it does, or in more detail by both what the program does and how the program statements accomplish this function.
Identify input(s) to a program.
Program inputs are data sent to a computer for processing by a program. Input can come in a variety of forms, such as tactile, audio, visual, or text.
An event is associated with an action and supplies input data to a program.
Events can be generated when a key is pressed, a mouse is clicked, a program is started, or any other defined action occurs that affects the flow of execution.
Inputs usually affect the output produced by a program.
In event-driven programming, program statements are executed when triggered rather than through the sequential flow of control.
Input can come from a user or other programs
Identify output(s) produced by a program.
Program outputs are any data sent from a program to a device. Program output can come in a variety of forms, such as tactile, audio, visual, or text.
Program output is usually based on a program’s input or prior state (e.g., internal values).
Programs can be used to process data, which allows users to discover information and create new knowledge.
Describe what information can be extracted from data.
Information is the collection of facts and patterns extracted from data.
Data provide opportunities for identifying trends, making connections, and addressing problems.
Digitally processed data may show correlation between variables. A correlation found in data does not necessarily indicate that a causal relationship exists. Additional research is needed to understand the exact nature of the relationship.
Often, a single source does not contain the data needed to draw a conclusion. It may be necessary to combine data from a variety of sources to formulate a conclusion.
Describe what information can be extracted from metadata.
Metadata are data about data. For example, the piece of data may be an image, while the metadata may include the date of creation or the file size of the image.
Changes and deletions made to metadata do not change the primary data.
Metadata are used for finding, organizing, and managing information.
Metadata can increase the effective use of data or data sets by providing additional information.
Metadata allow data to be structured and organized.
Identify the challenges associated with processing data.
The ability to process data depends on the capabilities of the users and their tools.
Data sets pose challenges regardless of size, such as:
the need to clean data
incomplete data
invalid data
the need to combine data source
Depending on how data were collected, they may not be uniform. For example, if users enter data into an open field, the way they choose to abbreviate, spell, or capitalize something may vary from user to user.
Cleaning data is a process that makes the data uniform without changing their meaning (e.g., replacing all equivalent abbreviations, spellings, and capitalizations with the same word).
Problems of bias are often created by the type or source of data being collected. Bias is not eliminated by simply collecting more data.
The size of a data set affects the amount of information that can be extracted from it.
Large data sets are difficult to process using a single computer and may require parallel systems.
Scalability of systems is an important consideration when working with data sets, as the computational capacity of a system affects how data sets can be processed and stored.
The way a computer represents data internally is different from the way the data are interpreted and displayed for the user. Programs are used to translate data into a representation more easily understood by people.
Compare data compression algorithms to determine which is best in a particular context.
Data compression can reduce the size (number of bits) of transmitted or stored data.
Fewer bits does not necessarily mean less information.
The amount of size reduction from compression depends on both the amount of redundancy in the original data representation and the compression algorithm applied.
Lossless data compression algorithms can usually reduce the number of bits stored or transmitted while guaranteeing complete reconstruction of the original data.
Lossy data compression algorithms can significantly reduce the number of bits stored or transmitted but only allow reconstruction of an approximation of the original data.
Lossy data compression algorithms can usually reduce the number of bits stored or transmitted more than lossless compression algorithms.
In situations where quality or ability to reconstruct the original is maximally important, lossless compression algorithms are typically chosen.
In situations where minimizing data size or transmission time is maximally important, lossy compression algorithms are typically chosen.
Programmers break down problems into smaller and more manageable pieces. By creating procedures and leveraging parameters, programmers generalize processes that can be reused. Procedures allow programmers to draw upon existing code that has already been tested, allowing them to write programs more quickly and with more confidence.
For generating random values:
a. Write expressions to generate possible values.
b. Evaluate expressions to determine the possible results.
The exam reference sheet provides
Text: RANDOM(a, b)
Block:
which generates and returns a random integer from a to b, inclusive. Each result is equally likely to occur. For example, RANDOM(1, 3) could return 1, 2, or 3.
Using random number generation in a program means each execution may produce a different result.
The way statements are sequenced and combined in a program determines the computed result. Programs incorporate iteration and selection constructs to represent repetition and make decisions to handle varied input values.
Compare multiple algorithms to determine if they yield the same side effect or result.
Algorithms can be written in different ways and still accomplish the same tasks.
Algorithms that appear similar can yield different side effects or results.
Some conditional statements can be written as equivalent Boolean expressions.
Some Boolean expressions can be written as equivalent conditional statements.
Different algorithms can be developed or used to solve the same problem.
For algorithms:
a. Create algorithms.
b. Combine and modify existing algorithms.
Algorithms can be created from an idea, by combining existing algorithms, or by modifying existing algorithms.
Knowledge of existing algorithms can help in constructing new ones. Some existing algorithms include:
determining the maximum or minimum value of two or more numbers
computing the sum or average of two or more numbers
identifying if an integer is or is not evenly divisible by another integer
determining a robot’s path through a maze
Using existing correct algorithms as building blocks for constructing another algorithm has benefits such as reducing development time, reducing testing, and simplifying the identification of errors.
Programmers break down problems into smaller and more manageable pieces. By creating procedures and leveraging parameters, programmers generalize processes that can be reused. Procedures allow programmers to draw upon existing code that has already been tested, allowing them to write programs more quickly and with more confidence.
Select appropriate libraries or existing code segments to use in creating new programs.
A software library contains procedures that may be used in creating new programs.
Existing code segments can come from internal or external sources, such as libraries or previously written code.
The use of libraries simplifies the task of creating complex programs.
Application program interfaces (APIs) are specifications for how the procedures in a library behave and can be used.
Documentation for an API/library is necessary in understanding the behaviors provided by the API/library and how to use them.
While computing innovations are typically designed to achieve a specific purpose, they may have unintended consequences.
Explain how the use of computing can raise legal and ethical concerns.
Material created on a computer is the intellectual property of the creator or an organization.
Ease of access and distribution of digitized information raises intellectual property concerns regarding ownership, value, and use.
Measures should be taken to safeguard intellectual property.
The use of material created by someone else without permission and presented as one’s own is plagiarism and may have legal consequences.
Some examples of legal ways to use materials created by someone else include:
Creative Commons—a public copyright license that enables the free distribution of an otherwise copyrighted work. This is used when the content creator wants to give others the right to share, use, and build upon the work they have created.
open source—programs that are made freely available and may be redistributed and modified
open access—online research output free of any and all restrictions on access and free of many restrictions on use, such as copyright or license restrictions
The use of material created by someone other than you should always be cited.
Creative Commons, open source, and open access have enabled broad access to digital information.
As with any technology or medium, using computing to harm individuals or groups of people raises legal and ethical concerns.
Computing can play a role in social and political issues, which in turn often raises legal and ethical concerns.
The digital divide raises ethical concerns around computing.
Computing innovations can raise legal and ethical concerns. Some examples of these include:
the development of software that allows access to digital media downloads and streaming
the development of algorithms that include bias
§ the existence of computing devices that collect and analyze data by continuously monitoring activities
There exist problems that computers cannot solve, and even when a computer can solve a problem, it may not be able to do so in a reasonable amount of time.
For determining the efficiency of an algorithm:
a. Explain the difference between algorithms that run in reasonable time and those that do not.
b. Identify situations where a heuristic solution may be more appropriate.
A problem is a general description of a task that can (or cannot) be solved algorithmically. An instance of a problem also includes specific input. For example, sorting is a problem; sorting the list (2,3,1,7) is an instance of the problem.
A decision problem is a problem with a yes/no answer (e.g., is there a path from A to B?). An optimization problem is a problem with the goal of finding the “best” solution among many (e.g., what is the shortest path from A to B?).
Efficiency is an estimation of the amount of computational resources used by an algorithm. Efficiency is typically expressed as a function of the size of the input.
An algorithm’s efficiency is determined through formal or mathematical reasoning.
An algorithm’s efficiency can be informally measured by determining the number of times a statement or group of statements executes.
Different correct algorithms for the same problem can have different efficiencies.
Algorithms with a polynomial efficiency or slower (constant, linear, square, cube, etc.) are said to run in a reasonable amount of time. Algorithms with exponential or factorial efficiencies are examples of algorithms that run in an unreasonable amount of time.
Some problems cannot be solved in a reasonable amount of time because there is no efficient algorithm for solving them. In these cases, approximate solutions are sought.
A heuristic is an approach to a problem that produces a solution that is not guaranteed to be optimal but may be used when techniques that are guaranteed to always find an optimal solution are impractical.
While computing innovations are typically designed to achieve a specific purpose, they may have unintended consequences.
Describe issues that contribute to the digital divide
Internet access varies between socioeconomic, geographic, and demographic characteristics, as well as between countries.
The “digital divide” refers to differing access to computing devices and the Internet, based on socioeconomic, geographic, or demographic characteristics.
The digital divide can affect both groups and individuals.
The digital divide raises issues of equity, access, and influence, both globally and locally
The digital divide is affected by the actions of individuals, organizations, and governments.
The way statements are sequenced and combined in a program determines the computed result. Programs incorporate iteration and selection constructs to represent repetition and make decisions to handle varied input values.
For binary search algorithms:
a. Determine the number of iterations required to find a value in a data set.
b. Explain the requirements necessary to complete a binary search.
The binary search algorithm starts at the middle of a sorted data set of numbers and eliminates half of the data; this process repeat until the desired value is found or all elements have been eliminated.
Data must be in sorted order to use the binary search algorithm.
Binary search is often more efficient than sequential/linear search when applied to sorted data.
12%–19%
5. Computing Innovations
Investigate computing innovations.
28%–33%
6. Responsible Computing
Contribute to an inclusive, safe, collaborative, and ethical computing culture.
Not assessed
Big Idea 3: Algorithms and Programming
30%–35%
Big Idea 4: Computer Systems and Networks
11%–15%
Big Idea 5: Impact of Computing
21%–26%
Computational Thinking Practice
Description
Exam Weighting (Multiple-Choice Section)
1. Computational Solution Design
Design and evaluate computational solutions for a purpose.
18%–25%
2. Algorithms and Program Development
Develop and implement algorithms.
20%–28%
3. Abstraction in Program Development
Develop programs that incorporate abstractions.
7%–12%
4. Code Analysis
Evaluate and test algorithms and programs.
-- Example 1
print("Hello World")
-- Example 2
print("AP Computer Science Principles")
-- Example 3
-- Problem 1
print("Problem 1")-- Problem 2
print("Problem 2")-- Problem 3
print("Problem 3")-- Problem 4
print("Problem 4")Express an algorithm that uses selection without using a programming language.
Selection determines which parts of an algorithm are executed based on a condition being true or false.
For selection:
a. Write conditional statements.
b. Determine the results of conditional statements.
Conditional statements, or “if-statements,” affect the sequential flow of control by executing different statements based on the value of a Boolean expression.
The exam reference sheet provides:
Text:
IF (condition)
{
<block of statements>
}
in which the code in block of statements is executed if the Boolean expression condition evaluates to true; no action is taken if condition evaluates to false.
The exam reference sheet provides:
Text:
IF (condition)
{
<block of statements>
}
ELSE
{
<second block of statements>
}
in which the code in first block of statements is executed if the Boolean expression condition evaluates to true; otherwise, the code in second block of statements is executed.
A variable is an abstraction inside a program that can hold a value. Each variable has associated data storage that represents one value at a time, but that value can be a list or other collection that in turn contains multiple values.
Using meaningful variable names helps with the readability of program code and understanding of what values are represented by the variables.
Some programming languages provide types to represent data, which are referenced using variables. These types include numbers, Booleans, lists, and strings.
Some values are better suited to representation using one type of datum rather than another
Determine the value of a variable as a result of an assignment.
The assignment operator allows a program to change the value represented by a variable.
The exam reference sheet provides the “ ” operator to use for assignment. For example,
Text:
a <-- expression
Block:
evaluates expression and then assigns a copy of the result to the variable a.
The value stored in a variable will be the most recent value assigned. For example:
a <-- 1
b <-- a
a <-- 2
display(b)
still displays 1
Programmers break down problems into smaller and more manageable pieces. By creating procedures and leveraging parameters, programmers generalize processes that can be reused. Procedures allow programmers to draw upon existing code that has already been tested, allowing them to write programs more quickly and with more confidence.
For procedure calls:
a. Write statements to call procedures.
b. Determine the result or effect of a procedure call.
A procedure is a named group of programming instructions that may have parameters and return values.
Procedures are referred to by different names, such as method or function, depending on the programming language.
Parameters are input variables of a procedure. Arguments specify the values of the parameters when a procedure is called.
A procedure call interrupts the sequential execution of statements, causing the program to execute the statements within the procedure before continuing. Once the last statement in the procedure (or a return statement) has executed, flow of control is returned to the point immediately following where the procedure was called.
The exam reference sheet provides procName(arg1, arg2, ...) as a way to call
Text:
PROCEDURE procName(parameter1, parameter2, ...)
{
<block of statements>
}
Block:
which takes zero or more arguments; arg1 is assigned to parameter1, arg2 is assigned to parameter2, and so on.
The exam reference sheet provides the procedure
Text:
DISPLAY(expression)
Block:
to display the value of expression, followed by a space.
The exam reference sheet provides the
Text:
RETURN(expression)
Block:
statement, which is used to return the flow of control to the point where the procedure was called and to return the value of expression.
The exam reference sheet provides
result <-- procName(arg1, arg2, ...)
to assign to result the "value of the procedure" being returned by calling.
Text:
PROCEDURE procName(parameter1, parameter2, ...)
{
<block of statements>
RETURN(expression)
}
Block:
The exam reference sheet provides procedure
Text:
INPUT()
Block:
which accepts a value from the user and returns the input value.
The way statements are sequenced and combined in a program determines the computed result. Programs incorporate iteration and selection constructs to represent repetition and make decisions to handle varied input values.
Express an algorithm that uses sequencing without using a programming language.
An algorithm is a finite set of instructions that accomplish a specific task.
Beyond visual and textual programming languages, algorithms can be expressed in a variety of ways, such as natural language, diagrams, and pseudocode.
Algorithms executed by programs are implemented using programming languages.
Every algorithm can be constructed using combinations of sequencing, selection, and iteration.
Represent a step-by-step algorithmic process using sequential code statements.
Sequencing is the application of each step of an algorithm in the order in which the code statements are given.
A code statement is a part of program code that expresses an action to be carried out.
An expression can consist of a value, a variable, an operator, or a procedure call that returns a value.
Expressions are evaluated to produce a single value
The evaluation of expressions follows a set order of operations defined by the programming language.
Sequential statements execute in the order they appear in the code segment.
Clarity and readability are important considerations when expressing an algorithm in a programming language.
Evaluate expressions that use arithmetic operators.
Arithmetic operators are part of most programming languages and include addition, subtraction, multiplication, division, and modulus operators.
The exam reference sheet provides a MOD b, which evaluates to the remainder when a is divided by b. Assume that a is an integer greater than or equal to 0 and b is an integer greater than 0. For example, 17 MOD 5 evaluates to 2.
The exam reference sheet provides the arithmetic operators +, -, *, /, and MOD. Text and Block:
a + b
a - b
a * b
a / b
These are used to perform arithmetic on a and b. For example, 17 / 5 evaluates to 3.4.
The order of operations used in mathematics applies when evaluating expressions. The MOD operator has the same precedence as the * and / operators.
Developers create and innovate using an iterative design process that is userfocused, that incorporates implementation/feedback cycles, and that leaves ample room for experimentation and risk-taking.
Develop a program using a development process.
A development process can be ordered and intentional, or exploratory in nature.
There are multiple development processes. The following phases are commonly used when developing a program:
§ investigating and reflecting
§ designing
§ prototyping § testing
A development process that is iterative requires refinement and revision based on feedback, testing, or reflection throughout the process. This may require revisiting earlier phases of the process.
A development process that is incremental is one that breaks the problem into smaller pieces and makes sure each piece works before adding it to the whole.
Design a program and its user interface.
The design of a program incorporates investigation to determine its requirements.
Investigation in a development process is useful for understanding and identifying the program constraints, as well as the concerns and interests of the people who will use the program.
Some ways investigation can be performed are as follows:
§ collecting data through surveys
§ user testing § interviews
§ direct observations
Program requirements describe how a program functions and may include a description of user interactions that a program must provide.
A program’s specification defines the requirements for the program.
In a development process, the design phase outlines how to accomplish a given program specification.
The design phase of a program may include:
brainstorming
planning and storyboarding
organizing the program into modules and functional components
creation of diagrams that represent the layouts of the user interface
Describe the purpose of a code segment or program by writing documentation.
Program documentation is a written description of the function of a code segment, event, procedure, or program and how it was developed.
Comments are a form of program documentation written into the program to be read by people and do not affect how a program runs.
Programmers should document a program throughout its development.
Program documentation helps in developing and maintaining correct programs when working individually or in collaborative programming environments.
Not all programming environments support comments, so other methods of documentation may be required.
Acknowledge code segments used from other sources.
It is important to acknowledge any code segments that were developed collaboratively or by another source.
Acknowledgement of a code segment(s) written by someone else and used in a program can be in the program documentation. The acknowledgement should include the origin or original author’s name.
print("Activity 2.4")
-- Example 1
-- Example 2
-- Example 3a MOD b
development of a testing strategy for the program
Explain how data can be represented using bits.
Data values can be stored in variables, lists of items, or standalone constants and can be passed as input to (or output from) procedures.
Computing devices represent data digitally, meaning that the lowest-level components of any value are bits.
Bit is shorthand for binary digit and is either 0 or 1.
A byte is 8 bits.
Abstraction is the process of reducing complexity by focusing on the main idea. By hiding details irrelevant to the question at hand and bringing together related and useful details, abstraction reduces complexity and allows one to focus on the idea.
Bits are grouped to represent abstractions. These abstractions include, but are not limited to, numbers, characters, and color.
The same sequence of bits may represent different types of data in different contexts.
Analog data have values that change smoothly, rather than in discrete intervals, over time. Some examples of analog data include pitch and volume of music, colors of a painting, or position of a sprinter during a race.
The use of digital data to approximate real world analog data is an example of abstraction.
Analog data can be closely approximated digitally using a sampling technique, which means measuring values of the analog signal at regular intervals called samples. The samples are measured to figure out the exact bits required to store each sample.
Explain the consequences of using bits to represent data.
In many programming languages, integers are represented by a fixed number of bits, which limits the range of integer values and mathematical operations on those values. This limitation can result in overflow or other errors.
Other programming languages provide an abstraction through which the size of representable integers is limited only by the size of the computer’s memory; this is the case for the language defined in the exam reference sheet.
In programming languages, the fixed number of bits used to represent real numbers limits the range and mathematical operations on these values; this limitation can result in round-off and other errors. Some real numbers are represented as approximations in computer storage.
For binary numbers:
a. Calculate the binary (base 2) equivalent of a positive integer (base 10) and vice versa.
b. Compare and order binary numbers.
Number bases, including binary and decimal, are used to represent data.
Binary (base 2) uses only combinations of the digits zero and one.
Decimal (base 10) uses only combinations of the digits 0 – 9.
As with decimal, a digit’s position in the binary sequence determines its numeric value. The numeric value is equal to the bit’s value (0 or 1) multiplied by the place value of its position.
The place value of each position is determined by the base raised to the power of the position. Positions are numbered starting at the rightmost position with 0 and increasing by 1 for each subsequent position to the left.
a. Describe the benefits of fault tolerance
b. Explain how a given system is fault-tolerant.
c. Identify vulnerabilities to failure in a system.
The Internet has been engineered to be faulttolerant, with abstractions for routing and transmitting data.
Redundancy is the inclusion of extra components that can be used to mitigate failure of a system if other components fail.
One way to accomplish network redundancy is by having more than one path between any two connected devices.
If a particular device or connection on the Internet fails, subsequent data will be sent via a different route, if possible.
When a system can support failures and still continue to function, it is called fault-tolerant. This is important because elements of complex systems fail at unexpected times, often in groups, and fault tolerance allows users to continue to use the network.
Redundancy within a system often requires additional resources but can provide the benefit of fault tolerance.
The redundancy of routing options between two points increases the reliability of the Internet and helps it scale to more devices and more people.
A decidable problem is a decision problem for which an algorithm can be written to produce a correct output for all inputs (e.g., “Is the number even?”).
An undecidable problem is one for which no algorithm can be constructed that is always capable of providing a correct yes-or-no answer.
An undecidable problem may have some instances that have an algorithmic solution, but there is no algorithmic solution that could solve all instances of the problem.
Parallel and distributed computing leverage multiple computers to more quickly solve complex problems or process large data sets.
For sequential, parallel, and distributed computing:
a. Compare problem solutions.
b. Determine the efficiency of solutions.
Sequential computing is a computational model in which operations are performed in order one at a time.
Parallel computing is a computational model where the program is broken into multiple smaller sequential computing operations, some of which are performed simultaneously
Distributed computing is a computational model in which multiple devices are used to run a program.
Comparing efficiency of solutions can be done by comparing the time it takes them to perform the same task.
A sequential solution takes as long as the sum of all of its steps.
A parallel computing solution takes as long as its sequential tasks plus the longest of its parallel tasks.
The “speedup” of a parallel solution is measured in the time it took to complete the task sequentially divided by the time it took to complete the task when done in parallel.
Describe benefits and challenges of parallel and distributed computing.
Parallel computing consists of a parallel portion and a sequential portion.
Solutions that use parallel computing can scale more effectively than solutions that use sequential computing.
Distributed computing allows problems to be solved that could not be solved on a single computer because of either the processing time or storage needs involved.
Distributed computing allows much larger problems to be solved quicker than they could be solved using a single computer.
When increasing the use of parallel computing in a solution, the efficiency of the solution is still limited by the sequential portion. This means that at some point, adding parallel portions will no longer meaningfully increase efficiency
Computer systems and networks facilitate the transfer of data.
Explain how computing devices work together in a network.
A computing device is a physical artifact that can run a program. Some examples include computers, tablets, servers, routers, and smart sensors.
A computing system is a group of computing devices and programs working together for a common purpose.
A computer network is a group of interconnected computing devices capable of sending or receiving data.
A computer network is a type of computing system.
A path between two computing devices on a computer network (a sender and a receiver) is a sequence of directly connected computing devices that begins at the sender and ends at the receiver.
Routing is the process of finding a path from sender to receiver.
The bandwidth of a computer network is the maximum amount of data that can be sent in a fixed amount of time.
Bandwidth is usually measured in bits per second.
Explain how the Internet works.
The Internet is a computer network consisting of interconnected networks that use standardized, open (nonproprietary) communication protocols.
Access to the Internet depends on the ability to connect a computing device to an Internet connected device.
A protocol is an agreed-upon set of rules that specify the behavior of a system.
The protocols used in the Internet are open, which allows users to easily connect additional computing devices to the Internet.
Routing on the Internet is usually dynamic; it is not specified in advance.
The scalability of a system is the capacity for the system to change in size and scale to meet new demands.
The Internet was designed to be scalable.
Explain how data are sent through the Internet via packets
Information is passed through the Internet as a data stream. Data streams contain chunks of data, which are encapsulated in packets.
Packets contain a chunk of data and metadata used for routing the packet between the origin and the destination on the Internet, as well as for data reassembly.
Packets may arrive at the destination in order, out of order, or not at all.
IP, TCP, and UDP are common protocols used on the Internet.
Describe the differences between the Internet and the World Wide Web.
The World Wide Web is a system of linked pages, programs, and files.
HTTP is a protocol used by the World Wide Web.
The World Wide Web uses the Internet
While computing innovations are typically designed to achieve a specific purpose, they may have unintended consequences.
Explain how people participate in problem-solving processes at scale.
Widespread access to information and public data facilitates the identification of problems, development of solutions, and dissemination of results
Science has been affected by using distributed and “citizen science” to solve scientific problems.
Citizen science is scientific research conducted in whole or part by distributed individuals, many of whom may not be scientists, who contribute relevant data to research using their own computing devices.
Crowdsourcing is the practice of obtaining input or information from a large number of people via the Internet.
Human capabilities can be enhanced by collaboration via computing.
Crowdsourcing offers new models for collaboration, such as connecting businesses or social causes with funding.
While computing innovations are typically designed to achieve a specific purpose, they may have unintended consequences.
Explain how an effect of a computing innovation can be both beneficial and harmful.
People create computing innovations.
The way people complete tasks often changes to incorporate new computing innovations.
Not every effect of a computing innovation is anticipated in advance.
A single effect can be viewed as both beneficial and harmful by different people, or even by the same person.
Advances in computing have generated and increased creativity in other fields, such as medicine, engineering, communications, and the arts.
Explain how a computing innovation can have an impact beyond its intended purpose.
Computing innovations can be used in ways that their creators had not originally intended:
§ The World Wide Web was originally intended only for rapid and easy exchange of information within the scientific community.
§ Targeted advertising is used to help businesses, but it can be misused at both individual and aggregate levels.
§ Machine learning and data mining have enabled innovation in medicine, business, and science, but information discovered in this way has also been used to discriminate against groups of individuals
Some of the ways computing innovations can be used may have a harmful impact on society, the economy, or culture.
Responsible programmers try to consider the unintended ways their computing innovations can be used and the potential beneficial and harmful effects of these new uses.
It is not possible for a programmer to consider all the ways a computing innovation can be used.
Computing innovations have often had unintended beneficial effects by leading to advances in other fields.
Rapid sharing of a program or running a program with a large number of users can result in significant impacts beyond the intended purpose or control of the programmer.
-- Problem 2
print("Problem 2")-- Problem 3
print("Problem 3")-- Problem 2
print("Problem 2")-- Problem 3
print("Problem 3")-- Problem 4
print("Problem 4")-- Problem 5
print("Problem 5")-- Problem 6
print("Problem 6")-- Example 1
print("Hello World")
-- Example 2
print("AP Computer Science Principles")
-- Example 3
-- Example 4
-- Example 5
-- Example 6
-- Example 7
-- Example 8-- Problem 1
print("Problem 1")-- Problem 2
print("Problem 2")-- Problem 3
print("Problem 3")-- Problem 4
print("Problem 4")-- Problem 5
print("Problem 5")-- Problem 6
print("Problem 6")-- Problem 7
print("Problem 7")-- Problem 8
print("Problem 8")-- Problem 9
print("Problem 9")-- Problem 10
print("Problem 10")local myName = ""
print("Name: " .. myName)
-- Example 1
-- Example 2
-- Example 3
-- Example 4
-- Example 5
-- Example 6
-- Example 7
-- Example 8
-- Example 9
-- Example 10
-- Example 11print("Problem 1")print("Problem 2")print("Problem 3")print("Problem 4")print("Problem 5")print("Problem 6")print("Problem 7")print("Problem 8")print("Problem 9")print("Problem 10")print("Session 11")
-- Example 1
-- Example 2
-- Example 3
-- Example 4
-- Example 5
-- Example 6
-- Example 7
-- Example 8
-- Example 9
-- Example 10
-- Example 11print("Problem 1")print("Problem 2")print("Problem 3")print("Problem 4")print("Problem 5")print("Problem 6")print("Problem 7")print("Problem 8")print("Problem 9")print("Problem 10")print("Problem 11")print("Problem 12")print("Problem 13")print("Problem 14")local myName = ""
print("Name: " .. myName)
-- Example 1
-- Example 2
-- Example 3
-- Example 4
-- Example 5
print("Problem 1")print("Problem 2")print("Problem 3")print("Problem 4")print("Problem 5")print("Problem 6")print("Problem 7")print("Problem 8")print("Problem 9")-- Example 1
print("Hello World")
-- Example 2
print("AP Computer Science Principles")
-- Example 3
-- Example 4
-- Example 5
-- Example 6
-- Example 7
-- Example 8-- Problem 1
print("Problem 1")-- Problem 2
print("Problem 2")-- Problem 3
print("Problem 3")-- Problem 4
print("Problem 4")-- Problem 5
print("Problem 5")-- Problem 6
print("Problem 6")-- Problem 7
print("Problem 7")-- Problem 8
print("Problem 8")-- Problem 9
print("Problem 9")-- Problem 10
print("Problem 10")For relationships between two variables, expressions, or values:
a. Write expressions using relational operators.
b. Evaluate expressions that use relational operators.
A Boolean value is either true or false.
The exam reference sheet provides the following relational operators: =, ≠, >, <, ≥, and ≤.
Text and Block:
a = b
a ≠ b
a > b
a < b
a ≥ b
a ≤ b
These are used to test the relationship between two variables, expressions, or values. A comparison using a relational operator evaluates to a Boolean value. For example, a = b evaluates to true if a and b are equal; otherwise, it evaluates to false.
For relationships between Boolean values:
a. Write expressions using logical operators.
b. Evaluate expressions that use logical operators.
The exam reference sheet provides the logical operators NOT, AND, and OR, which evaluate to a Boolean value.
The exam reference sheet provides
Text:
NOT condition
Block:
which evaluates to true if condition is false; otherwise it evaluates to false.
The exam reference sheet provides
Text:
condition1 AND condition2
Block:
which evaluates to true if both condition1 and condition2 are true; otherwise it evaluates to false.
The exam reference sheet provides
Text:
condition1 OR condition2
Block:
which evaluates to true if condition1 is true or if condition2 is true or if both condition1 and condition2 are true; otherwise it evaluates to false.
The operand for a logical operator is either a Boolean expression or a single Boolean value.
A list is an ordered sequence of elements. For example,
[value1, value2, value3, ...]
describes a list where value1 is the first element, value2 is the second element, value3 is the third element, and so on.
An element is an individual value in a list that is assigned a unique index.
An index is a common method for referencing the elements in a list or string using natural numbers.
A string is an ordered sequence of characters.
For data abstraction:
a. Develop data abstraction using lists to store multiple elements.
b. Explain how the use of data abstraction manages complexity in program code.
Data abstraction provides a separation between the abstract properties of a data type and the concrete details of its representation.
Data abstractions manage complexity in programs by giving a collection of data a name without referencing the specific details of the representation.
Data abstractions can be created using lists.
Developing a data abstraction to implement in a program can result in a program that is easier to develop and maintain.
Data abstractions often contain different types of elements.
The use of lists allows multiple related items to be treated as a single value. Lists are referred to by different names, such as array, depending on the programming language.
The exam reference sheet provides the notation
[value1, value2, value3, ...]
Text:
aList <-- [value1, value2, value3, ...]
Block:
creates a new list that contains the values value1, value2, value3, and ... at indices 1, 2, 3, and ... respectively and assigns it to aList.
Text:
aList <-- []
Block:
creates a new empty list and assigns it to aList.
Text:
aList <-- bList
Block:
assigns a copy of the list bList to the list aList. For example, if bList contains [20, 40, 60], then aList will also contain [20, 40, 60] after the assignment.
The exam reference sheet describes a list structure whose index values are 1 through the number of elements in the list, inclusive. For all list operations, if a list index is less than 1 or greater than the length of the list, an error message is produced and the program will terminate.
Express an algorithm that uses iteration without using a programming language.
Iteration is a repeating portion of an algorithm. Iteration repeats a specified number of times or until a given condition is met.
For iteration:
a. Write iteration statements.
b. Determine the result or side effect of iteration statements.
Iteration statements change the sequential flow of control by repeating a set of statements zero or more times, until a stopping condition is met.
The exam reference sheet provides
Text:
REPEAT n TIMES
{
<block of statements>
}
Block:
in which the block of statements is executed n times.
The exam reference sheet provides
Text:
REPEAT UNTIL (condition)
{
<block of statements>
}
in which the code in block of statements is repeated until the Boolean expression condition evaluates to true.
In REPEAT UNTIL(condition) iteration, an infinite loop occurs when the ending condition will never evaluate to true.
In REPEAT UNTIL(condition) iteration, if the conditional evaluates to true initially, the loop body is not executed at all, due to the condition being checked before the loop.
Programmers break down problems into smaller and more manageable pieces. By creating procedures and leveraging parameters, programmers generalize processes that can be reused. Procedures allow programmers to draw upon existing code that has already been tested, allowing them to write programs more quickly and with more confidence.
local myName = ""
print("Name: " .. myName)
-- Example 0
-- Example 1
-- Example 2
-- Example 3
-- Example 4
-- Example 5
-- Example 6
-- Example 7
print("Problem 1")local myName = ""
print("Name: " .. myName)
-- initialize done to false
local done = false
-- sentinel controlled while loop
while not done do
-- Menu Options
print("Menu")
print("E1 - Example 1")
print("Q - Quit")
io.write("Choice: ")
local choice = io.read()
if choice == "E1" then
print("Example 1")
-- add code here
elseif choice == "E2" then
print("Example 2")
-- add code here
elseif choice == "E3" then
print("Example 3")
-- add code here
elseif choice == "E4" then
print("Example 4")
-- add code here
elseif choice == "E5" then
print("Example 5")
-- add code here
elseif choice == "E6" then
print("Example 6")
-- add code here
elseif choice == "E7" then
print("Example 7")
-- add code here
elseif choice == "E8" then
print("Example 8")
-- add code here
elseif choice == "E9" then
print("Example 9")
-- add code here
-- Q condition
elseif choice == "Q" then
print("Quit!")
done = true
-- else condition
else
print("Invalid choice")
end
end
print("Problem 1")-- Problem 1
print("Problem 1")-- Problem 2
print("Problem 2")-- Problem 3
print("Problem 3")print("Problem 2")print("Problem 3")print("Problem 4")print("Problem 5")print("Problem 6")print("Problem 7")print("Problem 8")print("Problem 9")print("Problem 2")print("Problem 3")print("Problem 4")print("Problem 5")print("Problem 6")print("Problem 7")print("Problem 8")print("Problem 9")-- Problem 4
print("Problem 4")local myName = ""
print("Name: " .. myName)
-- Example 1
-- Example 2 and 3 inputs
-- Example 2
-- Example 3
-- Example 4
-- Example 5
-- Example 6
-- Example 7
-- Example 8
-- Example 9
-- Example 10
print("Problem 1")print("Problem 2")print("Problem 3")print("Problem 4")print("Problem 5")print("Problem 6")print("Problem 7")print("Problem 8")print("Problem 9")print("Name: ") -- add your name here
print("Project 1")
print("Title: Jungle Run")
local health = 80 -- initial health (physical or mental?)
print("Your plane has crashed and when you exit, you find yourself in a humid jungle,")
print("unsure if there are other people around.")
print()
print("Do you re-enter the plane or seek shelter elsewhere?")
print("1 - re-enter")
print("2 - seek shelter")
io.write("> ")
local choice=io.read("*n")
io.read() -- consuming new line
if choice == 1 then
print("you chose to re-enter")
health = health + 5
print("Current Health: " .. health)
elseif choice == 2 then
print("you chose to seek shelter")
health = health + 10
print("Current Health: " .. health)
else
print("invalid choice")
endprint("Session 12")
-- Example 1
-- Example 2
-- Example 3
-- Example 4
-- Example 5
-- Example 6
-- Iterative Program Design
-- Version 1 - Basic Program
-- Version 2 - Improved (Adds Tax)
-- Version 3 - Even Better (User - Friendly Output)
print("Problem 1")print("Problem 2")print("Problem 3")print("Problem 4")print("Problem 5")print("Problem 6")-- Version 1
-- Purpose: Collect parking time and display a base fee
-- Version 2
-- Purpose: Calculate fee using rounded-up hours
-- Version 3
-- Purpose: Apply a maximum daily charge
-- Version 4
-- Purpose: Validate input before calculating fee
print("Name: ") -- add your name here
print("Project 2")
print("Title: Jungle Run")
local points = 0
print("Your plane has crashed and when you exit, you find yourself in a humid jungle,")
print("unsure if there are other people around.")
print()
print("Do you re-enter the plane or seek shelter elsewhere?")
print("1 - re-enter")
print("2 - seek shelter")
io.write("> ")
local choice = tonumber(io.read())
if choice == 1 then
print("you chose to re-enter")
elseif choice == 2 then
print("you chose to seek shelter")
else
print("invalid choice")
endExplain how the use of procedural abstraction manages complexity in a program.
One common type of abstraction is procedural abstraction, which provides a name for a process and allows a procedure to be used only knowing what it does, not how it does it.
Procedural abstraction allows a solution to a large problem to be based on the solutions of smaller subproblems. This is accomplished by creating procedures to solve each of the subproblems.
The subdivision of a computer program into separate subprograms is called modularity.
A procedural abstraction may extract shared features to generalize functionality instead of duplicating code. This allows for program code reuse, which helps manage complexity.
Using parameters allows procedures to be generalized, enabling the procedures to be reused with a range of input values or arguments.
Using procedural abstraction helps improve code readability.
Using procedural abstraction in a program allows programmers to change the internals of the procedure (to make it faster, more efficient, use less storage, etc.) without needing to notify users of the change as long as what the procedure does is preserved.
Develop procedural abstractions to manage complexity in a program by writing procedures.
The exam reference sheet provides
Text:
PROCEDURE procName(parameter1, parameter2, ...)
{
<block of statements>
}
Block:
which is used to define a procedure that takes zero or more arguments. The procedure contains block of statements.
The exam reference sheet provides:
Text:
PROCEDURE procName(parameter1, parameter2, ...)
{
<block of statements>
RETURN(expression)
}
Block:
which is used to define a procedure that takes zero or more arguments. The procedure contains block of statements and returns the value of expression. The RETURN statement may appear at any point inside the procedure and causes an immediate return from the procedure back to the calling statement.
The way statements are sequenced and combined in a program determines the computed result. Programs incorporate iteration and selection constructs to represent repetition and make decisions to handle varied input values.
For list operations:
a. Write expressions that use list indexing and list procedures.
b. Evaluate expressions that use list indexing and list procedures.
The exam reference sheet provides basic operations on lists, including:
accessing an element by index
Text:
aList[i]
Block:
accesses the element of aList at index i. The first element of aList is at index 1 and is accessed using the notation aList[1].
assigning a value of an element of a list to a variable
Text:
x <-- aList[i]
Block:
assigning a value to an element of a list
Text:
aList[i] <-- x
Block:
assigns the value of x to aList[i].
Text:
aList[i] <-- aList[j]
Block:
assigns the value of aList[j] to aList[i].
inserting elements at a given index
Text:
INSERT(aList, i, value)
Block:
shifts to the right any values in aList at indices greater than or equal to i. The length of the list is increased by 1, and value is placed at index i in aList.
adding elements to the end of the list
Text:
APPEND(aList, value)
Block:
evaluates to the number of elements currently in aList.
List procedures are implemented in accordance with the syntax rules of the programming language.
removing elements
Text:
REMOVE(aList, value)
Block:
removes the item at index i in aList and shifts to the left any values at indices greater than i. The length of aList is decreased by 1.
determining the length of a list
Text:
LENGTH(aList)
Block:
evaluates to the number of elements currently in aList.
List procedures are implemented in accordance with the syntax rules of the programming language.
For algorithms involving elements of a list:
a. Write iteration statements to traverse a list.
b. Determine the result of an algorithm that includes list traversals.
Traversing a list can be a complete traversal, where all elements in the list are accessed, or a partial traversal, where only a portion of elements are accessed.
Iteration statements can be used to traverse a list.
The exam reference sheet provides
Text:
FOR EACH item IN aList
{
<block of statements>
}
Block:
The variable item is assigned the value of each element of aList sequentially, in order, from the first element to the last element. The code in block of statements is executed once for each assignment of item.
Knowledge of existing algorithms that use iteration can help in constructing new algorithms. Some examples of existing algorithms that are often used with lists include:
determining a minimum or maximum value in a list
computing a sum or average of a list of numbers
Linear search or sequential search algorithms check each element of a list, in order, until the desired value is found or all elements in the list have been checked.
Personally identifiable information (PII) is information about an individual that identifies, links, relates, or describes them. Examples of PII include:
Social Security number
age
race
phone number(s)
medical information
financial information
biometric data
Search engines can record and maintain a history of searches made by users.
Websites can record and maintain a history of individuals who have viewed their pages.
Devices, websites, and networks can collect information about a user’s location.
Technology enables the collection, use, and exploitation of information about, by, and for individuals, groups, and institutions.
Search engines can use search history to suggest websites or for targeted marketing.
Disparate personal data, such as geolocation, cookies, and browsing history, can be aggregated to create knowledge about an individual.
PII and other information placed online can be used to enhance a user’s online experiences.
PII stored online can be used to simplify making online purchases.
Commercial and governmental curation of information may be exploited if privacy and other protections are ignored.
Information placed online can be used in ways that were not intended and that may have a harmful impact. For example, an email message may be forwarded, tweets can be retweeted, and social media posts can be viewed by potential employers.
PII can be used to stalk or steal the identity of a person or to aid in the planning of other criminal acts.
Once information is placed online, it is difficult to delete.
Programs can collect your location and record where you have been, how you got there, and how long you were at a given location.
Information posted to social media services can be used by others. Combining information posted on social media and other sources can be used to deduce private information about you.
Explain how computing resources can be protected and can be misused.
Authentication measures protect devices and information from unauthorized access. Examples of authentication measures include strong passwords and multifactor authentication.
A strong password is something that is easy for a user to remember but would be difficult for someone else to guess based on knowledge of that user.
Multifactor authentication is a method of computer access control in which a user is only granted access after successfully presenting several separate pieces of evidence to an authentication mechanism, typically in at least two of the following categories: knowledge (something they know), possession (something they have), and inherence (something they are)
Multifactor authentication requires at least two steps to unlock protected information; each step adds a new layer of security that must be broken to gain unauthorized access.
Encryption is the process of encoding data to prevent unauthorized access. Decryption is the process of decoding the data. Two common encryption approaches are:
Symmetric key encryption involves one key for both encryption and decryption.
Public key encryption pairs a public key for encryption and a private key for decryption. The sender does not need the receiver’s private key to encrypt a message, but the receiver’s private key is required to decrypt the message.
Certificate authorities issue digital certificates that validate the ownership of encryption keys used in secure communications and are based on a trust model.
Computer virus and malware scanning software can help protect a computing system against infection.
A computer virus is a malicious program that can copy itself and gain access to a computer in an unauthorized way. Computer viruses often attach themselves to legitimate programs and start running independently on a computer.
Malware is software intended to damage a computing system or to take partial control over its operation.
All real-world systems have errors or design flaws that can be exploited to compromise them. Regular software updates help fix errors that could compromise a computing system.
Users can control the permissions programs have for collecting user information. Users should review the permission settings of programs to protect their privacy
Explain how unauthorized access to computing resources is gained.
Phishing is a technique that attempts to trick a user into providing personal information. That personal information can then be used to access sensitive online resources, such as bank accounts and emails.
Keylogging is the use of a program to record every keystroke made by a computer user in order to gain fraudulent access to passwords and other confidential information.
Data sent over public networks can be intercepted, analyzed, and modified. One way that this can happen is through a rogue access point.
A rogue access point is a wireless access point that gives unauthorized access to secure networks.
A malicious link can be disguised on a web page or in an email message.
Unsolicited emails, attachments, links, and forms in emails can be used to compromise the security of a computing system. These can come from unknown senders or from known senders whose security has been compromised.
Untrustworthy (often free) downloads from freeware or shareware sites can contain malware.
local myName = ""
print("Name: " .. myName)
-- define main function
function main()
print("Main Function")
local done = false
local choice = nil
while not done do
print("Menu")
print("E1 - Example 1")
print("Q - Quit")
io.write("Choice: ")
choice = io.read()
if choice == "E1" then
print("Example 1")
-- call Example 1 Function
elseif choice == "E2" then
print("Example 2")
-- call Example 1 Function twice
elseif choice == "E3" then
print("Example 3")
-- call Example 3 Function
elseif choice == "E4" then
print("Example 4")
-- call Example 4 Function
elseif choice == "E5" then
print("Example 5")
-- call Example 5 Function
elseif choice == "Q" then
done = true
else
print("Invalid Choice")
end
end
end
-- define Example 1 Function
-- define Example 3 Function
-- define Example 4 Function
-- define Example 5 Function
-- call main function, do not delete!
main()-- main function
function main()
-- call problem1 function
end
-- problem1 function definition
-- call to main function
main()-- main function
function main()
-- call problem2 function
end
-- problem2 function definition
-- call to main function
main()-- main function
function main()
-- call problem3 function
end
-- problem3 function definition
-- call to main function
main()-- main function
function main()
-- call problem4 function
end
-- problem4 function definition
-- call to main function
main()-- main function
function main()
-- call problem5 function
end
-- problem5 function definition
-- call to main function
main()-- main function
function main()
-- call problem6 function
end
-- problem6 function definition
-- call to main function
main()-- define main function
function main()
print("Main Function")
local done = false
local choice = nil
print("Menu")
print("E1 - Example 1")
print("Q - Quit")
io.write("Choice: ")
choice = io.read()
if choice == "E1" then
-- create list1
-- before
-- Example 1 Function call
-- After
elseif choice == "E2" then
-- Example 2 Function call
elseif choice == "E3" then
-- Example 3 Function call
elseif choice == "E4" then
-- Example 4 Function call
elseif choice == "E5" then
-- Example 5 Function call
elseif choice == "E6" then
-- Linear Search Function call
elseif choice == "E7" then
-- Binary Function call
elseif choice == "Q" then
done = true
else
print("Invalid Choice")
end
end
-- define printList function
-- define Example 1 Function
-- define Example 2 Function
-- define Example 3 Function
-- define Example 4 Function
-- define Example 5 Function
-- define linearSearch Function
-- define binarySearch Function
function binarySearch(array, target)
local low = 1
local high = #array
while low <= high do
local mid = (low + high) // 2 -- midpoint
local guess = array[mid]
if guess == target then
return mid -- target found
elseif guess > target then
high = mid - 1
else
low = mid + 1
end
end
return -1
end
-- call to main function, do not delete!
main()
-- function definition
function problem1()
end
-- function definition
function main()
-- function call
end
-- call to main function
main()-- function definition
function problem2()
end
-- function definition
function main()
-- function call
end
-- call to main function
main()-- function definition
function problem3()
end
-- function definition
function main()
-- function call
end
-- call to main function
main()-- function definition
function problem4()
end
-- function definition
function main()
-- function call
end
-- call to main function
main()-- function definition
function problem5()
end
-- function definition
function main()
-- function call
end
-- call to main function
main()-- function definition
function problem6()
end
-- function definition
function main()
-- function call
end
-- call to main function
main()-- function definition
function problem7()
end
-- function definition
function main()
-- function call
end
-- call to main function
main()local myName = ""
print("Name: " .. myName)
-- define main function
function main()
print("Main Function")
local done = false
local choice = nil
while not done do
print("Menu")
print("E1 - Example 1")
print("Q - Quit")
io.write("Choice: ")
choice = io.read()
if choice == "E1" then
-- call Example 1 Function
elseif choice == "E2" then
-- call Example 2 Function
elseif choice == "E3" then
-- call Example 3 Function
elseif choice == "E4" then
-- call Example 4 Function
elseif choice == "E5" then
-- call Example 5 Function
elseif choice == "E6" then
-- call Example 6 Function
elseif choice == "E7" then
-- call Example 7 Function
elseif choice == "Q" then
done = true
else
print("Invalid Choice")
end
end
end
-- define Example 1 Function
-- define Example 2 Function
-- define Example 3 Function
-- define Example 4 Function
-- define Example 5 Function
-- define Example 6 Function
-- define Example 7 Function
-- call main function
main()-- main function
function main()
-- call problem1 function
end
-- problem1 function definition
-- call to main function
main()local myName = ""
print("Name: " .. myName)
-- define main function
function main()
print("Hello Main Function")
print(myName)
local done = false
local choice = nil
while not done do
print("Menu")
print("E1 - Example 1")
print("Q - Quit")
io.write("Choice: ")
choice = io.read()
if choice == "E1" then
-- Example 1 Function call
example1()
elseif choice == "E2" then
-- Example 2 Function call
example2()
elseif choice == "E3" then
-- Example 3 Function call
example3()
elseif choice == "E4" then
-- Example 4 Function call
example4()
elseif choice == "Q" then
done = true
else
print("Invalid Choice")
end
end
end
-- define Example 1 Function
function example1()
print("Example 1")
-- define friends list
-- print the number of elements
-- print the element one by one
-- using a for loop, print the index and elements
-- assign value to first friend
-- assign value to the last friend
-- print the friends
end
-- define Example 2 Function
function example2()
-- create an empty list
-- add an element to the end of the list (append)
-- add an element to the end of the list (append)
-- add an element to the beginning of the list (insert)
-- print using for in loop
-- print using for in loop with index
-- delete a fruit
-- print using for in loop
end
-- define Example 3 Function
function example3()
end
-- define Example 4 Function
function example4()
end
-- call to main function, do not delete!
main()-- function definition
function problem1()
end
-- function definition
function main()
-- function call
end
-- call to main function
main()
Explain how computing innovations are improved through collaboration.
A computing innovation includes a program as an integral part of its function.
A computing innovation can be physical (e.g., self-driving car), nonphysical computing software (e.g., picture editing software), or a nonphysical computing concept (e.g., e-commerce).
Effective collaboration produces a computing innovation that reflects the diversity of talents and perspectives of those who designed it.
Collaboration that includes diverse perspectives helps avoid bias in the development of computing innovations.
Consultation and communication with users are important aspects of the development of computing innovations.
Information gathered from potential users can be used to understand the purpose of a program from diverse perspectives and to develop a program that fully incorporates these perspectives.
Self-driving cars are a computing innovation because they rely on advanced computing technologies to operate autonomously and navigate through the environment without human intervention. Self-driving cars incorporate:
Artificial Intelligence and Machine Learning: Self-driving cars utilize artificial intelligence (AI) and machine learning algorithms to analyze sensor data, make real-time decisions, and interact with the surrounding environment. These algorithms enable the car to perceive its surroundings, recognize objects such as pedestrians, other vehicles, and traffic signs, and make decisions based on the observed data.
Sensor Fusion: Self-driving cars integrate various sensors, including cameras, lidar, radar, and ultrasonic sensors, to gather detailed information about the surrounding environment. The data from these sensors is processed and fused together to create a comprehensive understanding of the car's surroundings, allowing it to detect and respond to potential obstacles, traffic conditions, and road hazards.
High-Performance Computing: Self-driving cars require powerful computing systems to process the vast amount of sensor data in real-time and execute complex algorithms for decision-making. These computing systems use high-performance processors, graphics processing units (GPUs), and specialized hardware like field-programmable gate arrays (FPGAs) or application-specific integrated circuits (ASICs) to handle the computational demands of the self-driving software.
Mapping and Localization: Self-driving cars rely on detailed maps and precise localization techniques to navigate accurately. Computing technologies are employed to create and update high-definition maps that include road geometry, traffic signs, and landmarks. Additionally, localization algorithms use sensor data and map matching techniques to determine the car's position and orientation in real-time.
Connectivity and Communication: Self-driving cars often leverage connectivity technologies, such as GPS, cellular networks, and vehicle-to-vehicle (V2V) or vehicle-to-infrastructure (V2I) communication, to enhance their capabilities. They can exchange information with other vehicles and infrastructure components, enabling cooperative driving, real-time traffic updates, and improved situational awareness.
Safety and Redundancy: Computing innovations play a vital role in ensuring the safety of self-driving cars. Redundant computing systems and fault-tolerant architectures are employed to provide backup and fail-safe mechanisms. Real-time monitoring, error detection, and response systems continuously assess the performance of the car's computing components to maintain safe operation.
Self-driving cars represent a significant leap forward in automotive technology, transforming the transportation industry and reshaping urban mobility.
E-commerce, which stands for electronic commerce, is a computing innovation because it leverages computing technologies and the internet to enable online buying and selling of goods and services. Here's why e-commerce can be considered a computing innovation:
Online Marketplaces: E-commerce platforms serve as digital marketplaces where businesses and consumers can interact and conduct transactions. These platforms provide a virtual space where sellers can showcase their products, and buyers can browse and make purchases conveniently using computing devices such as computers, smartphones, or tablets.
Digital Storefronts: E-commerce allows businesses to establish digital storefronts, which are websites or online portals where they can display their products or services. These digital storefronts enable businesses to reach a global audience and operate 24/7 without the limitations of physical locations, expanding their market reach and potential customer base.
Secure Transactions: E-commerce incorporates secure online payment systems that leverage computing technologies to ensure the confidentiality and integrity of financial transactions. Techniques such as encryption, secure sockets layer (SSL), and tokenization are used to protect sensitive payment information, instilling trust and confidence in online transactions.
Inventory Management and Logistics: Computing technologies are utilized in e-commerce for efficient inventory management and logistics. Businesses can track their inventory levels in real-time, automate order fulfillment processes, and streamline shipping and delivery operations using digital systems and algorithms. This improves operational efficiency, reduces errors, and enhances the overall customer experience.
Personalization and Recommendation Systems: E-commerce platforms employ computing innovations such as artificial intelligence and machine learning algorithms to personalize the shopping experience for users. These algorithms analyze user behavior, preferences, and past purchases to provide personalized product recommendations, tailored promotions, and targeted advertisements, enhancing customer satisfaction and engagement.
Data Analytics and Insights: E-commerce generates vast amounts of data related to customer behavior, sales trends, and market dynamics. Computing technologies enable businesses to collect, process, and analyze this data to gain valuable insights into customer preferences, optimize pricing strategies, improve inventory management, and make data-driven business decisions.
Digital Marketing and Customer Engagement: E-commerce leverages computing technologies for digital marketing campaigns, customer relationship management (CRM), and customer engagement. Businesses can utilize online advertising, email marketing, social media platforms, and personalized messaging to reach and engage customers, driving traffic to their e-commerce platforms and fostering brand loyalty.
E-commerce has revolutionized the way businesses operate and transformed the retail landscape.
Computing innovations are often improved through collaboration due to the following reasons:
Diverse Perspectives: Collaboration brings together individuals from different backgrounds, expertise, and experiences. This diversity of perspectives can lead to more innovative and comprehensive solutions. By combining various viewpoints, collaborators can identify potential flaws, suggest improvements, and explore novel approaches that may not have been possible through individual efforts.
Knowledge Sharing: Collaboration allows for the exchange of knowledge and expertise. When experts in different domains come together, they can share their insights, techniques, and best practices. This sharing of knowledge can lead to a deeper understanding of the problem space and uncover new possibilities for innovation. Collaborators can also learn from each other's mistakes and successes, accelerating the pace of innovation.
Resource Pooling: Collaborative efforts often involve pooling together resources, including financial resources, research facilities, computing infrastructure, and data sets. This pooling of resources allows collaborators to tackle larger and more complex challenges that may be beyond the capabilities of individual researchers or organizations. Access to shared resources can significantly enhance the quality and scope of computing innovations.
Complementary Skills: Collaboration enables individuals with complementary skills to work together towards a common goal. For example, a computing innovation may require expertise in software development, hardware design, data analysis, user experience, and domain knowledge. Collaborating allows each participant to focus on their area of expertise, leveraging the strengths of others to create a more robust and well-rounded solution.
Faster Iteration and Validation: Collaboration can accelerate the iteration and validation process of computing innovations. By working together, collaborators can provide rapid feedback, conduct peer reviews, and engage in constructive discussions. This iterative approach allows for quicker identification of flaws, refinement of ideas, and validation of concepts through experiments and real-world testing. The collective effort of collaborators can lead to faster progress and more reliable outcomes.
Shared Goals and Network Effects: Collaborating on computing innovations often involves shared goals and a collective vision. When multiple organizations or individuals collaborate towards a common objective, they can leverage network effects, where the value of the innovation increases as more participants join in. This can attract additional resources, funding, and expertise, further fueling the progress and impact of the innovation.
Overall, collaboration in computing innovations promotes synergy, fosters creativity, and leverages collective intelligence. It enables the pooling of knowledge, resources, and skills, leading to more robust, comprehensive, and impactful solutions that drive advancements in the field.
Explain how computing innovations are developed by groups of people.
Online tools support collaboration by allowing programmers to share and provide feedback on ideas and documents.
Common models such as pair programming exist to facilitate collaboration.
There are numerous online tools available that support collaboration across various domains. Here are some examples of popular online collaboration tools:
Google Workspace: Formerly known as G Suite, Google Workspace offers a suite of collaborative tools, including Google Docs, Google Sheets, Google Slides, and Google Drive. These tools allow multiple users to work together in real-time, simultaneously editing documents, spreadsheets, and presentations. They also provide features like commenting, version history, and file sharing.
Microsoft Office 365: Microsoft Office 365 provides online versions of Microsoft Office applications, such as Word, Excel, PowerPoint, and OneNote, along with cloud storage on OneDrive. These tools enable real-time collaboration, document sharing, and co-authoring, allowing multiple users to work together seamlessly.
Slack: Slack is a popular team communication and collaboration platform. It provides chat-based workspaces where teams can organize discussions, share files, and collaborate on projects. Slack integrates with various third-party tools and offers features like channels, direct messaging, file sharing, and app integrations.
GitHub: GitHub is a web-based platform primarily used for version control and collaboration on software development projects. It allows developers to host and manage code repositories, track changes, and collaborate with others through features like pull requests, issue tracking, and code reviews.
Zoom: While primarily known as a video conferencing tool, Zoom also supports collaboration through features like screen sharing, virtual whiteboarding, and breakout rooms. It enables teams to collaborate remotely, host online meetings, and work together on presentations or brainstorming sessions.
Demonstrate effective interpersonal skills during collaboration.
Effective collaborative teams practice interpersonal skills, including but not limited to:
communication
consensus building
conflict resolution
negotiation
Effective collaborative teams understand the importance of interpersonal skills and actively practice them to foster positive relationships, effective communication, and successful teamwork. Here are some key interpersonal skills that effective collaborative teams commonly practice:
Communication: Effective communication is vital for collaborative teams. They practice active listening to understand others' perspectives, ask clarifying questions, and provide clear and concise information. They express their thoughts and ideas articulately and respectfully, fostering open and honest communication among team members.
Emotional Intelligence: Collaborative teams practice emotional intelligence, which involves recognizing and understanding emotions in oneself and others. They demonstrate empathy, show support and understanding, and manage their emotions constructively. By considering the emotions and needs of team members, they build trust and create a positive team environment.
Conflict Resolution: Conflict is inevitable in collaborative teams, but effective teams practice constructive conflict resolution. They seek to understand the underlying issues, encourage open dialogue, and work towards finding mutually beneficial solutions. They value diverse perspectives and approach conflicts with a problem-solving mindset, rather than personal attacks or defensiveness.
Trust Building: Trust is the foundation of effective collaboration. Teams actively work on building trust by being reliable, transparent, and accountable. They follow through on commitments, share information openly, and respect confidentiality. Trust allows team members to feel safe, take risks, and collaborate more effectively.
Flexibility and Adaptability: Collaborative teams understand the need to be flexible and adaptable in dynamic environments. They embrace change, respond positively to new ideas and approaches, and are open to feedback. They understand that flexibility helps the team navigate challenges, adjust plans, and make necessary adaptations to achieve shared goals.
Conflict Management: Effective teams are skilled in managing and resolving conflicts. They create a safe space for team members to express concerns or disagreements, without fear of judgment or reprisal. They encourage constructive discussions and seek win-win solutions. By addressing conflicts early and constructively, they prevent them from escalating and impacting team dynamics.
Collaboration and Cooperation: Collaborative teams actively promote a cooperative mindset. They encourage teamwork, foster a sense of shared purpose, and emphasize collective achievement rather than individual success. They value collaboration and create an environment where everyone's contributions are recognized and appreciated.
Respect and Appreciation: Effective collaborative teams demonstrate respect for each other's opinions, ideas, and contributions. They appreciate diversity, recognizing the strengths and expertise each team member brings to the table. They celebrate achievements, acknowledge efforts, and show gratitude for the contributions of their colleagues.
By practicing these interpersonal skills, collaborative teams create a supportive and productive environment where ideas flourish, innovation thrives, and team members can collaborate effectively towards shared goals.
-- main function
function main()
-- call problem2 function
end
-- problem2 function definition
-- call to main function
main()-- main function
function main()
-- call problem3 function
end
-- problem3 function definition
-- call to main function
main()-- main function
function main()
-- call problem4 function
end
-- problem4 function definition
-- call to main function
main()-- main function
function main()
-- call problem5 function
end
-- problem5 function definition
-- call to main function
main()-- main function
function main()
-- call problem6 function
end
-- problem6 function definition
-- call to main function
main()-- main function
function main()
-- call problem7 function
end
-- problem7 function definition
-- call to main function
main()-- main function
function main()
-- call problem8 function
end
-- problem8 function definition
-- call to main function
main()-- main function
function main()
-- call problem9 function
end
-- problem9 function definition
-- call to main function
main()-- Main Function
function main()
print("College Cost Project")
local done = false
local choice = nil
while not done do
print("Menu")
print("C1 - Public College") -- replace with the name of your public college
print("C2 - Private College") -- replace with the name of your private college
print("L - Loan Calculator")
print("Q - Quit")
io.write("Choice: ")
choice = io.read()
if choice == "C1" then
-- call the tuition, housing and meals functions
elseif choice == "C2" then
-- call the tuition, housing and meals functions
elseif choice == "L" then
elseif choice == "Q" then
done = true
else
print("Invalid Choice")
end
end
end
-- define public tuition function
function public_tuition()
end
-- define public housing function
function public_housing()
end
-- define public meals function
function public_meals()
end
-- define private tuition function
function private_tuition()
end
-- define private housing function
function private_housing()
end
-- define private meals function
function private_meals()
end
-- define loan calculator Function
function loanCalculator()
end
-- call main function
main()-- function definition
function problem2()
end
-- function definition
function main()
-- function call
end
-- call to main function
main()
-- function definition
function problem3()
end
-- function definition
function main()
-- function call
end
-- call to main function
main()
-- function definition
function problem4()
end
-- function definition
function main()
-- function call
end
-- call to main function
main()
-- function definition
function problem5()
end
-- function definition
function main()
-- function call
end
-- call to main function
main()
-- function definition
function problem6()
end
-- function definition
function main()
-- function call
end
-- call to main function
main()
-- Main function
function main()
-- Initialize playlist with 10 songs
local playlist = {}
local done = false
while not done do
print("My Playlist Manager")
print("1. View playlist")
print("2. View playlist with index positions")
print("3. Add a song")
print("4. Remove a song")
print("5. Select a random song")
print("6. Sort playlist")
print("7. Shuffle playlist")
print("8. Reorder playlist")
print("9. Clear playlist")
print("10. Exit")
io.write("Choose an option (1-10): ")
local choice = io.read("*n")
io.read()
if choice == 1 then
print("My current playlist")
elseif choice == 2 then
print("My current playlist with index positions")
elseif choice == 3 then
print("Add a song")
elseif choice == 4 then
print("Remove a song")
elseif choice == 5 then
print("Here's a random song!")
elseif choice == 6 then
print("Sort my playlist alphabetically")
elseif choice == 7 then
print("Shuffle playlist")
-- Loop through the list from the last index to the second index.
-- Generate a random index between 1 and i
-- Swap elements at index i and j
elseif choice == 8 then
print("Reorder playlist")
elseif choice == 9 then
print("Playlist cleared.")
elseif choice == 10 then
print("Goodbye!")
done = true
else
print("Invalid choice. Please try again.")
end
end
end
-- Call the main function
main()
function w21problem1()
-- Parallel lists for student data
local names = {"Alice", "Bob", "Charlie", "David", "Eve", "Frank", "Grace", "Henry", "Ivy", "Jack"}
local schools = {"Oak Prep", "Public High", "Oak Prep", "Community School", "Public High",
"Oak Prep", "Community School", "Public High", "Elite Academy", "Community School"}
local scores = {85, 88, 80, 90, 87, 82, 91, 86, 84, 89}
for i = 1, #scores do
if schools[i] == "Oak Prep" then
scores[i] = scores[i] * 1.05
end
end
-- Sort students based on final scores (descending order)
for i = 1, #scores - 1 do
for j = i + 1, #scores do
if scores[i] < scores[j] then
-- Swap scores
scores[i], scores[j] = scores[j], scores[i]
-- Swap names
names[i], names[j] = names[j], names[i]
-- Swap schools
schools[i], schools[j] = schools[j], schools[i]
end
end
end
-- Print final student rankings
print("**Biased College Admissions Results:**")
for i = 1, #names do
print(i .. ". " .. names[i] .. " - School: " .. schools[i] .. " - Final Score: " .. string.format("%.2f", scores[i]))
end
end
-- Run the biased admissions system
w21problem1()
HTML (HyperText Markup Language) is the standard language used to create web pages. It uses tags to structure content and tell the browser how to display text, images, links, and other elements.
Every HTML document follows this basic structure:
<!DOCTYPE html> - Declares this as an HTML5 document
<html> - Root element that wraps all content
<head> - Contains metadata about the document
<title> - Sets the page title (appears in browser tab)
<body> - Contains all visible content
HTML uses tags to mark up content. Tags are enclosed in angle brackets < >.
Opening tag: <tagname>
Closing tag: </tagname>
Self-closing tag: <tagname />
Example:
HTML provides six levels of headings:
<table> - Creates the table
<tr> - Table row
<th> - Table header cell
<td> - Table data cell
text - Single line text
email - Email address
password - Password field
number - Numeric input
checkbox - Checkbox
radio - Radio button
submit - Submit button
These elements provide meaning to your content:
HTML elements can have attributes that provide additional information:
id - Unique identifier for an element
class - Groups elements for styling
src - Source for images, videos, etc.
href - URL for links
alt - Alternative text for images
title - Tooltip text
target - How to open links
Add comments to your HTML code (not visible on the page):
Always close your tags - Every opening tag should have a corresponding closing tag
Use semantic elements - Choose elements based on meaning, not appearance
Include alt text for images - Important for accessibility
Indent your code - Makes it easier to read and debug
Use lowercase for tags and attributes - Standard convention
Validate your HTML - Use online validators to check for errors
-- define main function
function main()
print("Main Function")
local done = false
local choice = nil
while not done do
print("Menu")
print("E1 - Example 1")
print("Q - Quit")
io.write("Choice: ")
choice = io.read()
if choice == "E1" then
-- call Example 1 Function
example1()
elseif choice == "E2" then
-- call Example 2 Function
example2()
elseif choice == "E3" then
-- call Example 3 Function
example3()
elseif choice == "E4" then
-- call Example 4 Function
example4()
elseif choice == "E5" then
-- call Example 5 Function
example5()
elseif choice == "Q" then
done = true
else
print("Invalid Choice")
end
end
end
-- define Example 1 Function
function example1()
-- Initialize parallel lists
local titles = {"Avengers: Endgame", "A Quiet Place", "Fast & Furious 9", "Parasite",
"Spider-Man: No Way Home", "The Lighthouse", "Titanic", "Moonlight",
"The Dark Knight", "Get Out"}
local types = {"blockbuster", "indie", "blockbuster", "indie", "blockbuster",
"indie", "blockbuster", "indie", "blockbuster", "indie"}
local ratings = {9.0, 8.5, 7.8, 9.2, 8.9, 8.4, 9.1, 8.7, 9.3, 8.6}
-- Increase ratings for blockbuster movies
for i = 1, #ratings do
if types[i] == "blockbuster" then
ratings[i] = ratings[i] + 0.5
end
end
-- Sort movies based on ratings (descending order)
for i = 1, #ratings - 1 do
for j = i + 1, #ratings do
if ratings[i] < ratings[j] then
-- Swap ratings
ratings[i], ratings[j] = ratings[j], ratings[i]
-- Swap titles
titles[i], titles[j] = titles[j], titles[i]
-- Swap types
types[i], types[j] = types[j], types[i]
end
end
end
-- Print the sorted movie recommendations
print("**Biased Movie Recommendations:**")
for i = 1, #titles do
print(i .. ". " .. titles[i] .. " - Rating: " .. ratings[i] .. " - Type: " .. types[i])
end
end
-- define Example 2 Function
function example2()
local list = {}
local numElements = 100
for i = 1, numElements do
table.insert(list, i)
end
-- Linear Search
local start_time = os.clock()
local result = linearSearch(list, numElements - 1)
local end_time = os.clock()
local elapsed_time = end_time - start_time
print(string.format("Linear search time: %.6f seconds", elapsed_time))
-- Binary Search
local start_time = os.clock()
local result = binarySearch(list, numElements - 1)
local end_time = os.clock()
local elapsed_time = end_time - start_time
print(string.format("Binary search time: %.6f seconds", elapsed_time))
end
-- define Quadratic Time Algorithm
function quadraticTimeAlgorithm(array)
for i = 1, #array do
for j = 1, #array do
-- Assuming a simple operation here like printing
-- or a minimal computation
local a = array[i] + array[j]
end
end
end
-- define Example 3 Function
function example3()
local list = {}
local numElements = 1000
for i = 1, numElements do
table.insert(list, i)
end
-- Quadratic Time Algorithm
local start_time = os.clock()
local result = quadraticTimeAlgorithm(list, numElements - 1)
local end_time = os.clock()
local elapsed_time = end_time - start_time
print(string.format("Quadratic Time Algorithm: %.6f seconds", elapsed_time))
end
-- define Example 4 Function
function example4()
local array = {}
local numElements = 15
for i = 1, numElements do
table.insert(array, i)
end
-- Exponential Time Algorithm
local start_time = os.clock()
generateSubsets(array, 1, {})
local end_time = os.clock()
local elapsed_time = end_time - start_time
print(string.format("Exponential Algorithm: %.6f seconds", elapsed_time))
end
-- define Example 5 Function
function example5()
local array = {}
local numElements = 10
for i = 1, numElements do
table.insert(array, i)
end
-- Factorial Time Algorithm
local start_time = os.clock()
local totalPermutations = generatePermutations(array, #array)
local end_time = os.clock()
local elapsed_time = end_time - start_time
print(string.format("Factorial Algorithm: %.6f seconds", elapsed_time))
end
-- define Linear Search Function
function linearSearch(array, target)
for index, value in ipairs(array) do
if value == target then
return index
end
end
return -1
end
-- define Binary Search Function
function binarySearch(array, target)
local low = 1
local high = #array
while low <= high do
local mid = (low + high) // 2 -- midpoint
local guess = array[mid]
if guess == target then
return mid -- target found
elseif guess > target then
high = mid - 1
else
low = mid + 1
end
end
return -1
end
-- define Generate Permutations Algorithm
function generatePermutations(array, n)
if n == 1 then
return 1 -- Return 1 for each completed permutation
else
local count = 0
for i = 1, n do
count = count + generatePermutations(array, n - 1)
if n % 2 == 0 then
array[i], array[n] = array[n], array[i]
else
array[1], array[n] = array[n], array[1]
end
end
return count
end
end
function printSet(set)
io.write("{")
for i, v in ipairs(set) do
io.write(v)
if i < #set then
io.write(", ")
end
end
io.write("}\n")
end
function generateSubsets(array, index, currentSubset)
if index > #array then
printSet(currentSubset)
return
end
-- Include the element at the current index
table.insert(currentSubset, array[index])
generateSubsets(array, index + 1, currentSubset)
-- Exclude the element at the current index
table.remove(currentSubset)
generateSubsets(array, index + 1, currentSubset)
end
-- call main function
main()
function w21problem2()
-- Parallel lists for suspect data
local names = {"Alice", "Bob", "Charlie", "David", "Eve", "Frank", "Grace", "Henry", "Ivy", "Jack"}
local neighborhoods = {"Downtown", "Suburb", "Downtown", "Uptown", "Suburb",
"Downtown", "Uptown", "Suburb", "Downtown", "Uptown"}
local base_risk_scores = {50, 30, 55, 40, 35, 60, 42, 28, 53, 38}
local prior_convictions = {true, false, true, false, false, true, false, false, true, false}
local employment_status = {"unemployed", "employed", "employed", "unemployed", "employed",
"unemployed", "employed", "employed", "unemployed", "employed"}
local ages = {22, 40, 19, 33, 29, 25, 48, 55, 21, 37}
-- Adjust risk scores with hidden biases
for i = 1, #base_risk_scores do
local risk = base_risk_scores[i]
if neighborhoods[i] == "Downtown" then
risk = risk * 1.08
end
if prior_convictions[i] then
risk = risk * 1.12
end
if employment_status[i] == "unemployed" then
risk = risk * 1.05
end
if ages[i] >= 18 and ages[i] <= 25 then
risk = risk * 1.06
end
base_risk_scores[i] = risk -- Store adjusted risk score
end
-- Sort suspects based on final risk scores (descending order)
for i = 1, #base_risk_scores - 1 do
for j = i + 1, #base_risk_scores do
if base_risk_scores[i] < base_risk_scores[j] then
-- Swap risk scores
base_risk_scores[i], base_risk_scores[j] = base_risk_scores[j], base_risk_scores[i]
-- Swap names
names[i], names[j] = names[j], names[i]
-- Swap neighborhoods
neighborhoods[i], neighborhoods[j] = neighborhoods[j], neighborhoods[i]
-- Swap prior convictions
prior_convictions[i], prior_convictions[j] = prior_convictions[j], prior_convictions[i]
-- Swap employment status
employment_status[i], employment_status[j] = employment_status[j], employment_status[i]
-- Swap ages
ages[i], ages[j] = ages[j], ages[i]
end
end
end
-- Print formatted final suspect rankings
print("\n**Biased Criminal Risk Assessment Results:**\n")
print(string.format("%-3s %-10s %-12s %-8s %-12s %-10s %s", "#", "Name", "Neighborhood", "Age", "Conviction", "Employment", "Risk Score"))
for i = 1, #names do
print(string.format("%-3d %-10s %-12s %-8d %-12s %-10s %.2f",
i, names[i], neighborhoods[i], ages[i], prior_convictions[i], employment_status[i], base_risk_scores[i]))
end
end
-- Run the biased risk assessment
w21problem2()
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello, World!</title>
</head>
<body>
Hello, World!
<h1>Main Title (Largest)</h1>
<h2>Section Title</h2>
<h3>Subsection Title</h3>
<h4>Sub-subsection Title</h4>
<h5>Small Title</h5>
<h6>Smallest Title</h6>
<p>This is a paragraph of text.</p>
<strong>Bold text</strong>
<em>Italic text</em>
<u>Underlined text</u>
<br>
<hr>
<ul>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ul>
<ol>
<li>First step</li>
<li>Second step</li>
<li>Third step</li>
</ol>
</body>
</html><!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<!-- Your content goes here -->
</body>
</html><p>This is a paragraph.</p><h1>Main Heading</h1>
<h2>Section Heading</h2>
<h3>Subsection Heading</h3>
<h4>Minor Heading</h4>
<h5>Small Heading</h5>
<h6>Smallest Heading</h6><p>This is a paragraph of text.</p>
<p>This is another paragraph.</p><strong>Bold text</strong>
<em>Italic text</em>
<u>Underlined text</u>
<br> <!-- Line break -->
<hr> <!-- Horizontal rule/line --><a href="https://www.example.com">Visit Example.com</a>
<a href="page2.html">Link to another page</a>
<a href="#section1">Link to section on same page</a><img src="image.jpg" alt="Description of image">
<img src="https://example.com/photo.png" alt="Remote image"><ul>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ul><ol>
<li>First step</li>
<li>Second step</li>
<li>Third step</li>
</ol><table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Row 1, Cell 1</td>
<td>Row 1, Cell 2</td>
</tr>
<tr>
<td>Row 2, Cell 1</td>
<td>Row 2, Cell 2</td>
</tr>
</table><form>
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<label for="message">Message:</label>
<textarea id="message" name="message"></textarea>
<input type="submit" value="Send">
</form><header>Page or section header</header>
<nav>Navigation links</nav>
<main>Main content area</main>
<article>Independent piece of content</article>
<section>Thematic grouping of content</section>
<aside>Sidebar content</aside>
<footer>Page or section footer</footer><img src="photo.jpg" alt="A beautiful sunset" width="300" height="200">
<a href="https://example.com" target="_blank" title="Opens in new tab">Link</a>
<p id="intro" class="highlight">Paragraph with ID and class</p><!-- This is a comment -->
<!--
This is a
multi-line comment
--><!DOCTYPE html>
<html>
<head>
<title>My First Web Page</title>
</head>
<body>
<header>
<h1>Welcome to My Website</h1>
<nav>
<a href="#about">About</a>
<a href="#contact">Contact</a>
</nav>
</header>
<main>
<section id="about">
<h2>About Me</h2>
<p>This is a paragraph about myself. I'm learning <strong>HTML</strong>!</p>
<img src="profile.jpg" alt="My profile picture">
</section>
<section>
<h2>My Hobbies</h2>
<ul>
<li>Reading books</li>
<li>Playing guitar</li>
<li>Coding websites</li>
</ul>
</section>
<section id="contact">
<h2>Contact Me</h2>
<form>
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<input type="submit" value="Send">
</form>
</section>
</main>
<footer>
<p>© 2025 My Website</p>
</footer>
</body>
</html>-- define main function
function main()
print("Main Function")
local done = false
local choice = nil
while not done do
print("Menu")
print("E1 - Example 1")
print("Q - Quit")
io.write("Choice: ")
choice = io.read()
if choice == "E1" then
-- call Example 1 Function
example1()
elseif choice == "E2" then
example2()
elseif choice == "E3" then
example3()
elseif choice == "E4" then
example4()
elseif choice == "E5" then
example5()
elseif choice == "Q" then
done = true
else
print("Invalid Choice")
end
end
end
-- define Example 1 Function
function example1()
-- double quotes
-- single quotes
-- \n is a newline
-- Lua multi-line string using double brackets
-- length
-- .upper()
-- .lower()
end
-- define Example 2 Function
function example2()
local major = "Computer Science"
print(major)
-- .sub()
-- .find()
-- loop and print every character
end
-- define Example 3 Function
function example3()
-- names list
-- ages list
-- print the names and corresponding ages
-- add a new name and age
-- print the last student's name and age
end
-- define Example 4 Function
function example4()
-- empty list of programming languages
-- add programming languages
-- the number of elements in the dictionary
-- call printDictionary function
-- delete a language
-- add a language
-- call printDictionary function (again)
end
-- define Example 5 Function
function example5()
local csTerms = {
["Algorithm"] = "A step-by-step procedure or formula for solving a problem or accomplishing a task.",
["API"] = "Application Programming Interface; a set of rules and protocols that allows different software applications to communicate with each other.",
["AI"] = "The simulation of human intelligence in machines that are programmed to think and learn like humans.",
["Binary"] = "A number system that uses only two digits, 0 and 1, which computers use to process and store data.",
["Blockchain"] = "A distributed, immutable ledger technology that records transactions across many computers to ensure data security and transparency.",
["Bug"] = "An error, flaw, or fault in a computer program that causes it to produce unexpected results or behave in unintended ways.",
["Debugging"] = "The process of finding and resolving defects or problems within a computer program.",
["Encryption"] = "The process of converting information or data into a code to prevent unauthorized access.",
["Firewall"] = "A network security system that monitors and controls incoming and outgoing network traffic based on predetermined security rules.",
["Machine Learning"] = "A subset of AI focused on building systems that learn from data rather than following explicit programming.",
["Network"] = "A collection of computers, servers, mainframes, or other devices connected to allow data sharing.",
["Open Source"] = "Software whose source code is available for modification or enhancement by anyone.",
["URL"] = "Uniform Resource Locator; the address of a resource on the Internet.",
["Wi-Fi"] = "A wireless networking technology that allows devices to interface with the Internet or communicate with one another without requiring a wired connection.",
["Zero-day"] = "A previously unknown software vulnerability that hackers can exploit before it is patched or mitigated."
}
-- access a particular element
-- update an element
-- access a particular element
-- check if key exists
-- call printDictionary
end
-- define dLength Function
-- define printDictionary Function
-- call main function
main()-- function definition
function problem1()
end
-- function definition
function main()
-- function call
end
-- call to main function
main()-- function definition
function problem2()
end
-- function definition
function main()
-- function call
end
-- call to main function
main()-- function definition
function problem3()
end
-- function definition
function main()
-- function call
end
-- call to main function
main()-- function definition
function problem4()
end
-- function definition
function main()
-- function call
end
-- call to main function
main()-- function definition
function problem5()
end
-- function definition
function main()
-- function call
end
-- call to main function
main()-- function definition
function problem6()
end
-- function definition
function main()
-- function call
end
-- call to main function
main()-- function definition
function problem7()
end
-- function definition
function main()
-- function call
end
-- call to main function
main()-- function definition
function problem8()
end
-- function definition
function main()
-- function call
end
-- call to main function
main()-- function definition
function problem9()
local cspTrivia = {}
cspTrivia["What is binary?"] = "Base-2 number system"
cspTrivia["What is an algorithm?"] = "Step-by-step procedure for solving a problem"
cspTrivia["What is abstraction in computing?"] = "Hiding complexity by removing details"
cspTrivia["What is the difference between the Internet and the World Wide Web?"] = "Internet is the network, Web is content"
cspTrivia["What is an IP address?"] = "Unique identifier for devices on a network"
cspTrivia["What is parallel computing?"] = "Multiple processors working simultaneously"
cspTrivia["What is a Boolean expression?"] = "True or false statement"
cspTrivia["What is a bit?"] = "0 or 1"
cspTrivia["What is the purpose of DNS?"] = "Convert domain names to IP addresses"
cspTrivia["What does HTTP stand for?"] = "HyperText Transfer Protocol"
end
-- function definition
function main()
-- function call
end
-- call to main function
main()-- define main function
function main()
print("Main Function")
local myOrder = {}
local done = false
local choice = nil
while not done do
print("Menu")
print("I - Restaurant Information")
print("A - Appetizers")
print("E - Entrees")
print("B - Beverages")
print("M - Modify Order")
print("P - Place Order")
print("Q - Quit")
io.write("Choice: ")
choice = io.read()
if choice == "Q" then
print("Quit!")
done = true
-- more choices
else
print("Invalid Choice")
end
end
end
-- define information function
-- define appetizers function
-- define entrees function
-- define desserts function
-- define beverages function
-- define modifyOrder function
-- define placeOrder function
-- call main function
main()