You are on page 1of 95

Introduction to Programming Course

Chapter 1: Fundamentals.

1. First Programs.

Exercise 5: Let the movement continue.

The syntax of a program is quite simple:

1. We write a line (line) that says program, followed by an opening brace: {


2. Here are the commands: one per line
3. And finally, a last key that closes the one we opened before }

Response:

program {
Move(North)
Move(North)
Move(North)
}

Exercise 6: Everywhere.

Response:

program {
Move(South)
Move(East)
Move(East)
}

Exercise 7: The order of things.

As humans, we tend to think in terms of the end result, i.e., we emphasize theobjective of
the program. We care more aboutwhat it does, not how. This denotational way would lead
us to say that it simplymoves the head to the northeast.

That is why there are several ways to solve the same problem: we can create several
programs that do the same thing (thewhat), but do it differently (thehow).

Response:

program {
Move(East)
Move(North)
}
Exercise 8: Yes, this can also be broken.

While we willnever want our program to break, it is definitely something thatis going to
happen to you many times. But it is not a reason to get frustrated, we assure you that it has
happened to everyone at some time (well, also 2, 3, 100, 800 times...).

Response:

program{
Move(South)
}

Exercise 9: Our first balls.

In addition to moving, the head can also place pellets in thecurrent cell. For this purpose,
we have the Put operation, which tells the head to deposit a bead of the given color:

Response:

program{
Put(Red)
}

Exercise 10: More and more balls.

Response:

program {
Put(Red)
Put(Red)
Put(Blue)
Put(Green)
Put(Red)
}

Exercise 11: Put your first balls.

As you may have noticed, these boards are a bit magical, we can put in a cell as many balls
as we want: 2, 4, 12, 50, 1000. There is no limit!

This is a very interesting thing that happens when programming: we can work with
quantities as large as we want.

Response:

program{
Put(Red)
Put(Red)
Put(Red)
Put(Red)
Put(Black)
Put(Black)
Put(Black)
}

Exercise 12: Removing pellets.

In the same way that there is a"put ball", we have a"take ball", which removes exactly one
ball of the given color.

Response:

program {
Move(South)
Remove(Red)
}

Exercise 13: When there are no pellets.

Response:

program{
Remove(Green)
}

Exercise 14: Clear cell.

Response:

program{
Sacar(Blue)
Remove(Green)
Remove(Black)
Remove(Red)
}

2. Practice First Programs.

Exercise 1: Warming up.

The following program places a red ball in the initial position and a black ball to the east.

Response:

program {
Put(Red)
Move(East)
Put(Black)
}

Exercise 2: Combining commands.

Create a program that puts two balls in the initial position, and another two in the next cell
to the East. All the balls must be red.

Response:

program{
Put(Red)
Put(Red)
Move(East)
Put(Red)
Put(Red)
}

Exercise 3: The red row.

Create a program that, starting from an empty board with the head at the origin, draws a line
of four cells to the East. The beads must be red and you must put one bead per cell.

Response:

program{
Put(Red)
Move(East)
Put(Red)
Move(East)
Put(Red)
Move(East)
Put(Red)
}

Exercise 4: A little ladder.

Using the tools you already know, create a program that draws a blue staircase like the one
shown in the image. The header starts at the origin (i.e., at the South-West edge) and should
be at the lower right end of the staircase.

Response:

program{
Put(Blue)
Move(North)
Put(Blue)
Move(North)
Put(Blue)
Move(South)
Move(East)
Put(Blue)
Move(South)
Put(Blue)
Move(East)
Put(Blue)
}

Exercise 5: Portugal.

Since we're not going to get too picky, we're going to ask you for a simplified version of the
flag of Portugal.

Response:

program{
Put(Green)
Move(North)
Put(Green)
Move(East)
Put(Red)
Move(South)
Put(Red)
Move(East)
Put(Red)
Move(North)
Put(Red)
}

Exercise 6: And now a closer one.

Response:

program{
Put(Blue)
Move(East)
Put(Blue)
Move(East)
Put(Blue)
Move(East)
Put(Blue)
Move(East)
Put(Blue)
Move(North)
Move(North)
Put(Blue)
Move(West)
Put(Blue)
Move(West)
Put(Blue)
Move(South)
Put(Red)
Move(North)
Move(West)
Put(Blue)
Move(West)
Put(Blue)
Move(South)
Move(South)
}

Exercise 7: Cleaning the garden.

With the spindle at the origin, create a program that takes care of"pruning" the image board:
remove all the green balls. At the end, the spindle should end where it started.

Response:

program{
Remove(Green)
Move(East)
Remove(Green)
Move(East)
Remove(Green)
Move(North)
Remove(Green)
Move(North)
Remove(Green)
Move(West)
Remove(Green)
Move(West)
Remove(Green)
Move(South)
Remove(Green)
Move(South)
}

Exercise 8: Replacing pellets.

Let's move on to something a little more difficult then. We are going to give you a 2x2
board (that is, with 4 cells) where each cell has a red ball.

Your task is to create a program that replaces all the red balls with green ones.

Response:

program{
Remove(Red)
Put(Green)
Move(East)
Remove(Red)
Put(Green)
Move(North)
Remove(Red)
Put(Green)
Move(West)
Remove(Red)
Put(Green)
Move(South)
}

3. Procedures.

Exercise 1: What is it about?

You should try to find out what the program does.

Response:

 Draw a picture of black balls

Exercise 2: A slightly long program.

Now you have the chance to see the program in action.

Response:

Continue to

Exercise 3: Things by their name.

Response:

Continue to

Exercise 4: Teaching tasks to the computer.

As you saw in the example of the square, you can begin to differentiate between two types
of commands within a program:

 those thatare defined by the language and serve to express basic operations, such
as Move, Put and Take. We will call theseprimitive commands, or
simplyprimitives;
 and thosedefined by us, which are used to express more complex tasks. As the
name of this lesson suggests, these are theprocedures.

When wedefine a procedure we are "teaching" the computer to perform a new task, which
was not originally included in the language.
Pay attention to the syntax of the example to see how we define a procedure and how
weinvoke it in a program.

Response:

Copy, paste and send the code

Exercise 5: Procedures in action.

Complete the code so that in addition to defining the PutBlackandRed procedure, it invokes
it in the program.

Response:

program{
SetBlackAndRed()
}

Exercise 6: Writing procedures.

By now we know that to program we always have to take into account the syntax and that to
define new procedures we also have rules:

 We start with the reserved word procedure;


 We choose a name that describes it and write it with a capital letter followed by
parentheses ( );
 We enclose the actions we want it to do between braces { }.

And if we want to use it, we have to invoke it inside the program by typing its name as it is
and without forgetting the parenthesis ( ) Pay attention to the syntax!

Response:

procedure Put3Greens() {
Put(Green)
Put(Green)
Put(Green)
}
program{
Set3Greens()
}

Exercise 7: Procedure, I summon you!


Create a program that does this by invoking the procedure Put3Greens. Remember that we
have already defined it for you in theLibrary section, so you don't have to write it again!

Response:

program{
Set3Greens()
Move(East)
Set3Greens()
}

Exercise 8: One definition, "infinite" uses.

Create a program that puts 9 red balls in the current cell by invoking the Put3Red procedure
as many times as necessary.

Response:

program{
Set3Red()
Set3Red()
Set3Red()
}

Exercise 9: Procedures inside others.

I defined the Put9Red procedure that, using Put3Red, puts nine red balls in a cell. Once
defined, invoke the new procedure in a program.

Response:

procedure Put9Red(){
Set3Red()
Set3Red()
Set3Red()
}
program{
Set9Red()
}

Exercise 10: Drawing with imagination.

Define the DrawBlackTip procedure and invoke it within a program. The head starts at
the origin and should end at the lower right end of the tip.

Response:

procedure DrawBlackTip(){
Put(Black)
}
program{
DrawBlackTip()
Move(North)
DrawBlackTip()
Move(South)
Move(East)
DrawBlackTip()
}

Exercise 11: From end to end.

Define the DrawTwoPoints procedure and invoke it inside a program. Remember to use
DrawBlackTip.

Response:

procedure DrawTwoPoints() {
DrawBlackTip()
Move(North)
Move(North)
Move(East)
DrawBlackTip()
}
program{
DrawTwoPoints()
}

Exercise 12: Red on the edge.

Response:

procedure RojoAlBorde() {
GoToEdge(North)
GoToEdge(West)
Put(Red)
}
program{
RojoAlBorde()
}

Exercise 13: Decorating the board.

I defined two procedures: the PutWreath procedure that places 3 red balls and 3 green balls
in a cell and the DecorateBoard procedure that uses it and places a garland in each top
corner. Invoke DecorarTablero in the program. Keep in mind that we do not know the
initial position where the head will be located.

Response:
procedure PutWreath(){
Set3Greens()
Set3Red()
}
procedure DecorateBoard(){
GoToEdge(North)
GoToEdge(West)
PutWreath()
GoToEdge(North)
GoToEdge(East)
PutWreath()
}
program{
DecorateBoard()
}

Exercise 14: Colors, colors, colors.

I defined a DrawColorLine procedure thatdraws a multicolored line of four cells to the


East and at the end of it places the head in the initial cell. Invoke the new procedure in a
program.

Response:

procedure Color(){
Put(Red)
Put(Green)
Put(Black)
Put(Blue)
}
procedure DrawColorLine(){
Color()
Move(East)
Color()
Move(East)
Color()
Move(East)
Color()
GoToEdge(West)
}
program{
DrawColorLine()
}

Exercise 15: Colored square.

Define a DrawColorSquare procedure that draws a 4×4 cells square in which each cell has a
ball of each color and invoke it in the program. The head must remain in the initial cell.

Response:

procedure DrawColorSquare(){
DrawColorLine()
Move(North)
DrawColorLine()
Move(North)
DrawColorLine()
Move(North)
DrawColorLine()
GoToEdge(South)
}
program{
DrawColorSquare()
}

4. Simple repetition.

Exercise 1: MoveWest10.

Let's warm up: I defined a MoveWest10 procedure that moves the spindle 10 times to the
West.

Response:

procedure MoveWest10(){
Move(West)
Move(West)
Move(West)
Move(West)
Move(West)
Move(West)
Move(West)
Move(West)
Move(West)
Move(West)
}

Exercise 2: The computer repeats for us.

When it is necessary to repeat a command (such as Move, Place, DrawBlackLine, etc) a


certain number of times, instead of copying and pasting as we have been doing so far, we
can use the repeat statement.

Response:

Copy, paste and send the code

Exercise 3: MoveWest5 using repeat.

I defined a MoveWest5 procedure that moves 5 times to the West.

Response:
procedure MoveWest5(){
repeat(5){
Move(West)
}
}

Exercise 4: Not everything is repetition.

I defined the procedure Put3AlNortheast(), which puts 3 black balls in the first cell
Northeast of the header.

Response:

procedure Put3Anortheast(){
Move(North)
Move(East)
repeat(3){
Put(Black)
}
}

Exercise 5: It is also valid afterwards.

I defined the procedure PutBlueFar(), which places a Blue ball 4 cells to the East

Response:

procedure PutBlueFar(){
repeat(4){
Move(East)
}
Put(Blue)
}

Exercise 6: Repeating several commands.

Response:

procedure DrawBlackLine6(){
repeat(6){
Put(Black)
Move(East)
}
}

Exercise 7: Where is the error?

Response:

procedure RedLine4() {
repeat(4) {
Put(Red)
Move(North)
}
}

Exercise 8: Diagonal with a ball.

I defined a procedure Diagonal4Blue() that draws a diagonal of length 4 to the Northeast,


where each cell has a blue ball. The head should be where shown in the picture.

Response:

