23 minute read

Computer Science8

Next Article
Chemistry4

Chemistry4

8. Computer Science

8.1

Advertisement

The advent of technology in our society has led to the intersection of billions of lives. Computer science, like the people it brings together, is an array of diverse components that integrate into a cohesive tool for interaction. Image by Hannah Chang ’22.

Visualizing a Rubik’s Cube in Processing

By Jacob Allebach ’20

In the class Algorithm Design, taught by Mr. Nassar, we were learning about search algorithms and how to apply them to common CS situations when someone pitched the idea of making a program that would solve a Rubik’s cube in the least number of moves. Immediately, the whole class became fascinated with this idea and began work on this sizable project.

Figure 8.1: Example permutations of the 2x2 Rubik’s Cube

We were split up into teams to make the work go more of the cube in Processing. In order for the cube to be displayed in 3-dimensions within Processing, I had to use P3D, which allows the use of a Z-axis along with the other axes. Because we weren’t familiar with P3D prior to this project, my partner and I had to figure out how to utilize the tools effectively.

The first struggle came with rotating each individual piece on the cube properly to get the effect we wanted. Since the pieces were created as separate cubes, we figured out that each cube’s center of rotation could be moved to the inside corner of each one by translating them slightly away from the origin point. Having each cube rotate differently around the same point allowed for smooth rotation. After that, we needed to add color to each side of the cube, but the cubes themselves could only be one solid color. We came up with the idea to put very thin boxes just above the surface of each cube face, giving the appearance of the cubes having different colors. Since each face is translated from the pivoting corner of each cube, they rotate with the cube they’re attached to. The last step was getting each face to change colors whenever a side rotates. This was tricky because we had programmed the cubes so that once a turn finished, smoothly, and the part I worked on was the visualization

it would snap back to its original position so the program

68

would not constantly have to update and store the amount of rotation that has happened. This means the stickers snap back with the cubes that they are connected to.

Luckily, one of the other teams had a good solution for us. Since the code that determines the fastest solution returns a list of cube states and a list of moves made, we By Jackson Zemek ’22 Introduction The main reason why 80% of people are not fond of wearing hearing aids today is that they expect the hearing aids to repair hearing, but hearing aids are only meant to minimize distracting background noise [1]. It is also embarrassing if a person wearing the hearing aid needs to tell the manager of the restaurant to turn the music down just to help one person hear better. My grandfather suffers the same issues as 80% of the people who are not fond of hearing aids. He does not like to wear his hearing aids because it is embarrassing to make others go out of their way to help just one person hear better, and he doesn’t like how the hearing aids only cancel out background noise, and not other distracting sounds.

There are two groups of hearing aids: analog hearing aids, and digital hearing aids. Analog hearing aids are a less expensive route for a hearing aid and tend to amplify all noises. Analog hearing aids also tend to be larger and more substantial in and around the ear than digital hearing aids. Digital hearing aids are the more complex and advanced model of hearing aids, and are programmed to minimize background noise and amplify noises in different environments. Proposal My project idea is to design an improved hearing aid. The program will start with asking the people who want to be heard to speak into the mic. While speaking into the mic, the program will move a frequency equalizer—a program that can manipulate different frequencies of sound—to the point where their voice will be amplified, and other noises will be fully cancelled out. This process will happen for each person, so there is one specific frequency equalizer (EQ) for every person who wants to be heard. This process can be improved by creating separate EQs for the left and right sides of the microphone and keeping track of pitches of voice to further cancel out other noises.

The average speaking voice frequencies of an adult Chapter 8. Computer Science

were able to make the cube go through the two lists, and continually rotate the given ways and update the colors of the cube to the next state just before moving on to the next turn. With the project finished and all the pieces put together, I can say with certainty that I learned a lot about

8.2 Designing a Frequency Selective Hearing Aid

P3D and how to represent objects in 3-dimensions. male can range from from 85 to 180 Hz, and the average speaking voice frequencies of an adult female can range from 165 to 255 Hz. With this information, my program can manipulate frequencies in this range more precisely, and can react when there are other frequencies at this range. I am currently using Atom combined with p5.js to write my code. P5 is a great programming language for manipulating sounds because it has built in libraries that allow the user to easily keep track of volume, frequency, and panning. I am also designing the user interface with Atom using html code.