procedure Diagonal4Blue(){
repeat(4){
Put(Blue)
Move(North)
Move(East)
}
}

Exercise 9: "Heavy" diagonal.

I defined a procedure DiagonalHeavy4Blue() that instead of putting 1 ball in each cell, now
you have to put 21.

Response:

procedure Pellets(){
repeat(21){
Put(Blue)
}
}
procedure DiagonalHeavy4Blue(){
repeat(4){
Bolitas()
Move(North)
Move(East)
}
}

Exercise 10: The edge case.

Response:

procedure BlackLine4This(){
repeat(3){
Put(Black)
Move(East)
}
Put(Black)
}
Exercise 11: From side to side, we draw a square.

I defined the procedure BlackSquare4() to draw a 4x4 square with black balls. When
starting, the head is in the lower left corner of the square (not necessarily of the board) and
when the program ends, the head should be in the upper right corner of the square. Don't
forget to invoke LineaNegra4Este() which is in the Library section.

Response:

procedure BlackSquare4(){
repeat(3){
BlackLine4East()
repeat(3){
Move(West)
}
Move(North)
}
BlackLine4East()
}

5. Parameters.

Exercise 1: Thinking in subtasks.

I defined the DrawBlackLine3() procedure that, as its name indicates,draws a line by


putting 3 consecutive black balls to the East and leaving the head where it started. Invoke it
in a program.

In the Library you will find the BackToBack procedure. That means you can invoke it
without having to define it!

Response:

procedure DrawBlackLine3(){
repeat(2){
Put(Black)
Move(East)
}
Put(Black)
BackToBack()

}
program{
DrawBlackLine3()
}

Exercise 2: Drawing a square with subtasks.


I defined the DrawBlackSquareSide3() procedure that using DrawBlackLine3() draws a
black square on the board. Invoke it in a program.

Response:

procedure DrawBlackSquareFromSide3(){
repeat(2){
DrawBlackLine3()
Move(North)
}
DrawBlackLine3()
}
program{
DrawBlackSquareSide3()
}

Exercise 3: Color hope.

Define the DrawGreenLine3() procedure to draw a green line and invoke it in the program.

Response:

procedure DrawGreenLine3(){
repeat(2){
Put(Green)
Move(East)
}
Put(Green)
BackToBack()
}
program{
DrawGreenLine3()
}

Exercise 4: The missing ones.

I defined the procedures DrawRedLine3() and DrawBlueLine3() to add the colors Red and
Blue.

Response:

procedure DrawRedLine3(){
repeat(2){
Put(Red)
Move(East)
}
Put(Red)
BackToBack()
}
procedure DrawBlueLine3(){
repeat(2){
Put(Blue)
Move(East)
}
Put(Blue)
BackToBack()
}

Exercise 5: Procedures with holes.

Response:

Copy, paste and send the code

Exercise 6: Filling in the blanks.

Create a program that places three green balls passing as parameter the color Green.

Response:

program{
Set3(Green)
}

Exercise 7: DrawLine3.

I defined the DrawLine3 procedure that receives a color and draws a line of that color.
Don't worry about the programs to invoke it with each of the colors, they are on our side.

Response:

procedure DrawLine3(color){
repeat(2){
Put(color)
Move(East)
}
Put(color)
BackToBack()
}

Exercise 8: DrawSideSquare3.

Invoking DrawLine3, I defined the DrawSideSquare3 procedure that receives a color


and draws a 3x3 square of that color.

Response:

procedure DrawSideSquare3(color){
repeat(2){
DrawLine3(color)
Move(North)
}
DrawLine3(color)
}

Exercise 9: Passing several parameters.

Create a program that invokes the new version of DrawLine3 (you don't have to define it,
just invoke it) and draws a multicolor square, passing as parameters the Color and the
direction.

Response:

program{
DrawLine3(Green, East)
Move(East)
DrawLine3(Red, North)
Move(North)
DrawLine3(Black, West)
Move(West)
DrawLine3(Blue, South)
}

Exercise 10: Law, order and BOOM.

Create any program that invokes DrawLine3, but this time try to invoke it with the
arguments inverted.

Response:

program{
DrawLine3(North, South)
}

Exercise 11: One argument for two parameters.

What do you think will happen if we pass a procedure fewer arguments than it needs?

Create a program that invokes DrawLine3 but passing it only one argument.

Response:

program{
DrawLine3(Green)
}

Exercise 12: Third time's the charm.


To finish this lesson we are going to define a procedure called Triad that receives three
parameters!

Triada receives three colors per parameter and places three balls, side by side to the East, in
the same order in which they are received. The spindle starts at the origin and should end on
the last bead of the triad.

Response:

procedure Triad(colorRed, colorGreen, colorBlue){


Set(colorRed)
Move(East)
Set(colorGreen)
Move(East)
Set(colorBlue)
}

6. Simple Repetition Practice.

Exercise 1: Warming up... Coming back!

Do you dare to define the Diagonal4BlueBack procedure? This procedure shoulddo the
same as Diagonal4Blue, but you have to leave the headin the initial position. Remember
that you can invoke everything in the Library without having to redefine it.

Response:

procedure Diagonal4BlueBack(){
Diagonal4Blue()
repeat(4){
Move(West)
Move(South)
}
}

Exercise 2: A wider diagonal.

The procedure must be called DiagonalBand4.

Response:

procedure DiagonalBand4() {
repeat(3) {
Diagonal4BlueBack()
Move(North)
}
GoToEdge(South)
}
Exercise 3: Let's put... As much as we want.

I defined the procedure PutN(quantity, color).

Response:

procedure PutN(a, b){


repeat(a){
Put(b)
}
}

Exercise 4: Memory Day.

The objective, then, is to define a DiaDeLaMemoria() procedure:

 In the current cell, put 24 blue balls, whichrepresent the day.


 In the cell immediately to the east, put 3 green balls, whichrepresent the month.
 In the cell below, put 1976 black balls,representing the year.

Response:

procedure MemoryDay(){
SetN(24, Blue)
Move(East)
SetN(3, Green)
Move(East)
PonerN(1976, Black)
}

Exercise 5: Write any date.

I defined the procedure Date(day, month, year), which receives thethree


correspondingvalues, and writes the date they represent, like this:

 In the current cell, as many blue balls torepresent the day.


 In the cell immediately to the East, as many Green balls torepresent the month.
 In the cell below, as many Black balls torepresent the year.

Response:

procedure Date(day, month, year){


SetN(day, Blue)
Move(East)
SetN(month, Green)
Move(East)
SetN(year, Black)
}
Exercise 6: Let's move... As much as we want.

I defined a procedure MoveN(quantity, direction) that makes the spindle move the specified
number of times in the specified direction.

Answer:

procedure MoveN(quantity, address){


repeat(quantity){
Move(address)
}
}

Exercise 7: The numbers on the clock.

I defined a DrawClock(radius) procedure that puts the clock numbers as above:around the
current box. The size of the clock is indicated by theradius you receive as a parameter: the
larger the radius, the farther the numbers are from the center.

Response:

procedure DrawClock(radius){
MoveN(radius,North)
SetN(12,Red)
MoveN(radius,East)
MoveN(radius,South)
SetN(3,Red)
MoveN(radius,West)
MoveN(radius,South)
SetN(6,Red)
MoveN(radius,West)
MoveN(radius,North)
SetN(9,Red)
MoveN(radius,East)
}

Exercise 8: A heavy line.

I defined the procedure LineThisPass(weight, color, length). Note that the spindlemust
return to the initial position. For that you will have to invoke MoverN.

Response:

procedure LineThisHeavyLine(weight, color, length){


repeat(length){
SetN(weight, color)
MoveN(1, East)
}
MoveN(longitude, West)
}

Exercise 9: Guard with the guard.

I defined a GuardaDe5() procedure, which makes a"guard" of 5 tiles (like the ones that
decorate the walls). Eachtile consists of 1 green, 5 black and 9 red balls.

Response:

procedure GuardFrom5(){
repeat(4){
SetN(9, Red)
SetN(5, Black)
SetN(1, Green)
Move(East)
}
SetN(1, Green)
SetN(5, Black)
SetN(9, Red)
}

Exercise 10: An L-shaped guard.

I defined a SaveInL() procedure that does a save in L as shown in the figure, butleaving the
head in the initial position.

Answers:

procedure MoveTile(num, dir){


repeat(num){
Move(dir)
SetTile()
}
}
procedure SaveInL(){
SetTile()
MoveTile(2, East)
MoveN(2, West)
MoveTile(2, North)
MoveN(2, South)
}

7. Expressions.

Exercise 1: Many ways of saying the same thing.

With this idea and invoking PonerN, create a program that puts five little black balls, BUT
without writing the number 5.

Response:
program{
SetN(3+2, Black){
}
}

Exercise 2: The sum of the parts.

I defined a procedure PutSum(x, y) that receives two parameters and puts the amount of red
balls that arises from addingxandy.

Response:

procedure PutSum(x, y){


PutN(x + y, Red)
}

Exercise 3: What to do first.

We have the information of how many buses, cars and bicycles attended and from there we
can make a calculation following these rules:

 Eachbus carries40 people;


 Eachcar carries4 people;
 Eachbicycle carries1 person.

Define the procedure ContarGente(micros, autos, bicicletas) that from the number of buses,
cars and bicycles that receives as parameter, makes the necessary counts and reflects the
result with green balls.

Response:

procedure CountPeople(buses, cars, bicycles){


PutN(40 * buses + 4 * cars + 1 * bicycles, Green)
}

Exercise 4: The salmon run.

Response:

Copy, paste and send the code

Exercise 5: Two steps forward, one step back.


I defined the procedure WalkUntrusted(steps) that simulates Carlos' walking: it should
receive the number of steps it should take and take half of them. It always moves to the
east.

Response:

procedure WalkUntrusted(steps){
MoveN(steps div 2, East)
}

Exercise 6: Put to the side.

We want to define a procedure that allows us to put a ballnext to where the head is, leaving
it in the original position.

I defined the procedure PutTo(address, color).

Response:

procedure PutTo(address, color){


Move(address)
Put(color)
Move(opposite(direction))
}

Exercise 7: The returning line.

Using your new knowledge of expressions, modify theLine procedure so that the spindle
stays where it started.

Response:

procedure Line(direction, color, length) {


repeat(length) {
Put(color)
Move(address)
}
MoveN(length, opposite(direction))
}

Exercise 8: Drawing an L.

Find out which of the new functions you have to invoke and define the Ele(address)
procedure. Do not worry about the initial position of the head, we will take care of placing it
in the corresponding place so that the L can be drawn.
Response:

procedure Ele(address){
Line(address, Blue, 3)
Line(next(address), Blue, 3)
}

Exercise 9: Prior to the following.

Response:

Choose option number 4.

Exercise 10: Follow the arrow.

Define the Arrow(direction) procedure that draws a red arrow in the corresponding
direction. The head always starts and should always be in the center, as shown in the
example boards.

Response:

procedure Arrow(direction){
Move(previous(address))
Put(Red)
Move(next(address))
Move(next(address))
Put(Red)
Move(previous(address))

Move(next(address))
Move(previous(address))
Move(address)
Put(Red)
Move(opposite(direction))
}

Exercise 11: Copying balls.

ne task that we surely have to do is to put a lot of balls, and for that we already know that
there is the PonerN procedure that we built several exercises ago. We also know the color of
the balls we have to put: Red, but... how do we know how many to put?

Let's look at some examples:

 If there are 4 green balls, put 4 red balls.


 If there are 2 green balls, put 2 red balls.
 If there are no green balls, no red balls should be placed.
Response:

procedure CopyGreensInRed() {
SetN(nroBolitas(Green), Red)
}

Exercise 12: Taking out small balls.

Continuing with the counting of the beads, it is now your turn to define a procedure to
removeall the beads ofone color.

Let's think about the necessary subtasks:

1. Being able to take out many pellets: already solved with SacarN.
2. Count how many balls to remove: this can be done with nroBolitas.
3. To remove all the balls of one color: you have to combine the 2 previous ones.

I defined TakeAll(color), which receives a color and takes out all the balls of that color (it
should not do anything with the rest of the colors).

Response:

procedure DrawAll(color){
SacarN(nroBolitas(color), color)
}

8. Conditional Alternative.

Exercise 1: Sacar with fear.

Response:

Copy, paste and send the code

Exercise 2: Sacar con miedo, second attempt.

Response:

Copy, paste and send the code

Exercise 3: Eliminating the red ball.

Modify the procedure we gave you so that you get a red ball, onlyif there is one.
Response:

procedure SacarRojoConMiedo() {
if(hayBolitas(Rojo)){
Remove(Red)
}
}

Exercise 4: A rather far-fetched example.

To exercise the latter, we are going to ask you to define a CompleteCell() procedure,if there
is already a black ball, complete the cell by putting a red, a blue and a green one.

Response:

procedure CompleteCell(){
if(hayBolitas(Black)){
Put(Red)
Put(Blue)
Put(Green)
}
}

Exercise 5: And it is only useful to check for pellets?

Create a program that moves to the East onlyif possible. Remember to use
canMove(address).

Response:

program{
if(canMove(East)){
Move(East)
}
}

Exercise 6: A little bit of mathematics.

Another thing you can do inside anif is to compare numbers, as you probably did in
mathematics.

Fortunately, this is written in Gobstones just as in traditional mathematics, with a < for
minor and a > for major. Example: nroBolitas(Verde) > 5 tells us if there are more than 5
green balls.

Knowing this, try to create a program that puts 1black ballonly if there are less than 5black
balls.
Response:

program{
if(nroBolitas(Negro) < 5){
Put(Black)
}
}

Exercise 7: How to say no to...

I defined a procedure EnsureAGreenBall() that ensures that in the current cell there is at
least one green ball. That is: if there are already green pellets, nothing needs to be done, but
if there arenot, one should be added.

Response:

procedure SecureAGreenBall(){
if(not hayBolitas(Verde)){
Put(Green)
}
}

Exercise 8: Two different paths.

Response:

Copy, paste and send the code

Exercise 9: A light board.

Define a TurnOnLightOff() procedure that takes care of turning on the lights that are off or
turning off the lights that are on, as appropriate. Note that in each cell there can only be
green or black balls.

Response:

procedure TurnOnLightOff(){
if(hayBolitas(Negro)){
Remove(Black)
Put(Green)
} else {
Remove(Green)
Put(Black)
}
}

9. Functions.
Exercise 1: And what do you eat this with?

You have to read for several minutes and interpret the code and try to understand it.

Response:

Copy, paste and send the code

Exercise 2: The importance of naming things.

Gobstone functions,

Response:

Copy, paste and send the code

Exercise 3: MoveSomeBalls, version 2.

Modify the first version of MoverSegunBolitas() to use the function nroBolitasTotal()


instead of the long expression.

Response:

procedure MoverSegunBolitas() {
if (nroBolitasTotal() > 10) {
Move(East)
} else {
Move(North)
}
}

Exercise 4: allExcept.

I defined the function allExcept to return the number of balls that arenot of the color that is
passed by parameter.

Response:

function allExcept(color){
return (nroBolitasTotal()-nroBolitas(color))
}

Exercise 5: A function of another type.


I defined the function redIsDominant() that tells us if the number of red ballsis greater than
the sum of the balls of the other colors. In theLibrary is allExcept(color) ready to be
invoked.

Response:

function redIsDominant(){
return (nroBolitas(Rojo)>todasExcepto(Rojo))
}

Exercise 6: At liberty.

There is the && operator that serves just that: it takes two Boolean expressions and returns
True only ifboth are true. If you know anything about logic, this is what is commonly
called aconjunction and is usually represented by the symbol ∧.

I defined the function isFreeCoast() that indicates whether the head can move both East and
West.

Response:

function isFreeSides(){
return(canMove(East) && canMove(West))
}

Exercise 7: Any little ball will do.

Unlike the previous exercise, what we want to know is ifany of them is true, so we have to
use another operator: thedisjunction, which is written | | | and returns true if at leastone of
the two questions is true.

Both && and | | can be used multiple times without the need to use parentheses, as long as
they have Boolean expressions on both sides.

I defined the function isThereAnyBall() that answers the question is there a ball in the
current cell?

Response:

function hayAlgunaBolita(){
return(hayBolitas(Green) || hayBolitas(Blue) || hayBolitas(Red) ||
hayBolitas(Black))
}
Exercise 8: Always on the edge...

We remind you of the logical operators we have seen so far:

 Negation:"flips" a Boolean expression - example: not hayBolitas(Rojo).


 Conjunction: determines ifboth conditions are met - example: canMove(North)
&& canMove(South).
 Disjunction: determines ifany of the conditions are met - example: isSmart() ||
hasGoodWave().

With the help of that little table, I defined the function I'mOnAnEdge() that determines if
the head is standing on an edge.

Response:

function estoyEnUnBorde(){
return(not canMove(North) || not canMove(South) || not canMove(East) || not
canMove(West))
}

Exercise 9: The ideal partners.

Let's now look at functions thatdo things before returning a result. To exemplify this, we
will want you to define a function that tells us if there is a ball of a specific color, butin the
cell next to it.

I defined the function hayBolitasAl(direction, color) that reports if there are any beads of
the specified color in the neighboring cell at the given direction.

Response:

function hayBolitasAl(address,color){
Move(address)
return(hayBolitas(color))
}

Exercise 10: The ideal can also be broken.

Let's try it: let's test the hayBolitasAl function of the previous exercise with cases where the
head cannot move. Press Submit and see the result.

Response:

Press Send
Exercise 11: Are there balls far away?

I defined the function hayBolitasLejosAl(direction, color, distance). The idea of"moving the
head many times" was solved several lessons ago with the procedureMoverN. You could use
it.

Response:

function hayBolitasLejosAl(direction,color,distance) {
MoveN(distance,direction)
return(hayBolitas(color))
}

Exercise 12: I am surrounded by old balls.

Using hayBolitasAl, I defined the function estoyRodeadoDe(color) that indicates if the head
is surrounded by balls of that color.

We say that the head is "surrounded" if there are balls of that color in the four directions:
North, East, South and West.

Response:

function I'mSurroundedFrom(color) {
return (there areBolitasAl(North, color) && there areBolitasAl(East, color)
&& there areBolitasAl(South, color) && there areBolitasAl(West, color))
}

Exercise 13: No limits.

To close, let's define the function hayLimite(), which determines if there is some kind of
limit when moving the spindle.

The limit may be due to one of two factors: becauseI am on an edge and therefore cannot
move in any direction, or becauseI am surrounded by red balls that cut me off. Ifeither of
these two conditions occurs, it means that there is a limit.

Using I'mOnAnEdge and I'mSurroundedFrom, I defined there isLimit.

Response:

function hayLimite(){
return (I'mOnAnEdge() ||I'mSurroundedBy(Red))
}
Chapter 2: Imperative Programming.

Functions and data types.

Exercise 2: Functions, declaration.

Let's see if you understand: I wrote aJavaScript function half, which takes a number and
returns its half. Note that the division operator inJavaScript is /.

Response:

function half(number){
return(1/2*number)
}

Exercise 3: Functions, use.

Let's see if you understand; I wrote the following functions:

 above:takes a number and returns that number minus one.


 triple: returns the triple of a number.
 previousDelTriple: which combines the two previous functions: it multiplies
a number by 3 and subtracts 1 from it.
Response:

function previous(number){
return(number - 1)
}
function triple(number){
return(number * 3)
}
previous functionDelTriple(number){
return(previous(triple(number))))
}

Exercise 4: Testing functions.

Let's see if you understand, try the following expressions in the console:

 4 + 5
 Math.round(4.5)
 functionMysterious(1, 2, 3) (we already declared it for you and you can use it)

Response:

Try the following expressions in the console

Exercise 5: Doing the math.

Try the following expressions in the console:

 Math.round(4.4)
 Math.round(4.6)
 Math.max(4, 7)
 Math.min(4, 7)

Response:

Try the above expressions in the console

Exercise 6: Placing stops.

Response:

function extract(balance, amount) {


return Math.max((balance-amount),0);
}

Exercise 7: Books of good memory.


Now it's your turn! Dani also says that someone likes to read when the number of books
he/she remembers reading is more than 20.

Response:

function leGustaLeer(unNumero){
return(aNumber > 20)
}

Exercise 8: Booleans.

Let's see if you understand; I wrote the following functions:

 ThisEntre, take three numbers and tell if the first is greater than the second and less
than the third.
 thisOutOfRange: to take three numbers and say whether the first is less than the
second or greater than the third.

Response:

function thisEntre(num1, num2, num3){


return(num1 > num2 && num1 < num3)
}
function thisOutOfRange(num1, num2, num3){
return(num1 > num2 && num1 > num3)
}

Exercise 9: Words, only words.

Let's see if it is clear: I wrote the function isWeekEnd that takes a string representing the
name of a day of the week, and tells us if it is "Saturday" or "Sunday".

Response:

function isWeekEnd(day){
return(day === "Saturday" || day === "Sunday")
}

Exercise 10: Operating on strings.

Let's see if it's clear: I wrote a function lengthFirstNameComplete, which takes a first name
and a last name, and returns their total length, counting an extra space to separate the two.

Response:

function lengthFullName(firstName, lastName){


return length((firstname)+(lastname)+(1));
}
Exercise 11: SCREAM!

I wrote the shout function. We leave you to use the convertToCase function, which, uhm....
well... basically converts to uppercase a string .

Response:

function shout(word){
return("¡" + convertToMayuscula(word) + "!")
}

Exercise 12: What if...?

No introduction to theJavaScript language would be complete without showing at least one


control structure we already know: the conditional alternative.

Let's see if you understand: I wrote a max function, which works like Math.max (no good to
use it!) and returns the maximum between two numbers. For example, the maximum
between 4 and 5 is 5, and the maximum between 10 and 4 is 10.

Response:

function maximo(numero1, numero2) {


if (number1 >= number2) {
return number1;
} else {
return numero2;
}
}

Exercise 13: What sign are you?

We need a sign function, that given a number returns:

 1 if the number is positive.


 0 if the number is zero.
 -1 if the number is negative.

I wrote the sign function. You may need more than one if.

Response:

function sign (number){


if(number > 0) return 1
if(number === 0) return 0
if(number < 0) return - 1
}
Exercise 14: The return of the Boolean.

I wrote the function isLuckyNumber that given a number tells if it meets the above logic.
It's not worth using if!

Response:

function isLuckyNumber(number) {
return (number)>0 && (number)<100 && (number!=15);
}

Exercise 15: Awards.

The jury of a tournament asked us to develop a function medalSecondPlace that returns the
medal that corresponds to the first places, according to the following logic:

 first place: "gold".


 second place: "silver".
 third place: "bronze".
 other positions: you are entitled to "nothing".

Response:

function medallaSegunPuesto(lugar){
if(place === 1){
return("gold")
} else if(place === 2) {
return("silver")
} else if(place === 3) {
return("bronze")
} else {
return("nothing")
}
}

Exercise 16: Data types.

As we have just seen, inJavaScript there are numbers, booleans and strings:

In addition, there are operations that work for alldata types, for example:

 ===: tells us if two things are equal.


 !==: tells us if two things are different.