There are different factors such as pitch, left-right, and frequency variation that can separate voices. I will add more voices and more EQs in the future so that the program can be used for many voices at a time. After the basics of my program are set, the code can expand to take into account those different factors such as pitch, left-right, and frequency variation to make the outputting sound more realistic. The goal is to make the person wearing the hearing aid hear accurately what is happening to the left and right of them so that they can be present in the moment.

After the completion of all of the following steps, I will need to make my product transportable, smaller, and more reliable so that it can be efficient and always work. This improved hearing aid is a new idea that will help the faint of hearing community and make their lives better and more enjoyable. Hearing is a core part of everyday life that most of us take for granted; the frequency hearing aid can help this common issue. To test how effective my product is, I will be gathering multiple recordings of my product being used by myself while also recording the same atmosphere without my program running. I will then compare the two sound files side by side to prove that my program in fact cancels out more sounds and amplifies the voices only.

There is very little risk involved in Designing a Frequency Selective Hearing Aid. The only risk is damage to hearing; however, it will be minimized by me carefully controlling the volume of my computer at all times, and

8.3 Noaman. Two-Dimensional Array and For Loop Example 69

making sure it is at a safe volume for my health. I will not be testing my hearing aid on anybody else, so there is no risk to other people.

[1]

[2]

[3] Bev Betkowski. Why Most People with Hearing Loss Don’t Use Hearing Aids. Aug. 2018. URL: medicalxpress.com/news/2018-08-peopleloss-dont-aids.html (cited on page 68). Communications System. URL: www . qrg . northwestern . edu / projects / vss / docs / Communications / 1 - what - is - frequency . html. Earbuds (for Teens) - Nemours KidsHealth. Jan. 2015. URL: kidshealth . org / en / teens / earbuds.html. [4]

[5]

[6]

[7] Hearing Aids. June 2018. URL: www.nidcd.nih. gov/health/hearing-aids.

Hearing Aids: How to Choose the Right One. May 2019. URL: www.mayoclinic.org/diseasesconditions / hearing - loss / in - depth / hearing-aids/art-20044116.

Sound Frequency. URL: www . sciencedirect . com / topics / engineering / sound - frequency.

What Sounds Can People Hear? Dec. 2018. URL: dosits . org / science / measurement / what - sounds-can-we-hear/.

8.3 Two-Dimensional Array and For Loop Example

By Niam Noaman ’21

Below is a small snippet of code from our AP CS class. We are currently learning about arrays. An array can store different elements or variables in a semi-organized fashion. There are some limitations to arrays. For example, they can’t change size, which is the number of variables you want to be stored. However, it can be much better to store elements in an array than all in separate variables. In this code, our class used two-dimensional arrays. These arrays have both rows and columns that can help organize variables further.

The code above sorts through a 2D array and finds the largest integer inside of the array. The first line of code simply creates the 2D array. The method is public (meaning it can be called by any object) and static (meaning it is not called on an instance of the class). The “int” means it returns an integer value. Within the method, we create a variable that stores the largest number; we call this value “num” for simplicity purposes. The next two lines of code are for loops. These loops increment through each value inside of the 2D array. That brings us to the if statement. This if statement runs for each variable and checks to see if the number that it is on is greater than the largest value, “num.” If this is true, then it will set “num” to the greater value and move on to the next variables. This allows the code to find the greatest value and set it to “num.” Once every value has been checked, the code moves on and returns “num.” This is the greatest value inside of the 2D arrays.

i n t [ ] [ ] i n t A r r a y = { { 1 , 2 , 3 , 4 , 5 } , { 2 , 7 , 3 , 4 , 5 } , { 3 , 4 , 1 , 4 , 5 } } ;

p u bli c s t a t i c i n t l a r g e s t ( ) { i n t num = 0 ; f o r ( i n t i = 0 ; i < i n t A r r a y . l e n g t h ; i ++ ) { f o r ( i n t j = 0 ; j < i n t A r r a y [ i ] . l e n g t h ; j ++ ){ i f ( i n t A r r a y [ i ] [ j ] > num ) { num = i n t A r r a y [ i ] [ j ] ; } } } r e t u r n num ; }