Try the following things on the console:

 5 + 6 (ok, the numbers can be added).


 5 === 6 (ok, all things can be compared).
 8 > 6 (ok, the numbers can be ordered).
 !true (ok, booleans can benegated).
 false / true (no good, booleans cannot be split!).

Response:

Test on the console

Exercise 17: Data of all types.

Before we finish one last challenge: What is the value of the following expressions? Check
all the right ones!

Response:

4 + 4 equals 8

"4" + "4" is equal to "44".

"on" + "ce" stands for "once".

true && false is false

5 >= 6 is false

! true is false

2. Practice Functions and Data Types.

Exercise 1: Buying Hardware.

I wrote a quantCuesta function that takes the number of inches of the monitor and the
amount of memory, and calculates the estimated cost of our computer.

Response:

function how muchCuesta(monitor, memory){


return((monitor * 60) + (memory * 200) + 1000);
}

Exercise 2: Is it convenient for me?


Now that we know how much a computer costs, we want to know if a computeris right for
me. This occurs when:

 It is less than $6000.


 It has at least a 32-inch monitor.
 It has at least 8GB of memory.

I wrote the function meConviene, which again takes the number of inches and amount of
memory and tells us if it is convenient to buy it.

Response:

function meConviene(inch,memory){
return (how muchCuesta(inch,memory) < 6000 && inch >= 32 && memory >= 8);
}

Exercise 3: Triangles.

Time to do some geometry! We want to know a few things about a triangle:

 perimeterTriangle: given the three sides of a triangle, we want to know how long its
perimeter is.
 areaTriangle: given the base and height of a triangle, we want to know its area.

Develop the functions perimeterTriangle and areaTriangle.

Response:

function perimeterTriangle(side1, side2, side3){


return (side1 + side2 + side3)
}
function areaTriangle(side1, side3){
return (side1 * side3 / 2)
}

Exercise 4: Squares.

And now it's the turn of the squares; we want to know

 perimeterSquare: given a side, we want to know how long its perimeter is.
 areaSquare: given a side, we want to know its area.

Develop the functions perimeterSquare and areaSquare.

Response:

function perimeterSquare(side) {
return (side * 4)
}
function areaSquare(side) {
return (side * side)
}

Exercise 5: Are you in tune?

Develop a tuned function, which receives the frequency (a number) fromthe control panel,
and tells if this frequency is equal to 440Hz.

Response:

function thisFrequency(frequency){
return (frequency === 440)
}

Exercise 6: Is it close?

Now we want to know if the centerc of the piano isclose to being in tune. This occurs when
it is between 437Hz and 443Hz, but it is NOT exactly 440Hz.

I wrote the function thisClose.

Response:

function thisClose(frequency){
return (437 <= frequency && frequency <= 443 && frequency !== 440)
}

Exercise 7: Posters.

I wrote the function writeLittlePost, which takes a title, a first name and a last name and
forms a single string.

Response:

function escribirCartelito(titulo, nombre, apellido){


return(title + " " + first name + " " + last name)
}

Exercise 8: More Posters.

Response:

function escribirCartelito(titulo, nombre, apellido, bool){


return (title + " " + (!bool?firstname+""+lastname:lastname))
}
Exercise 9: Optimal posters.

Now that we can write our large and small nameplates, we want anew function that will
give us the optimal size nameplate:

 If first and last name have, in total, more than 15 letters, we want a short sign;
 Otherwise, we want a long sign.

I defined the function writeBillboardOptimal that takes a title, a first name and a last name,
and using writeBillboard generates a short or long billboard, according to the rules above.

Response:

function escribirCartelitoOptimo(titulo, nombre, apellido){


return writeLetter(title, name, first name, last name,(length(first name +
last name) >= 15))
}

Exercise 10: Face or mint.

I wrote a function decisionConMoneda, which takes three parameters and returns the
second one if the first one is "cara", or the third one, if "ceca".

Response:

function decisionConMoneda(moneda, pizzas, empanadas){


if(coin === "heads"){
return pizzas;
}else{
return empanadas;
}
}

Exercise 11: Envido!

We want to know the value of the trick cards when playingenvido. We know that:

 All cards from 1 to 7, inclusive, are worth their numbering.


 Cards from 10 to 12, inclusive, are worth 0.
 You don't play with 8s or 9s.

I wrote a function valueSend, which takes a letter number and returns its send value.

Response:

function valueSent(letter){
if(letter >= 1 && letter <= 7)
{return letter}
if(letter >= 10 && letter <= 12)
{return 0}
}

Exercise 12: I want a replay.

Well, uhm, no, stop, first we want to calculate how many envido points a player adds up to.
We know that:

 If the two cards are of the same suit, the value of the send is the sum of their send
values plus 20.
 Otherwise, the value of the shipment is the highest shipment value between them.

Using the function sendValue (which we already wrote for you), develop the function
totalSendPoints that takes the values and suits of two cards and tells how much send they
add up to in total.

Response:

function pointsSentTotals(n1, p1, p1, n2, p2){


if(p1 === p2){
return (valueSent(n1) + valueSent(n2) + 20)
}else{
return Math.max(n1, n2)
}
}

Exercise 13: I want voucher four.

When playing truco, the opposing teams may alternatively raise the bet. For example, if a
player singstruco, another player can singretruco. Obviously, the stakes are getting higher
and higher:

Canto Points at stake


trick 2
retruco 3
is worth
4
four

I wrote the function valueCantoTruco, which takes the song and returns how many points it
is worth.

Response:
function valueCantoTruco(canto){
if(canto === "truco"){
return(2)
}
if(canto === "retruco"){
return(3)
}
if(canto === "vale cuatro"){
return(4)
}
}

Variables and Procedures.

Exercise 1: What about the board?

Response:

functionMysterious(2, 1)

Exercise 2: Screen printing.

Response:

Try functionEgocentrica() in the console.

Exercise 3: Martin Fierro.

Let's see if it becomes clear, I wrote a versosMartinFierro function that prints the first
verses of Martin Fierro on the screen:

Here I start to sing


To the beat of the vigüela;
That the man who unveils it
An extraordinary grief

This function must return 0

Response:

function versosMartinFierro() {
print("Here I start singing");
print("To the beat of the beam;");
print("Let the man who unveils it");
print("An extraordinary sorrow");
return 0
}
Exercise 4: What about the procedures?

When we want to reuse code, we could declare:

 functions, which always return something and have no effect.


 procedures, which do not return anything, and produce effects.

Send this new version of versosMartinFierro.

Response:

function versosMartinFierro() {
print("Here I start singing");
print("To the beat of the beam;");
print("Let the man who unveils it");
print("An extraordinary sorrow");
}

Exercise 5: What about the program?

InJavaScript everything we write outside of afunction will implicitly be that entry point.
For example, if we want a program that prints the classic "Hello, world!" on the screen, we
can write it like this:

print("Hello World!");

Response:

print("Rolling dice");
print("The first roll hit " + rollDead());
print("The second roll hit " + rollDead());
print("The third roll hit " + rollDead());

Exercise 6: Coercions.

Let's see if it's clear, I wrote a function elephantsEquilibrants, which takes a number of
elephants andreturns a rhyme from a well-known song "3 elephants were swinging".

Response:

function elephantsEquilibrants(number){
return(number + " " + "elephants were swinging")
}

Exercise 7: The circle of life.


Considering the number pi equal to 3.14159265358979 (not infinite but precise enough for
our calculations):

I defined the functions perimeterCircle and areaCircle that receive the radius of a circle and
from it return its perimeter and area.

Response:

function perimeterCircle(radius){
return(3.14159265358979 * 2 * radius)
}
function areaCircle(radius) {
return(3.14159265358979 * radius * radius)
}

Exercise 8: I think it is easier this way.

let pi = 3.14159265358979;

Change the places where 3.14159265358979 appears for the variable pi in the functions we
have defined.

Response:

let pi = 3.14159265358979;

function perimeterCircle(radius){
return(pi * 2 * radius)
}
function areaCircle(radius) {
return(pi * radius * radius)
}

Exercise 9: This is worthless.

Now that you understand how variables areassigned, here is some food for thought: what
happens if I try touse a variable to which I have never assigned a value?

Response:

Copy, paste and test in the console

Exercise 10: Global variables.


Variables declared within a function, known aslocal variables, present no great mystery.
However, particular care must be taken: they can only be used from within the function in
question.

However, variables declared directly in the program, known asglobal variables, can be used
from any function.

Response:

let loadMaximumInKilograms = 300


function elevatorOverloaded(people){
return(persons * weightAveragePersonWeightInKilograms) >
loadMaximumInKilograms
}

Exercise 11: Becoming rich.

I wrote an incrementFortuna procedure that doubles the value of the global variable
pesosInMyWallet. Don't declare the variable, we already did it for you (with a secret
amount of money).

Response:

function incrementFortuna(){
pesosInMyWallet = pesosInMyWallet * 2
}

Exercise 12: How much is this worth?

We saw that a variable can only have one value, so each time we assign a new one, we lose
the previous one.

Response:

20

4. Boolean logic.

Exercise 1: Let the last one turn off the light.

Let's start with something simple, do you remember the operator! It is called negation, not
or logical complement and is used to negate a Boolean value.
If I have the boolean represented by hasHungry, the complement will be !hasHungry.

I defined the useClose procedure so that we can open and close the zipper of a backpack.

Response:

let backpackOpen = true;


function useClose() {
backpackOpen = !backpackOpen
}

Exercise 2: Denying does not cost anything.

Now it's your turn! I defined isOlderOfAge, which receives an age, and then is
YoungerOfAge from it.

Response:

function isOlderOf(age){
return(age >= 18)
}
function isMinorOfAge(age){
return(!isOldestOfAge(age))
}

Exercise 3: The peripatetics.

I defined an esPeripatetic function that takes a person's profession, nationality and the
number of kilometers he/she walks per day. Someone is peripatetic when he is a Greek
philosopher and likes to walk (he walks more than 2 kilometers per day).

Response:

function esPeripatetico(teacher, nationality, kms){


return(professor === "philosopher" && nationality === "Greek" && kms > 2)
}

Exercise 4: The truth behind the conjunction.

Response:

Test on console:

consumesLittleEnergy(24, 5)

consumesLittleEnergy(24, 0)
consumesLittleEnergy(21, 7)

consumesLittleEnergy(18, 1)

Exercise 5: Let's play T.E.G.!

Response:

Test on the console:

win(true, 25)

win(false, 30)

win(false, 20)

win(true, 31)

Exercise 6: And now... who can help us?

We know the bank is closed when:

 It is a holiday, or
 It's the weekend, or
 We are not during banking hours.

I defined the functions isWeekEnd and isClosed.

Response:

let esFeriado = true;


function isWeekEnd(day){
return(day === "saturday" || day === "sunday")
}
function isClosed(isFeriado, day, time){
return(enFeriado || !dentroDeHorarioBancario(horario) ||
enFinDeSemana(dia))
}

Exercise 7: Good morning.

In the Buendía family it happens that:

 Arcadio is the son of José Arcadio and Pilar Ternera.


 Aureliano José is the son of Colonel Aureliano and Pilar Ternera.
 Aureliano Segundo and Remedios are the children of Arcadio and Sofia De La
Piedad.

To start analyzing this family, we have already defined the functions motherFrom and
fatherFrom.

Now it is up to you to define the function areMediaBrothers. Remember that half-siblings


can share mother or father but not both because.... in that case they would be siblings!

Response:

function haveTheSameMother(child1, child2){


let mother1 = motherFrom(child1);
let mother2 = motherFrom(child2);
return mother1 === mother2;
}
function haveSameParent(child1, child2){
let parent1 = parentFrom(child1);
let parent2 = parentFrom(child2);
return parent1 === parent2;
}
function areMiddleSiblings(child1, child2){
return (haveSameMother(child1, child2) !== haveSameFather(child1, child2));
}

Exercise 8: The truth is that there is no truth.

Try your function areMeansSiblings with the following values and check if it behaves like
the table:

Response:

sonMediosHermanos(arcadio, aurelianoJose)
sonMediosHermanos(aurelianoSegundo, remedios)
sonMediosHermanos(aurelianoJose, remedios)

Exercise 9: Hello! My name is Xor.

Unlike and, or and not, xor is not usually defined in languages. However, now that you
know how it works, if you ever need it, you can define it by hand.

Let's see if you understand: I defined the generic function xor, which takes two booleans
and returns the corresponding truth value.

Response:

function xor(a, b){


return(a !== b)
}

Exercise 10: Precedence.

When a mathematical expression has several operators, we know that multiplications and
divisions will be performed before additions and subtractions:

5 * 3 + 8 / 4 - 3 = 14

As in mathematics, when using logical operators, expressions are evaluated in a certain


order calledprecedence.

Response:

Test it in the console with the values:

payWithCard(true, "credit", 320)

payWithCard(false, "credit", 80)

payWithCard(true, "debit", 215)

payWithCard(true, "debit", 32)

Exercise 11: An unprecedented exercise.

I wrote the function canRetire that receives the age and gender of a person, in addition to
the years of pension contributions he/she has.

The minimum age for women is 60 years old, while for men it is 65 years old. In both cases,
at least 30 years of contributions are required.

Try to solve it in a single function! Then let's see what it would look like if we delegate.

Response:

function canRetire(age, gender, contribution){


return((gender === "F" && age >= 60) || (gender === "M" && age >= 65)) &&
contribution >= 30
}

Exercise 12: Can I go upstairs?


The requirements to ride the attraction are:

 Reach the minimum height of 1.5m (or 1.2m if accompanied by an adult).


 Not having any heart condition.

I defined the 3-parameter function canClimb that receives a person's height in meters,
whether he/she is accompanied and whether he/she has a heart condition.

Response:

function canRise(height, accompanied, condition){


return((height >= 1.5) || (height >= 1.2 && accompanied)) && !affeccion
}

5. Lists.

Exercise 1: Favorite series.

To represent a set of strings, we place all the strings we are interested in between square
brackets ([ and ]) separated by commas. Easy, isn't it?

Response:

Try the following queries in the console:

seriesFavoritesFromAna

seriesFavoritesDeHector

["hello", "world!"]

["hello", "hello"]

Exercise 2: And this is a list.

What we have just seen is how to easily model sets of things. Using[],JavaScript provides
a simple way to group these elements into lists.

Is there a maximum number of elements? No, there is no limit! Lists can have any number
of elements.
Not only that, but order is important. For example, ["hello", "world"] is not the same as
["world", "hello"]: both have the same elements, but in different positions.

Response:

Try the following queries in the console:

equalLists(["hello", "world"], ["world", "hello"])

equalLists(["hello", "world"], ["hello", "world"])

equalLists(["hello", "world"], ["hello", "all", "the", "world"])

equalLists(["hello"], ["hello", "world"])

["hello", "world"] === ["world", "hello"]

people

["mara", "julian"] === people

people === people

Exercise 3: Games of chance.

We can also represent sets of numbers or Booleans in the same way: writing them in square
brackets and separated by commas. We can have lists of numbers, of strings, of booleans,
and so on. We could even have lists of lists!

Response:

Let's see if this is clear. Try the following queries in the console:

numerosDeLoteria

salioCara

[[1, 2, 3], [4, 5, 6]]

Exercise 4: Empty lists.


Great, it looks like a list can contain any type of item! We can have lists of Booleans, of
numbers, of strings, of lists...

Not only that, but they can contain any number of elements: one, two, fifteen, hundreds.

Can we then have empty lists, i.e., with no elements? Of course!

let unaListaVacia = []

Response:

Try typing in the console aVacancyList

Exercise 5: How many elements do you have?

By now we know what things we can represent with lists, and how to do it. But what can we
do with them?

Let's start with the easy part: knowing how many elements are in the list. We can do this by
using the length function, similar to what we did with strings.

Response:

Perform the following queries in the console:

length([])

length(lotteryNumber)

length([4, 3])

Exercise 6: Adding flavor.

Lists are very useful for containing multiple items. But there is more! We can also add
elements to it at any time, using the add function, which receives two parameters: the list
and the element.

As we can see, adding adds an element to the list, which increases its size. But where in the
list do you add it? At the beginning? In the end? In the middle?
Find out for yourself: inspect in the console which items contain belongings, add a
"crossbow" and inspect belongings again.

There is also a remover procedure, which only receives the list by parameter. Check the
console to see what it does.

Response:

Test on the console

add(belongings, "magic amulet")

Exercise 7: Transfer.

Declare a move procedure, which takes two lists, removes the last element from the first
one and adds it to the second one.

Response:

function move(aList, anotherList){


add(otherList, remove(otherList))
}

Exercise 8: And where is it?

And what happens if you pass an element that it does not have as a parameter to position?
See for yourself!

Response:

Copy and paste into the console

position(workdays, "osvaldo")

Exercise 9: Contains.

I wrote the function contains that tells us if a list contains a certain element.

If you have been paying attention to the query examples, you will have noticed that lists can
also have duplicate elements: [1, 2, 1], ["hello", "hello"], etc.
Therefore, position actually returns the position of thefirst occurrence of the element in the
list.

Response:

function contains(array, search){


return(position(array, search) >- 1)
}

Exercise 10: Nth element.

Just as there is a function to find out in which position an element is, it can also happen that
we want to know the opposite: which element is in a certain position.

To find out we can use theindexing operator, writing after the collection and between
square brackets [] the position we want to find out.

Response:

let list =[]

list[0]

Exercise 11: More awards.

If you ask for an element in a position equal or greater than the size of the list, you will get
undefined. It doesn't seem terrible, but the problem is that with undefined you can't do
anything really useful.

So the warning is: don't over-index!

With that in mind, here's a challenge: I rewrote the function medalSecondPost, but this time
using at most a single if. You may find the lists useful here .

We remind you what the function does: it has to return the medal that corresponds to the
first places in a competition.

Response:

let medal = ["nil", "gold", "silver", "bronze"]

function medallaSegunPuesto(puesto){
if(post <= 3){
return(medal[position])
} else {
return(medal[0])
}
}

Exercise 12: Don't forget to say hello.

Let's get to know a way to go through the elements of a list with a new friend: the for loop.

Response:

function greet(people){
for(let person1 of persons){
print("hello" + " " + person1);
}
}

6. Records.

Exercise 1: The first records.

Response:

Copy and paste the code into the console

statueOfFreedom
christRedentor
EiffelTower
tajMahal
colosseum

Exercise 2: Your own monument.

It's your monument moment! Save in the variables torreAzadi and


monumentoNacionalALaBandera records of these monuments, originating from the cities
of Tehran,Iran and Rosario,Argentina respectively. Do you dare to investigate in which
year they were finished to complete that field?

Response:

let AzadiTower = {name: "Azadi Tower", location: "Tehran, Iran",


yearOfConstruction: 1971}
let monumentoNacionalALaBandera = {name: "Monumento Nacional A La Bandera",
location: "Rosario, Argentina", yearOfConstruction: 1957 }
Exercise 3: Accessing the field.

We declare the planets mercury, mars and saturn as records with the following information:
name, temperatureAverage and if it has Rings. Try them on the console!

Response:

We declare the planets mercury, mars and saturn as records!

Exercise 4: Glide temperature.

Develop a function temperatureFromPlanet that receives by parameter a planet record and


returns a string indicating its name and its average temperature. It has to work for any
planet!

Response:

function planetTemperature(planet){
return(planet.name + " has an average temperature of " +
planet.averageTemperature + " degrees")
}

Exercise 5: Moving files.

Develop the moveFile procedure, which receives a record and a new path and modifies the
file with the new path.

Response:

function moveFile(record, pathNew){


let readme = record.path = newPath
}

Exercise 6: Records of two millennia.

In the previous exercise we modified the registry path, but we did not use its creation date.
Let's use it! We want to know if a file is from the last millennium, which happens when its
year is before 2000.

Develop the function esDelMilenioPasado, which receives a file and returns a boolean.

Response:
function esDelMilenioPasado(file){
return(year(file.creation) < 2000)
}

Exercise 7: Complex desserts.

Create a function moreDifficultToBake, which receives two dessert records for parameters
and returns the one that has more ingredients of the two.

Response:

function moreDifficultToCook(dessert1, dessert2){


if(length(dessert1.ingredients) < length(dessert2.ingredients)){
return dessert2;
}
if(length(dessert1.ingredients) >= length(dessert2.ingredients)){
return dessert1;
}
}

Exercise 8: Registration lists.

Just as we work with lists of numbers, Booleans, strings or more lists, we can also list
records. You can do everything you did before, such as remove, know its length or ask for
the element of a certain position using the square brackets [ ].

Try in the console the lists dessertsFavorites and monumentsOfAmerica. There is a dessert
that we didn't show before, can you tell what it is just by reading its ingredients?

Response:

Test on console:

dessertsFavorites

monumentosDeAmerica

Exercise 9: 60 sweet minutes.

Develop the procedure addAPostresRapidos, which receives a list with quick desserts and
one dessert per parameter. If the cooking time is one hour or less, the record is added to the
list.

Response:
function addAPostresresRapidos(list, dessert){
if(dessert.cookingTime <= 60){
add(list, dessert)
}
}

Exercise 10: There is a record in my register.

Find out what the ingredients field of the dessert field of the menuChildren record returns.
It's one record inside the other!

Response:

Test on console

menuChildren.dessert.ingredients

Exercise 11: Sugar.

I defined a procedure sweetenMenu, which receives a menu record and adds sugar to the
ingredients of your dessert. If it already has sugar in it, it doesn't matter.... add more!

Response:

function sweetenMenu(menu){
add(menu.dessert.ingredients, "sugar")
return menu.dessert
}

7. Tours.

Exercise 1: Semiannual earnings.

Is there a problem with the gainSemester function we wrote above? Will it work with
quarterly balance sheets? What about quarterly quarters?

Try it on the console!

Response:

Test on the console:

profitSemester
Exercise 2: What about the rest of the profits?

What we would like is to be able to add up the profits of all the balances in a list, no matter
how many there actually are; we want a function profitTotal, which can add up balances for
any period of months: semesters, quarters, quarters, etc. How difficult!

Response:

profitTotal([
{ month: "January", profit: 2 },
{ month: "February", profit: 3 }
])

Exercise 3: All gains, the gain.

Response:

function gananciaTotal4(balancesOfAperiod){
let summation = 0
summation = summation + balancesOfAperiod[0].gain
summation = summation + balancesOfAperiod[1].gain
summation = summation + balancesOfAperiod[2].gain
summation = summation + balancesOfAperiod[3].gain
return sum
}

Exercise 4: An old friend visits us.

What we have to do, then, is to repeat the accumulation operation several times, once for
each item in the list. Let's say hello (again) to the for...of!

As you can see, the for...of allows us to visit and do something with each element of a list;
in this case, we will be visiting each balance of balancesOfAPeriod.

Response:

profitTotal([
{ month: "March", profit: 8 },
{ month: "August", profit: 10 }
])

Exercise 5: Clear accounts.


Ana has new requirements! Now he asked us the following: "I want to know how many
balances were positive, that is, those in which the profit was greater than zero".

Complete the PositiveBalanceAmount function. If you pay attention, you will notice that it
has a similar structure to the previous problem.

Response:

function amountOfBalancesPositive(balancesOfAperiod){
let quantity = 0
for(let balance of balancesOfAperiod){
quantity = quantity + ((balance.profit) > 0)
}
return quantity;
}