8.4

70

Interactive Weight Lifting Sensor

By Luke Lamitina ’22

Rationale

Every year, millions of people across America, and even the world, wake up on January 1st ready to commit to a healthier lifestyle. Many people try this once and then give up. They decide that in order to get healthy, they are going to try resistance training, which is a form of physical activity that puts stress on muscles in order to increase overall muscular strength. What they find is that the movement patterns required for some exercises are hard to do correctly. Some will find a personal trainer, others will say that personal trainers are too expensive [4]. No matter the excuse, the result is the same in many cases and is detrimental to the health of the person.

Staying healthy is a basic human necessity and resistance training is a very valuable way to increase overall health. Resistance exercise has been shown to have a huge benefit. It is shown to increase overall muscle mass, strength, flexibility, improved body composition, and, in some cases, self-esteem [2]. Not only is resistance training beneficial for muscles, but stronger muscles protect against joint bleeding and pain, which is very important for people with bleeding disorders [5]. Many people think that weight-bearing exercises cause increased joint pain, but according to a study in the Journal of Rheumatology, 43 percent of people found that weight-bearing exercises caused a reduction in joint pain [1].

Strength training can be very beneficial, but also very detrimental if done without proper form or equipment. Every year, thousands of people get hurt trying to improve their health by lifting weights. For every 1000 hours of CrossFit training, a form of resistance training, there is an average of 3.1 injuries [6]. One of the risks of training with improper form is the creation of imbalances. Sometimes people can get by with having bad form when lifting, but by doing so, they create imbalances in their muscle strength and composition. Imbalances are a very largely overlooked consequence of lifting with bad form [3].

Resistance training has a vastly positive effect on humanity and society due to its physical and emotional benefits. A happy and healthy version of humanity is necessary for the types of problems that we will have to tackle in the coming decades, and even centuries. If humanity as a whole is healthier, it could possibly lead to a more peaceful and civilized future for us and future generations to come.

The goal of the Interactive Weight Lifting Sensor is Chapter 8. Computer Science

to reduce the risk of injury and increase overall strength while weight training.

Procedure 1.

2.

3.

4.

5.

6.

7.

8. 9.

10. 11.

12.

13. Find an adequate sensor (MPU-6050) that is equipped with an accelerometer and gyroscope. Wire up the sensor to a breadboard and Arduino Uno Board. Use Arduino to start getting yaw-pitch-roll (ypr) values from the sensor. Print “TILTED” to the serial monitor in Arduino if the yaw-pitch-roll values increase or decrease by more than 10 degrees. Interface Arduino with Processing so that I can print ypr values on the serial monitor on Processing. Make a Processing sketch that visualizes the movement of the sensor as a bar. Make it so that the bar changes color if the ypr values are +/- 10 degrees. Add audio files that play when the sensor is tilted. Code an additional cylinder into the sketch that will represent the force vector. Add Bluetooth capability. 3D print the clip that the sensor will be placed in and clipped to the bar. If all of the above is done, add a speed monitor that prints speed of bar to the monitor. Transfer the speed monitor to the actual sketch.

Materials Arduino Uno Board Breadboard 3D Printer (For clip that sensor will sit inside of) MPU-6050 3 Axis Accelerometer Gyroscope Wires

Design Criteria / Expected Outcomes

The device that I am building will fit securely to barbel and connect remotely to a software program on a nearby computer via Bluetooth. It will then transmit live statistics of the movement of the bar, such as tilt, a force vector, and speed. Additionally, there will be an audio feature for when one of the statistics is not ideal. An audio file will play when this happens and give advice on how to fix the problem.

8.5 Routledge. Word Ladders 71

Data Analysis

In order to determine what the actual, correct metrics for the bar movement are, I will take tests of professionals lifting the bar in different movements. I will average the tilt, speed, and force vectors over all of the tests in order to produce ideal tilt, speed, and force vectors for all of the specific movements.

[1]

[2] Z Barone. Is Weightlifting Bad for you in the Long Run? URL: https : / / sites . psu . edu / siowfa15/2015/10/29/is- weightliftingbad- for- you- in- the- long- run/ (cited on page 70).