Exercise 6: The average gain.

Let's move on to Ana's next request. We can already calculate a sum of profits and also
create counters, now we are going to calculate averages.

Ana would like to know given any set of balances what is its average profit.

Response:

function gananciaPrommedio(gananciaTotal){
let summation = 0
for(let balance of gananciaTotal){
summation = (summation + balance.gain)
}
return sum / length (TotalGain)
}

Exercise 7: Who wins, who loses.

Seeing that we can do everything she asks us to do, Ana wants to know the average profit of
the positive balances.

I defined the functions:

 Positive profit, which is the sum of the profits of the positive balances.
 averagePositiveProfit invoking PositiveProfit and numberOfPositiveBalances.

Response:

function positiveGain(balancesOfAperiod){
let summation = 0
for(let balance of balancesOfAperiod){
if(balance.gain > 0){
summation = summation + (balance.gain)
}
}
return sum
}

function averagePositiveProfits(balancesOfAperiod){
return profitPositive(balancesOfAperiod) /
amountOfBalancesPositive(balancesOfAperiod)
}

Exercise 8: I am the map, I am the map.

Unfortunately, it is not possible to use the average function with our list of records. What
we need is a list that has only the earnings of each balance. To do this we must transform,
ormap, each element of the list.

Complete the earnings function that takes a list of balances and returns a list of only the
earnings of each one.

Response:

function earnings(balancesOfAperiod){
let profits = []
for(let balance of balancesOfAperiod){
add(profit, balance.profit)
}
return earnings
}

Exercise 9: To filter, to filter everything in its place.

With programming you can do anything, or almost anything. We have already made a
function to know the number of positive balances (numberOfPositiveBalances), now let's
see how we can know which are those balances.

Complete the function balancesPositive that takes the balances of a period and returns a list
of those whose profit was greater than zero.

Response:

function balancesPositive(balancesOfAperiod){
let balances = []
for(let balance of balancesOfAperiod){
if(balance.gain > 0){
add(balances, balance)
}
}
return balances
}

Exercise 10: A more positive average.

Now that we have the profit function and positive balances, we can use the generic average
function to find out the average profit of the positive balances.

Define the function profitsFromBalancesPositive and then use it together with average to
define averageFromBalancesPositive.

Response:

function gainsFromBalancesPositive(balancesOfAperiod){
return earnings(balancesPositive(balancesOfAperiod))
}
function averagePositiveBalances(balancesOfAperiod){
return average(earningsPositiveBalances(balancesOfAperiod))
}

Exercise 11: This is the maximum.

We are going to learn about a new function, maximo, which allows us to know what is the
largest value in a list of numbers.

Using this new function, I defined the maxProfit function that tells us what is the highest
profit among the balances of a period of time.

Response:

function maxMaximumProfit(balancesOfAperiod){
return maximum(earnings(balancesOfAperiod))
}

Exercise 12: At least.

We guess you guessed the name. If not, it is minimal.

Define the minimumPositiveProfit function that tells us what is the lowest profit of all
positive balances.

Response:

function minimumPositiveProfit(balancesOfAperiod){
return minimo(gananciasDeBalancesPositivos(balancesDeUnPeriodo));
}

Exercise 13: The best months of the year.

For that we are going to do the following functions:

 months, which given a list of records returns a list of months;


 lucky, which filters out those records that had a profit greater than $1000;
 LuckyMonths, returns those months that were lucky.

I defined the functions months, lucky, luckyMonths.

Response:

Chapter 2: Imperative Programming.

Functions and data types.

Exercise 2: Functions, declaration.

Let's see if you understand: I wrote aJavaScript function half, which takes a number and
returns its half. Note that the division operator inJavaScript is /.

Response:

function half(number){
return(1/2*number)
}

Exercise 3: Functions, use.

Let's see if you understand; I wrote the following functions:

 above:takes a number and returns that number minus one.


 triple: returns the triple of a number.
 previousDelTriple: which combines the two previous functions: it multiplies
a number by 3 and subtracts 1 from it.

Response:
function previous(number){
return(number - 1)
}
function triple(number){
return(number * 3)
}
previous functionDelTriple(number){
return(previous(triple(number))))
}

Exercise 4: Testing functions.

Let's see if you understand, try the following expressions in the console:

 4 + 5
 Math.round(4.5)
 functionMysterious(1, 2, 3) (we already declared it for you and you can use it)

Response:

Try the following expressions in the console

Exercise 5: Doing the math.

Try the following expressions in the console:

 Math.round(4.4)
 Math.round(4.6)
 Math.max(4, 7)
 Math.min(4, 7)

Response:

Try the above expressions in the console

Exercise 6: Placing stops.

Response:

function extract(balance, amount) {


return Math.max((balance-amount),0);
}

Exercise 7: Books of good memory.

Now it's your turn! Dani also says that someone likes to read when the number of books
he/she remembers reading is more than 20.
Response:

function leGustaLeer(unNumero){
return(aNumber > 20)
}

Exercise 8: Booleans.

Let's see if you understand; I wrote the following functions:

 ThisEntre, take three numbers and tell if the first is greater than the second and less
than the third.
 thisOutOfRange: to take three numbers and say whether the first is less than the
second or greater than the third.

Response:

function thisEntre(num1, num2, num3){


return(num1 > num2 && num1 < num3)
}
function thisOutOfRange(num1, num2, num3){
return(num1 > num2 && num1 > num3)
}

Exercise 9: Words, just words.

Let's see if it is clear: I wrote the function isWeekEnd that takes a string representing the
name of a day of the week, and tells us if it is "Saturday" or "Sunday".

Response:

function isWeekEnd(day){
return(day === "Saturday" || day === "Sunday")
}

Exercise 10: Operating on strings.

Let's see if it's clear: I wrote a function lengthFirstNameComplete, which takes a first name
and a last name, and returns their total length, counting an extra space to separate the two.

Response:

function lengthFullName(firstName, lastName){


return length((firstname)+(lastname)+(1));
}

Exercise 11: SCREAM!


I wrote the shout function. We leave you to use the convertToCase function, which, uhm....
well... basically converts to uppercase a string .

Response:

function shout(word){
return("¡" + convertToMayuscula(word) + "!")
}

Exercise 12: What if...?

No introduction to theJavaScript language would be complete without showing at least one


control structure we already know: the conditional alternative.

Let's see if you understand: I wrote a max function, which works like Math.max (no good to
use it!) and returns the maximum between two numbers. For example, the maximum
between 4 and 5 is 5, and the maximum between 10 and 4 is 10.

Response:

function maximo(numero1, numero2) {


if (number1 >= number2) {
return number1;
} else {
return numero2;
}
}

Exercise 13: What sign are you?

We need a sign function, that given a number returns:

 1 if the number is positive.


 0 if the number is zero.
 -1 if the number is negative.

I wrote the sign function. You may need more than one if.

Response:

function sign (number){


if(number > 0) return 1
if(number === 0) return 0
if(number < 0) return - 1
}

Exercise 14: The return of the Boolean.


I wrote the function isLuckyNumber that given a number tells if it meets the above logic.
It's not worth using if!

Response:

function isLuckyNumber(number) {
return (number)>0 && (number)<100 && (number!=15);
}

Exercise 15: Awards.

The jury of a tournament asked us to develop a function medalSecondPlace that returns the
medal that corresponds to the first places, according to the following logic:

 first place: "gold".


 second place: "silver".
 third place: "bronze".
 other positions: you are entitled to "nothing".

Response:

function medallaSegunPuesto(lugar){
if(place === 1){
return("gold")
} else if(place === 2) {
return("silver")
} else if(place === 3) {
return("bronze")
} else {
return("nothing")
}
}

Exercise 16: Data types.

As we have just seen, inJavaScript there are numbers, booleans and strings:

In addition, there are operations that work for alltypes of data, for example:

 ===: tells us if two things are equal.


 !==: tells us if two things are different.

Try the following things on the console:

 5 + 6 (ok, the numbers can be added).


 5 === 6 (ok, all things can be compared).
 8 > 6 (ok, the numbers can be ordered).
 !true (ok, booleans can benegated).
 false / true (no good, booleans cannot be split!).
Response:

Test on the console

Exercise 17: Data of all types.

Before we finish one last challenge: What is the value of the following expressions? Check
all the right ones!

Response:

4 + 4 equals 8

"4" + "4" is equal to "44".

"on" + "ce" stands for "once".

true && false is false

5 >= 6 is false

! true is false

2. Practice Functions and Data Types.

Exercise 1: Buying Hardware.

I wrote a quantCuesta function that takes the number of inches of the monitor and the
amount of memory, and calculates the estimated cost of our computer.

Response:

function quantoCuesta(monitor, memory){


return((monitor * 60) + (memory * 200) + 1000);
}

Exercise 2: Is it convenient for me?

Now that we know how much a computer costs, we want to know if a computeris right for
me. This occurs when:

 It is less than $6000.


 It has at least a 32-inch monitor.
 It has at least 8GB of memory.

I wrote the function meConviene, which again takes the number of inches and amount of
memory and tells us if it is convenient to buy it.

Response:

function meConviene(inch,memory){
return (how muchCuesta(inch,memory) < 6000 && inch >= 32 && memory >= 8);
}

Exercise 3: Triangles.

Time to do some geometry! We want to know a few things about a triangle:

 perimeterTriangle: given the three sides of a triangle, we want to know how long its
perimeter is.
 areaTriangle: given the base and height of a triangle, we want to know its area.

Develop the functions perimeterTriangle and areaTriangle.

Response:

function perimeterTriangle(side1, side2, side3){


return (side1 + side2 + side3)
}
function areaTriangle(side1, side3){
return (side1 * side3 / 2)
}

Exercise 4: Squares.

And now it is the turn of the squares; we want to know

 perimeterSquare: given a side, we want to know how long its perimeter is.
 areaSquare: given a side, we want to know its area.

Develop the functions perimeterSquare and areaSquare.

Response:

function perimeterSquare(side) {
return (side * 4)
}
function areaSquare(side) {
return (side * side)
}
Exercise 5: Are you in tune?

Develop a tuned function, which receives the frequency (a number) fromthe control panel,
and tells if this frequency is equal to 440Hz.

Response:

function thisFrequency(frequency){
return (frequency === 440)
}

Exercise 6: Is it close?

Now we want to know if the centerc of the piano isclose to being in tune. This occurs when
it is between 437Hz and 443Hz, but it is NOT exactly 440Hz.

I wrote the function thisClose.

Response:

function thisClose(frequency){
return (437 <= frequency && frequency <= 443 && frequency !== 440)
}

Exercise 7: Posters.

I wrote the function writeLittlePost, which takes a title, a first name and a last name and
forms a single string.

Response:

function escribirCartelito(titulo, nombre, apellido){


return(title + " " + first name + " " + last name)
}

Exercise 8: More Posters.

Response:

function escribirCartelito(titulo, nombre, apellido, bool){


return (title + " " + (!bool?firstname+""+lastname:lastname))
}

Exercise 9: Optimal posters.


Now that we can write our large and small nameplates, we want anew function that will
give us the optimal size nameplate:

 If first and last name have, in total, more than 15 letters, we want a short sign;
 Otherwise, we want a long sign.

I defined the function writeBillboardOptimal that takes a title, a first name and a last name,
and using writeBillboard generates a short or long billboard, according to the above rules.

Response:

function escribirCartelitoOptimo(titulo, nombre, apellido){


return writeLetter(title, name, first name, last name,(length(first name +
last name) >= 15))
}

Exercise 10: Face or mint.

I wrote a function decisionConMoneda, which takes three parameters and returns the
second one if the first one is "cara", or the third one, if "ceca".

Response:

function decisionConMoneda(moneda, pizzas, empanadas){


if(coin === "heads"){
return pizzas;
}else{
return empanadas;
}
}

Exercise 11: Envido!

We want to know the value of the trick cards when playingenvido. We know that:

 All cards from 1 to 7, inclusive, are worth their numbering.


 Cards from 10 to 12, inclusive, are worth 0.
 You don't play with 8s or 9s.

I wrote a function valueSend, which takes a letter number and returns its send value.

Response:

function valueSent(letter){
if(letter >= 1 && letter <= 7)
{return letter}
if(letter >= 10 && letter <= 12)
{return 0}
}

Exercise 12: I want a replay.

Well, uhm, no, stop, first we want to calculate how many envido points a player adds up to.
We know that:

 If the two cards are of the same suit, the value of the send is the sum of their send
values plus 20.
 Otherwise, the value of the shipment is the highest shipment value between them.

Using the function sendValue (which we already wrote for you), develop the function
TotalSendPoints that takes the values and suits of two cards and tells how much send they
add up to in total.

Response:

function pointsSentTotals(n1, p1, p1, n2, p2){


if(p1 === p2){
return (valueSent(n1) + valueSent(n2) + 20)
}else{
return Math.max(n1, n2)
}
}

Exercise 13: I want voucher four.

When playing truco, the opposing teams may alternatively raise the bet. For example, if a
player singstruco, another player can singretruco. Obviously, the stakes are getting higher
and higher:

Canto Points at stake


trick 2
retruco 3
is worth
4
four

I wrote the function valueCantoTruco, which takes the song and returns how many points it
is worth.

Response:

function valueCantoTruco(canto){
if(canto === "truco"){
return(2)
}
if(canto === "retruco"){
return(3)
}
if(canto === "vale cuatro"){
return(4)
}
}

Variables and Procedures.

Exercise 1: What about the board?

Response:

functionMysterious(2, 1)

Exercise 2: Screen printing.

Response:

Try functionEgocentrica() in the console.

Exercise 3: Martin Fierro.

Let's see if it becomes clear, I wrote a versosMartinFierro function that prints the first
verses of Martin Fierro on the screen:

Here I start to sing


To the beat of the vigüela;
That the man who unveils it
An extraordinary grief

This function must return 0

Response:

function versosMartinFierro() {
print("Here I start singing");
print("To the beat of the beam;");
print("Let the man who unveils it");
print("An extraordinary sorrow");
return 0
}

Exercise 4: What about the procedures?


When we want to reuse code, we could declare:

 functions, which always return something and produce no effect.


 procedures, which do not return anything, and produce effects.

Send this new version of versosMartinFierro.

Response:

function versosMartinFierro() {
print("Here I start singing");
print("To the beat of the beam;");
print("Let the man who unveils it");
print("An extraordinary sorrow");
}

Exercise 5: What about the program?

InJavaScript everything we write outside of afunction will implicitly be that entry point.
For example, if we want a program that prints the classic "Hello, world!" on the screen, we
can write it like this:

print("Hello World!");

Response:

print("Rolling dice");
print("The first roll hit " + rollDead());
print("The second roll hit " + rollDead());
print("The third roll hit " + rollDead());

Exercise 6: Coercions.

Let's see if it's clear, I wrote a function elephantsEquilibrants, which takes a number of
elephants andreturns a rhyme from a well-known song "3 elephants were swinging".

Response:

function elephantsEquilibrants(number){
return(number + " " + "elephants were swinging")
}

Exercise 7: The circle of life.

Considering the number pi equal to 3.14159265358979 (not infinite but precise enough for
our calculations):
I defined the functions perimeterCircle and areaCircle that receive the radius of a circle and
from it return its perimeter and area.

Response:

function perimeterCircle(radius){
return(3.14159265358979 * 2 * radius)
}
function areaCircle(radius) {
return(3.14159265358979 * radius * radius)
}

Exercise 8: I think it is easier this way.

let pi = 3.14159265358979;

Change the places where 3.14159265358979 appears for the variable pi in the functions we
have defined.

Response:

let pi = 3.14159265358979;

function perimeterCircle(radius){
return(pi * 2 * radius)
}
function areaCircle(radius) {
return(pi * radius * radius)
}

Exercise 9: This is worthless.

Now that you understand how variables areassigned, here is some food for thought: what
happens if I try touse a variable to which I have never assigned a value?

Response:

Copy, paste and test in the console

Exercise 10: Global variables.

Variables declared within a function, known aslocal variables, present no great mystery.
However, particular care must be taken: they can only be used from within the function in
question.
However, variables declared directly in the program, known asglobal variables, can be used
from any function.

Response:

let loadMaximumInKilograms = 300


function elevatorOverloaded(people){
return(persons * weightAveragePersonWeightInKilograms) >
loadMaximumInKilograms
}

Exercise 11: Becoming rich.

I wrote an incrementFortuna procedure that doubles the value of the global variable
pesosInMyWallet. Don't declare the variable, we already did it for you (with a secret
amount of money).

Response:

function incrementFortuna(){
pesosInMyWallet = pesosInMyWallet * 2
}

Exercise 12: How much is this worth?

We saw that a variable can only have one value, so each time we assign a new one, we lose
the previous one.

Response:

20

4. Boolean logic.

Exercise 1: Let the last one turn off the light.

Let's start with something simple, do you remember the operator! It is called negation, not
or logical complement and is used to negate a Boolean value.

If I have the boolean represented by hasHungry, the complement will be !hasHungry.

I defined the useClose procedure so that we can open and close the zipper of a backpack.

Response:
let backpackOpen = true;
function useClose() {
backpackOpen = !backpackOpen
}

Exercise 2: Denying does not cost anything.

Now it's your turn! I defined isOlderOfAge, which receives an age, and then is
YoungerOfAge from it.

Response:

function isOlderOf(age){
return(age >= 18)
}
function isMinorOfAge(age){
return(!isOldestOfAge(age))
}

Exercise 3: The peripatetics.

I defined an esPeripatetic function that takes a person's profession, nationality and the
number of kilometers he/she walks per day. Someone is peripatetic when he is a Greek
philosopher and likes to walk (he walks more than 2 kilometers per day).

Response:

function esPeripatetico(teacher, nationality, kms){


return(professor === "philosopher" && nationality === "Greek" && kms > 2)
}

Exercise 4: The truth behind the conjunction.

Response:

Test on console:

consumesLittleEnergy(24, 5)

consumesLittleEnergy(24, 0)

consumesLittleEnergy(21, 7)

consumesLittleEnergy(18, 1)

Exercise 5: Let's play T.E.G.!


Response:

Test on the console:

win(true, 25)

win(false, 30)

win(false, 20)

win(true, 31)

Exercise 6: And now... who can help us?

We know the bank is closed when:

 It is a holiday, or
 It's the weekend, or
 We are not during banking hours.

I defined the functions isWeekEnd and isClosed.

Response:

let esFeriado = true;


function isWeekEnd(day){
return(day === "saturday" || day === "sunday")
}
function isClosed(isFeriado, day, time){
return(enFeriado || !dentroDeHorarioBancario(horario) ||
enFinDeSemana(dia))
}

Exercise 7: Good morning.

In the Buendía family it happens that:

 Arcadio is the son of José Arcadio and Pilar Ternera.


 Aureliano José is the son of Colonel Aureliano and Pilar Ternera.
 Aureliano Segundo and Remedios are the children of Arcadio and Sofia De La
Piedad.

To start analyzing this family, we have already defined the functions motherFrom and
fatherFrom.
Now it is your turn to define the function areMediaBrothers. Remember that half-siblings
can share mother or father but not both because.... in that case they would be siblings!

Response:

function haveTheSameMother(child1, child2){


let mother1 = motherFrom(child1);
let mother2 = motherFrom(child2);
return mother1 === mother2;
}
function haveSameParent(child1, child2){
let parent1 = parentFrom(child1);
let parent2 = parentFrom(child2);
return parent1 === parent2;
}
function areMiddleSiblings(child1, child2){
return (haveSameMother(child1, child2) !== haveSameFather(child1, child2));
}

Exercise 8: The truth is that there is no truth.

Try your function areMeansSiblings with the following values and check if it behaves like
the table:

Response:

sonMediosHermanos(arcadio, aurelianoJose)
sonMediosHermanos(aurelianoSegundo, remedios)
sonMediosHermanos(aurelianoJoseph, remedios)

Exercise 9: Hello! My name is Xor.

Unlike and, or and not, xor is not usually defined in languages. However, now that you
know how it works, if you ever need it, you can define it by hand.

Let's see if you understand: I defined the generic function xor, which takes two booleans
and returns the corresponding truth value.

Response:

function xor(a, b){


return(a !== b)
}

Exercise 10: Precedence.


When a mathematical expression has several operators, we know that multiplications and
divisions will be performed before additions and subtractions:

5 * 3 + 8 / 4 - 3 = 14

As in mathematics, when using logical operators, expressions are evaluated in a certain


order calledprecedence.

Response:

Test it in the console with the values:

payWithCard(true, "credit", 320)

payWithCard(false, "credit", 80)

payWithCard(true, "debit", 215)

payWithCard(true, "debit", 32)

Exercise 11: An unprecedented exercise.

I wrote the function canRetire that receives the age and gender of a person, in addition to
the years of pension contributions he/she has.

The minimum age for women is 60 years old, while for men it is 65 years old. In both cases,
at least 30 years of contributions are required.

Try to solve it in a single function! Then let's see what it would look like if we delegate.

Response:

function canRetire(age, gender, contribution){


return((gender === "F" && age >= 60) || (gender === "M" && age >= 65)) &&
contribution >= 30
}

Exercise 12: Can I go upstairs?

The requirements to ride the attraction are:

 Reach the minimum height of 1.5m (or 1.2m if accompanied by an adult).


 Not having any heart condition.
I defined the 3-parameter function canClimb that receives a person's height in meters,
whether he/she is accompanied and whether he/she has a heart condition.

Response:

function canRaise(height, accompanied, condition){


return((height >= 1.5) || (height >= 1.2 && accompanied)) && !affeccion
}

5. Lists.

Exercise 1: Favorite series.

To represent a set of strings, we place all the strings we are interested in between square
brackets ([ and ]) separated by commas. Easy, isn't it?

Response:

Try the following queries in the console:

seriesFavoritesFromAna

seriesFavoritesDeHector

["hello", "world!"]

["hello", "hello"]

Exercise 2: And this is a list.

What we have just seen is how to easily model sets of things. Using[],JavaScript provides
a simple way to group these elements into lists.

Is there a maximum number of elements? No, there is no limit! Lists can have any number
of elements.

Not only that, but order is important. For example, ["hello", "world"] is not the same as
["world", "hello"]: both have the same elements, but in different positions.

Response:

Try the following queries in the console:


equalLists(["hello", "world"], ["world", "hello"])

equalLists(["hello", "world"], ["hello", "world"])

equalLists(["hello", "world"], ["hello", "all", "the", "world"])

equalLists(["hello"], ["hello", "world"])

["hello", "world"] === ["world", "hello"]

people

["mara", "julian"] === people

people === people

Exercise 3: Games of chance.

We can also represent sets of numbers or Booleans in the same way: writing them in square
brackets and separated by commas. We can have lists of numbers, of strings, of booleans,
and so on. We could even have lists of lists!

Response:

Let's see if this is clear. Try the following queries in the console:

LotteryNumbers

salioCara

[[1, 2, 3], [4, 5, 6]]

Exercise 4: Empty lists.

Great, it looks like a list can contain any type of item! We can have lists of Booleans, of
numbers, of strings, of lists...

Not only that, but they can contain any number of elements: one, two, fifteen, hundreds.

Can we then have empty lists, i.e., that have no elements? Of course!
let unaListaVacia = []

Response:

Try typing in the console aVacancyList

Exercise 5: How many elements do you have?

By now we know what things we can represent with lists, and how to do it. But what can we
do with them?

Let's start with the easy part: knowing how many items are in the list. We can do this by
using the length function, similar to what we did with strings.

Response:

Perform the following queries in the console:

length([])

length(lotteryNumber)

length([4, 3])

Exercise 6: Adding flavor.

Lists are very useful for containing multiple items. But there is more! We can also add
elements to it at any time, using the add function, which receives two parameters: the list
and the element.

As we can see, adding adds an element to the list, which increases its size. But where in the
list do you add it? At the beginning? In the end? In the middle?

Find out for yourself: inspect in the console which items contain belongings, add a
"crossbow" and inspect belongings again.

There is also a remove procedure, which only receives the list by parameter. Check the
console to see what it does.

Response:
Test on the console

add(belongings, "magic amulet")

Exercise 7: Transfer.

Declare a move procedure, which takes two lists, removes the last element from the first
one and adds it to the second one.

Response:

function move(aList, anotherList){


add(otherList, remove(otherList))
}

Exercise 8: And where is it?

And what happens if you pass an element that it does not have as a parameter to position?
See for yourself!

Response:

Copy and paste into the console

position(workdays, "osvaldo")

Exercise 9: Contains.

I wrote the function contains that tells us if a list contains a certain element.

If you have been paying attention to the query examples, you will have noticed that lists can
also have duplicate elements: [1, 2, 1], ["hello", "hello"], etc.

Therefore, position actually returns the position of thefirst occurrence of the element in the
list.

Response:

function contains(array, search){


return(position(array, search) >- 1)
}

Exercise 10: Nth element.


Just as there is a function to find out in which position an element is, it can also happen that
we want to know the opposite: which element is in a certain position.

To find out we can use theindexing operator, writing after the collection and between
square brackets [] the position we want to find out.

Response:

let list =[]

list[0]

Exercise 11: More awards.

If you ask for an element in a position equal or greater than the size of the list, you will get
undefined. It doesn't seem terrible, but the problem is that with undefined you can't do
anything really useful.

So the warning is: don't over-index!

With that in mind, here's a challenge: I rewrote the function medalSecondPosts, but this
time using at most a single if. You may find the lists useful here .

We remind you what the function does: it has to return the medal that corresponds to the
first places in a competition.

Response:

let medal = ["nil", "gold", "silver", "bronze"]

function medallaSegunPuesto(puesto){
if(post <= 3){
return(medal[position])
} else {
return(medal[0])
}
}

Exercise 12: Don't forget to say hello.

Let's get to know a way to traverse the elements of a list with a new friend: the for loop.

Response:
function greet(people){
for(let person1 of persons){
print("hello" + " " + person1);
}
}

6. Records.

Exercise 1: The first records.

Response:

Copy and paste the code into the console

statueOfFreedom
christRedentor
EiffelTower
tajMahal
colosseum

Exercise 2: Your own monument.

It's your monument moment! Save in the variables torreAzadi and


monumentoNacionalALaBandera records of these monuments, originating from the cities
of Tehran,Iran and Rosario,Argentina respectively. Do you dare to investigate in which
year they were finished to complete that field?

Response:

let AzadiTower = {name: "Azadi Tower", location: "Tehran, Iran",


yearOfConstruction: 1971}
let monumentoNacionalALaBandera = {name: "Monumento Nacional A La Bandera",
location: "Rosario, Argentina", yearOfConstruction: 1957 }

Exercise 3: Accessing the field.

We declare the planets mercury, mars and saturn as records with the following information:
name, temperatureAverage and if it has Rings. Try them on the console!

Response:

We declare the planets mercury, mars and saturn as records!


Exercise 4: Glide temperature.

Develop a function temperatureFromPlanet that receives by parameter a planet record and


returns a string indicating its name and its average temperature. It has to work for any
planet!

Response:

function planetTemperature(planet){
return(planet.name + " has an average temperature of " +
planet.averageTemperature + " degrees")
}

Exercise 5: Moving files.

Develop the moveFile procedure, which receives a record and a new path and modifies the
file with the new path.

Response:

function moveFile(record, pathNew){


let readme = record.path = newPath
}

Exercise 6: Records of two millennia.

In the previous exercise we modified the registry path, but we did not use its creation date.
Let's use it! We want to know if a file is from the last millennium, which happens when its
year is before 2000.

Develop the function esDelMilenioPasado, which receives a file and returns a boolean.

Response:

function esDelMilenioPasado(file){
return(year(file.creation) < 2000)
}

Exercise 7: Complex desserts.

Create a function moreDifficultToBake, which receives two dessert records for parameters
and returns the one that has more ingredients of the two.

Response:
function moreDifficultToCook(dessert1, dessert2){
if(length(dessert1.ingredients) < length(dessert2.ingredients)){
return dessert2;
}
if(length(dessert1.ingredients) >= length(dessert2.ingredients)){
return dessert1;
}
}

Exercise 8: Registration lists.

Just as we work with lists of numbers, Booleans, strings or more lists, we can also list
records. You can do everything you did before, such as remove, know its length or ask for
the element of a certain position using the square brackets [ ].

Try in the console the lists dessertsFavorites and monumentsOfAmerica. There is a dessert
that we didn't show before, can you tell what it is just by reading its ingredients?

Response:

Test on console:

dessertsFavorites

monumentosDeAmerica

Exercise 9: 60 sweet minutes.

Develop the procedure addAPostresRapidos, which receives a list with quick desserts and
one dessert per parameter. If the cooking time is one hour or less, the record is added to the
list.

Response:

function addAPostresresRapidos(list, dessert){


if(dessert.cookingTime <= 60){
add(list, dessert)
}
}

Exercise 10: There is a record in my register.

Find out what the ingredients field of the dessert field of the menuChildren record returns.
It's one record inside the other!
Response:

Test on console

menuChildren.dessert.ingredients

Exercise 11: Sugar.

I defined a procedure sweetenMenu, which receives a menu record and adds sugar to the
ingredients of your dessert. If it already has sugar in it, it doesn't matter.... add more!

Response:

function sweetenMenu(menu){
add(menu.dessert.ingredients, "sugar")
return menu.dessert
}

7. Tours.

Exercise 1: Semiannual earnings.

Is there a problem with the gainSemester function we wrote above? Will it work with
quarterly balance sheets? What about quarterly quarters?

Try it on the console!

Response:

Test on the console:

profitSemester

Exercise 2: What about the rest of the profits?

What we would like is to be able to add up the profits of all the balances in a list, no matter
how many there actually are; we want a function profitTotal, which can add up balances for
any period of months: semesters, quarters, quarters, etc. How difficult!

Response:
profitTotal([
{ month: "January", profit: 2 },
{ month: "February", profit: 3 }
])

Exercise 3: All gains, the gain.

Response:

function gananciaTotal4(balancesOfAperiod){
let summation = 0
summation = summation + balancesOfAperiod[0].gain
summation = summation + balancesOfAperiod[1].gain
summation = summation + balancesOfAperiod[2].gain
summation = summation + balancesOfAperiod[3].gain
return sum
}

Exercise 4: An old friend visits us.

What we have to do, then, is to repeat the accumulation operation several times, once for
each item in the list. Let's say hello (again) to the for...of!

As you can see, the for...of allows us to visit and do something with each element of a list;
in this case, we will be visiting each balance of balancesOfAPeriod.

Response:

profitTotal([
{ month: "March", profit: 8 },
{ month: "August", profit: 10 }
])

Exercise 5: Clear accounts.

Ana has new requirements! Now he asked us the following: "I want to know how many
balances were positive, that is, those in which the profit was greater than zero".

Complete the PositiveBalanceAmount function. If you pay attention, you will notice that it
has a similar structure to the previous problem.

Response:
function amountOfBalancesPositive(balancesOfAperiod){
let quantity = 0
for(let balance of balancesOfAperiod){
quantity = quantity + ((balance.profit) > 0)
}
return quantity;
}

Exercise 6: The average gain.

Let's move on to Ana's next request. We can already calculate a sum of profits and also
create counters, now we are going to calculate averages.

Ana would like to know what is the average profit given any set of balances.

Response:

function gananciaPrommedio(gananciaTotal){
let summation = 0
for(let balance of gananciaTotal){
summation = (summation + balance.gain)
}
return sum / length (TotalGain)
}

Exercise 7: Who wins, who loses.

Seeing that we can do everything she asks us to do, Ana wants to know the average profit of
the positive balances.

I defined the functions:

 Positive profit, which is the sum of the profits of the positive balances.
 averagePositiveProfit invoking PositiveProfit and numberOfPositiveBalances.

Response:

function positiveGain(balancesOfAperiod){
let summation = 0
for(let balance of balancesOfAperiod){
if(balance.gain > 0){
summation = summation + (balance.gain)
}
}
return summation
}

function averagePositiveProfits(balancesOfAperiod){
return profitPositive(balancesOfAperiod) /
amountOfBalancesPositive(balancesOfAperiod)
}
Exercise 8: I am the map, I am the map.

Unfortunately, it is not possible to use the average function with our list of records. What
we need is a list that has only the earnings of each balance. To do this we must transform,
ormap, each element of the list.

Complete the earnings function that takes a list of balances and returns a list of only the
earnings of each one.

Response:

function earnings(balancesOfAperiod){
let profits = []
for(let balance of balancesOfAperiod){
add(profit, balance.profit)
}
return earnings
}

Exercise 9: To filter, to filter everything in its place.

With programming you can do anything, or almost anything. We have already made a
function to know the number of positive balances (numberOfPositiveBalances), now let's
see how we can know which are those balances.

Complete the function balancesPositive that takes the balances of a period and returns a list
of those whose profit was greater than zero.

Response:

function balancesPositive(balancesOfAperiod){
let balances = []
for(let balance of balancesOfAperiod){
if(balance.gain > 0){
add(balances, balance)
}
}
return balances
}

Exercise 10: A more positive average.

Now that we have the profit function and positive balances, we can use the generic average
function to find out the average profit of the positive balances.
Define the function profitsFromBalancesPositive and then use it together with average to
define averageFromBalancesPositive.

Response:

function gainsFromBalancesPositive(balancesOfAperiod){
return earnings(balancesPositive(balancesOfAperiod))
}
function averagePositiveBalances(balancesOfAperiod){
return average(earningsPositiveBalances(balancesOfAperiod))
}

Exercise 11: This is the maximum.

We are going to learn about a new function, maximo, which allows us to know what is the
largest value in a list of numbers.

Using this new function, I defined the maxProfit function that tells us what is the highest
profit among the balances of a period of time.

Response:

function maxMaximumProfit(balancesOfAperiod){
return max(earnings(balancesOfAperiod))
}

Exercise 12: At least.

We guess you guessed the name. If not, it is minimal.

Define the minimumPositiveProfit function that tells us what is the lowest profit of all
positive balances.

Response:

function minimumPositiveProfit(balancesOfAperiod){
return minimo(gananciasDeBalancesPositivos(balancesDeUnPeriodo));
}

Exercise 13: The best months of the year.

For that we are going to do the following functions:

 months, which given a list of records returns a list of months;


 lucky, which filters out those records that had a profit greater than $1000;
 LuckyMonths, returns those months that were lucky.
I defined the functions months, lucky, luckyMonths.

Response:

function months(earningsPeriod){
let month = []
for(let period of earningsPeriod){
add(month, period.month)
}
return month
}
function lucky(earningsPeriod){
let lucky = []
for(let period of earningsPeriod){
if(period.gain > 1000){
add(lucky, period);
}
}
return lucky;
}
function luckyMonths(earningsPeriod){
return months(lucky(earningsPeriod));
}

You might also like