Benefits of Proper Form and Technique during Resistance Training. URL: https : / / www . walkitscience . org / physical - health - 1 / physical- activity/benefits- of- properBy Scott Routledge ’20

In a word ladder, the goal is to see if there is a way to get from a word like “green” to a completely different word like “brown” by changing one letter at a time. Each time you change a letter has to result in a new word.

A graph can be used to create the foundation for a word ladder. In computer science, a graph is a data structure used to show relationships between items. Graphs are made up of vertices – typically numbered from 0–n –and edges that connect them. A visual representation of a graph is shown below. For this problem, let’s create a graph where each vertex is a unique five-letter word. Pairs of words like “ankle” and “angle” would be connected by an edge – they are referred to as adjacent vertices. On the other hand, “angle” and “angel” are not adjacent to each other.

An example of a visual representation of a graph and corresponding adjacency lists: [3]

[4]

[5]

[6] form- and- technique- during- resistancetraining/ (cited on page 70). Consequences of Fitness Training with Bad Form | Not So Basic Fitness. URL: http : / / www . notsobasicfitness.com/consequences-oftraining - with - bad - form - imbalances/ (cited on page 70). Gym Accident Statistics. URL: https : / / www . legalmatch . com / law - library / article / gym - accident - statistics . html (cited on page 70). Strength Training 101. URL: https://hemaware. org / mind - body / strength - training - 101 (cited on page 70). Weight-training do’s and don’ts. URL: https:// www.mayoclinic.org/healthy- lifestyle/ fitness/in- depth/weight- training/art

8.5 Word Ladders: An Application of Depth First Search

20045842 (cited on page 70).

Vertex 0 1 2 3 4 5 Adjacent Vertices 3, 6 5 3, 4, 5, 6 0, 2, 4, 5, 6 1, 2, 3, 4, 5, 6 0, 2, 3, 4, 5

In addition to a visual depiction, graphs can also be defined using an array of sets. Each index in the array corresponds to a vertex and contains a set (an unordered group of numbers) of all the adjacent vertices.

Because words like “green” and “brown” are not adjacent, we need a way of searching the graph to see if there is a path between them. Depth-First Search, or DFS, is an algorithm for finding a path between two vertices on a graph. Starting at any given vertex, DFS will look at the set of adjacent vertices for the target, then, if the target is not found, it will move to another adjacent vertex and search its set for the target. DFS will continue to move through the graph, marking each vertex that it visits so that, if it reaches a dead end, it can go backwards.

DFS is analogous to exploring a maze with a roll of string. In a maze, there is no way of knowing if the path will lead to the target until you have reached the end. In the case that the path leads to a dead-end – this could be when all possible directions have already been visited

72

– you can use the string to retrace your steps to a point where you can follow a different path.

Depth First Search is only one algorithm for searching through a graph. A drawback of using DFS is that it will only find a path – not necessarily the shortest path. For instance, when using DFS, going from “green” to “brown” takes 12 steps but going from “brown” to “green” is a 281 step journey. Neither one of these is the shortest path. The Quest to Save Humanity By Christopher Porco Introduction During the summer of 2019, I took a computer science course at Carnegie Mellon University. As a part of this course – 15-112 – students create a "term project" that is meant to provide students the opportunity to showcase many skills they learned throughout the course [2]. I have always loved a good video game, and I felt this would be a great opportunity for me to design one. I called it The Quest to Save Humanity.

Figure 8.2: The loading screen for my video game The Quest to Save Humanity The Quest to Save Humanity is a single-player game where the player is tasked with – you guessed it – saving humanity. "How did the world come to this point?" you might ask. Figure 8.3: The "About" page Chapter 8. Computer Science

You can achieve a cool effect in Processing by iterating through the list of steps, flashing each word on the screen in a monospaced font, one after another, emphasizing the letter that has changed each time.

An example of a word ladder (green to brown): green, greed, greet, great, groat, groan, grown, frown,

8.6

flown, clown, blown, brown.

Well, looking at Figure 8.3, the player learns that humanity has been taken hostage by the Alcatar alien tribe, and we must save as many hostages as possible. But how does the player play the game? Looking at the "Instructions" page (Figure 8.4), the player gets all the necessary

information about the controls. Figure 8.4: The "Instructions" page

Now that the player knows what they are getting themselves into, let’s begin to save humanity. After clicking the "play" button, the player is presented with two options

as seen in Figure 8.5.

Figure 8.5: The "Play" menu

Depending on the mode the player selects, the aliens will have a different movement strategy. When the player clicks the first mode, "swarm," the player’s character (green triangle) spawns in space. Moving around, the

8.6 Porco. The Quest to Save Humanity 73

player sees aliens rushing towards them – they must shoot and destroy the aliens to ensure the player doesn’t lose all of their health! After enough exploration and some assistance from the mini-map in the bottom-right corner, the player will find the hostage trapped in a yellow box. Once the player hovers over it, they have saved that hostage! The player will then enter the next round, with the aliens increasing in difficulty after each hostage is saved. Figure 8.6: The player has found a hostage! Dijkstra’s Algorithm Alternatively, the player can select the "Dijkstra’s" mode. In this mode, everything is the same as the "swarm" mode except for how the aliens move. In "swarm," the aliens spawn in at a random point on the map and move in towards the player’s location. While this works, I implemented a "Dijkstra’s" mode such that the aliens move with more predictability for the user, making developing a getaway strategy from the aliens a little bit easier.

In the "Dijkstra’s" mode, the locations of the stars in the background are used as nodes in a graph. The aliens navigate that graph to attack the player using Dijkstra’s algorithm, which is an algorithm created by Edsger Dijkstra. In this context, it generates the shortest path between an alien and the player.

This algorithm begins by setting every node in the graph for a given alien to a very large number (indicating that its value is unknown) and adds them to list Q. In the main loop, v is set to the node in Q that has the smallest distance from the current node. Then, for each neighbor of v, called u, the distance from v to u is updated in the dist array if a shorter path to u has been found. After the main loop executes, the dist array is returned. This array contains the shortest distance from node source to any desired ending node. Psuedocode for this algorithm can be seen in Figure 8.7. gorithm. URL: https://brilliant.org/wiki/ dijkstras - short - path - finder/ (cited on page 73). f u n c t i o n D i j k s t r a ( Graph , s o u r c e ) : d i s t [ s o u r c e ] : = 0 f o r e a c h v e r t e x v i n G raph : i f v != s o u r c e d i s t [ v ] : = i n f i n i t y add v t o Q

w hil e Q i s n o t empty : v : = v e r t e x i n Q wit h

min

d i s t [ v ]

remove v from Q f o r e a c h n ei g h b o r u o f v : a l t : = d i s t [ v ] + l e n g t h ( v , u ) i f a l t < d i s t [ u ] : d i s t [ u ] : = a l t r e t u r n d i s t [ ]

Figure 8.7: Psuedocode for Dijkstra’s algorithm [1]

Expanding the Game Given that I had about a week to complete this game, I was limited by what all I could do. If I were to expand on the game, I would make better graphics for the user, the aliens, and the hostage. I would also tweak the scaling of the aliens’ difficulty, as I believe it is too easy in the beginning. I believe that adding asteroids would add another fun and realistic complexity to the game. Additionally, I think it would be fun if I made the game a multiplayer game such that multiple people could log on and play together.

What I Learned

While I have never made a video game before, creating The Quest to Save Humanity was a fun experience. I enjoyed making this video game although I’m not sure it is something I see myself doing in the future. I enjoyed the challenge of coming up with a story line and developing game mechanics, but I did not really enjoy the graphics aspect of it. With this experience under by belt, I now understand a little more about my interests in computer science and specifically what video game design is like. I encourage you to challenge yourself to make a video game or, more generally, explore a topic in computer

[1] Thaddeus Abiy et. al. Dijkstra’s Shortest Path Alscience that you don’t know much about! [2] 15-112 Staff. Term Project Assignment. 2019. URL: https://www.cs.cmu.edu/~112-n19/notes/ term-project.html (cited on page 72).

Young people, when informed and empowered, when they realize that what they do truly makes a difference, can indeed change the world. –Jane Goodall

This article is from: