Professional Documents
Culture Documents
Mumuki Exercises
Mumuki Exercises
Chapter 1: Fundamentals.
1. First Programs.
Response:
program {
Move(North)
Move(North)
Move(North)
}
Exercise 6: Everywhere.
Response:
program {
Move(South)
Move(East)
Move(East)
}
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)
}
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)
}
Response:
program {
Put(Red)
Put(Red)
Put(Blue)
Put(Green)
Put(Red)
}
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)
}
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)
}
Response:
program{
Remove(Green)
}
Response:
program{
Sacar(Blue)
Remove(Green)
Remove(Black)
Remove(Red)
}
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)
}
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)
}
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)
}
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)
}
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)
}
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)
}
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.
Response:
Response:
Continue to
Response:
Continue to
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:
Complete the code so that in addition to defining the PutBlackandRed procedure, it invokes
it in the program.
Response:
program{
SetBlackAndRed()
}
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:
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()
}
Response:
program{
Set3Greens()
Move(East)
Set3Greens()
}
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()
}
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()
}
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()
}
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()
}
Response:
procedure RojoAlBorde() {
GoToEdge(North)
GoToEdge(West)
Put(Red)
}
program{
RojoAlBorde()
}
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()
}
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()
}
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)
}
Response:
Response:
procedure MoveWest5(){
repeat(5){
Move(West)
}
}
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)
}
}
I defined the procedure PutBlueFar(), which places a Blue ball 4 cells to the East
Response:
procedure PutBlueFar(){
repeat(4){
Move(East)
}
Put(Blue)
}
Response:
procedure DrawBlackLine6(){
repeat(6){
Put(Black)
Move(East)
}
}
Response:
procedure RedLine4() {
repeat(4) {
Put(Red)
Move(North)
}
}
Response:
procedure Diagonal4Blue(){
repeat(4){
Put(Blue)
Move(North)
Move(East)
}
}
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)
}
}
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.
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()
}
Response:
procedure DrawBlackSquareFromSide3(){
repeat(2){
DrawBlackLine3()
Move(North)
}
DrawBlackLine3()
}
program{
DrawBlackSquareSide3()
}
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()
}
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()
}
Response:
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.
Response:
procedure DrawSideSquare3(color){
repeat(2){
DrawLine3(color)
Move(North)
}
DrawLine3(color)
}
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)
}
Create any program that invokes DrawLine3, but this time try to invoke it with the
arguments inverted.
Response:
program{
DrawLine3(North, South)
}
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)
}
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:
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)
}
}
Response:
procedure DiagonalBand4() {
repeat(3) {
Diagonal4BlueBack()
Move(North)
}
GoToEdge(South)
}
Exercise 3: Let's put... As much as we want.
Response:
Response:
procedure MemoryDay(){
SetN(24, Blue)
Move(East)
SetN(3, Green)
Move(East)
PonerN(1976, Black)
}
Response:
I defined a procedure MoveN(quantity, direction) that makes the spindle move the specified
number of times in the specified direction.
Answer:
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)
}
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:
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)
}
I defined a SaveInL() procedure that does a save in L as shown in the figure, butleaving the
head in the initial position.
Answers:
7. Expressions.
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){
}
}
I defined a procedure PutSum(x, y) that receives two parameters and puts the amount of red
balls that arises from addingxandy.
Response:
We have the information of how many buses, cars and bicycles attended and from there we
can make a calculation following these rules:
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:
Response:
Response:
procedure WalkUntrusted(steps){
MoveN(steps div 2, East)
}
We want to define a procedure that allows us to put a ballnext to where the head is, leaving
it in the original position.
Response:
Using your new knowledge of expressions, modify theLine procedure so that the spindle
stays where it started.
Response:
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)
}
Response:
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))
}
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?
procedure CopyGreensInRed() {
SetN(nroBolitas(Green), Red)
}
Continuing with the counting of the beads, it is now your turn to define a procedure to
removeall the beads ofone color.
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.
Response:
Response:
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)
}
}
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)
}
}
Create a program that moves to the East onlyif possible. Remember to use
canMove(address).
Response:
program{
if(canMove(East)){
Move(East)
}
}
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)
}
}
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)
}
}
Response:
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:
Gobstone functions,
Response:
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))
}
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))
}
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...
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))
}
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))
}
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))
}
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))
}
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.
Response:
function hayLimite(){
return (I'mOnAnEdge() ||I'mSurroundedBy(Red))
}
Chapter 2: Imperative Programming.
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)
}
function previous(number){
return(number - 1)
}
function triple(number){
return(number * 3)
}
previous functionDelTriple(number){
return(previous(triple(number))))
}
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:
Math.round(4.4)
Math.round(4.6)
Math.max(4, 7)
Math.min(4, 7)
Response:
Response:
Response:
function leGustaLeer(unNumero){
return(aNumber > 20)
}
Exercise 8: Booleans.
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:
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")
}
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:
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) + "!")
}
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:
I wrote the sign function. You may need more than one if.
Response:
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);
}
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:
Response:
function medallaSegunPuesto(lugar){
if(place === 1){
return("gold")
} else if(place === 2) {
return("silver")
} else if(place === 3) {
return("bronze")
} else {
return("nothing")
}
}
As we have just seen, inJavaScript there are numbers, booleans and strings:
In addition, there are operations that work for alldata types, for example:
Response:
Before we finish one last challenge: What is the value of the following expressions? Check
all the right ones!
Response:
4 + 4 equals 8
5 >= 6 is false
! true is false
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:
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.
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.
Response:
Exercise 4: Squares.
perimeterSquare: given a side, we want to know how long its perimeter is.
areaSquare: given a side, we want to know its area.
Response:
function perimeterSquare(side) {
return (side * 4)
}
function areaSquare(side) {
return (side * side)
}
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.
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:
Response:
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:
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:
We want to know the value of the trick cards when playingenvido. We know that:
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}
}
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:
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:
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)
}
}
Response:
functionMysterious(2, 1)
Response:
Let's see if it becomes clear, I wrote a versosMartinFierro function that prints the first
verses of Martin Fierro on the screen:
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?
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");
}
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")
}
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)
}
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)
}
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:
However, variables declared directly in the program, known asglobal variables, can be used
from any function.
Response:
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
}
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.
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:
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))
}
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:
Response:
Test on console:
consumesLittleEnergy(24, 5)
consumesLittleEnergy(24, 0)
consumesLittleEnergy(21, 7)
consumesLittleEnergy(18, 1)
Response:
win(true, 25)
win(false, 30)
win(false, 20)
win(true, 31)
It is a holiday, or
It's the weekend, or
We are not during banking hours.
Response:
To start analyzing this family, we have already defined the functions motherFrom and
fatherFrom.
Response:
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)
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:
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
Response:
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:
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:
5. Lists.
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:
seriesFavoritesFromAna
seriesFavoritesDeHector
["hello", "world!"]
["hello", "hello"]
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:
people
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
Not only that, but they can contain any number of elements: one, two, fifteen, hundreds.
let unaListaVacia = []
Response:
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:
length([])
length(lotteryNumber)
length([4, 3])
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:
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:
And what happens if you pass an element that it does not have as a parameter to position?
See for yourself!
Response:
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:
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:
list[0]
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.
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:
function medallaSegunPuesto(puesto){
if(post <= 3){
return(medal[position])
} else {
return(medal[0])
}
}
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.
Response:
statueOfFreedom
christRedentor
EiffelTower
tajMahal
colosseum
Response:
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:
Response:
function planetTemperature(planet){
return(planet.name + " has an average temperature of " +
planet.averageTemperature + " degrees")
}
Develop the moveFile procedure, which receives a record and a new path and modifies the
file with the new path.
Response:
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)
}
Create a function moreDifficultToBake, which receives two dessert records for parameters
and returns the one that has more ingredients of the two.
Response:
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
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)
}
}
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
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.
Is there a problem with the gainSemester function we wrote above? Will it work with
quarterly balance sheets? What about quarterly quarters?
Response:
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 }
])
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
}
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 }
])
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;
}
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)
}
Seeing that we can do everything she asks us to do, Ana wants to know the average profit of
the positive balances.
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)
}
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
}
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
}
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))
}
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))
}
Define the minimumPositiveProfit function that tells us what is the lowest profit of all
positive balances.
Response:
function minimumPositiveProfit(balancesOfAperiod){
return minimo(gananciasDeBalancesPositivos(balancesDeUnPeriodo));
}
Response:
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)
}
Response:
function previous(number){
return(number - 1)
}
function triple(number){
return(number * 3)
}
previous functionDelTriple(number){
return(previous(triple(number))))
}
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:
Math.round(4.4)
Math.round(4.6)
Math.max(4, 7)
Math.min(4, 7)
Response:
Response:
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.
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:
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")
}
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:
Response:
function shout(word){
return("¡" + convertToMayuscula(word) + "!")
}
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:
I wrote the sign function. You may need more than one if.
Response:
Response:
function isLuckyNumber(number) {
return (number)>0 && (number)<100 && (number!=15);
}
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:
Response:
function medallaSegunPuesto(lugar){
if(place === 1){
return("gold")
} else if(place === 2) {
return("silver")
} else if(place === 3) {
return("bronze")
} else {
return("nothing")
}
}
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:
Before we finish one last challenge: What is the value of the following expressions? Check
all the right ones!
Response:
4 + 4 equals 8
5 >= 6 is false
! true is false
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:
Now that we know how much a computer costs, we want to know if a computeris right for
me. This occurs when:
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.
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.
Response:
Exercise 4: Squares.
perimeterSquare: given a side, we want to know how long its perimeter is.
areaSquare: given a side, we want to know its area.
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.
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:
Response:
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:
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:
We want to know the value of the trick cards when playingenvido. We know that:
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}
}
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:
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:
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)
}
}
Response:
functionMysterious(2, 1)
Response:
Let's see if it becomes clear, I wrote a versosMartinFierro function that prints the first
verses of Martin Fierro on the screen:
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
}
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");
}
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")
}
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)
}
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)
}
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:
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:
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
}
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.
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.
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
}
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))
}
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:
Response:
Test on console:
consumesLittleEnergy(24, 5)
consumesLittleEnergy(24, 0)
consumesLittleEnergy(21, 7)
consumesLittleEnergy(18, 1)
win(true, 25)
win(false, 30)
win(false, 20)
win(true, 31)
It is a holiday, or
It's the weekend, or
We are not during banking hours.
Response:
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:
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)
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:
5 * 3 + 8 / 4 - 3 = 14
Response:
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:
Response:
5. Lists.
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:
seriesFavoritesFromAna
seriesFavoritesDeHector
["hello", "world!"]
["hello", "hello"]
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:
people
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
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:
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:
length([])
length(lotteryNumber)
length([4, 3])
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
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:
And what happens if you pass an element that it does not have as a parameter to position?
See for yourself!
Response:
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:
To find out we can use theindexing operator, writing after the collection and between
square brackets [] the position we want to find out.
Response:
list[0]
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.
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:
function medallaSegunPuesto(puesto){
if(post <= 3){
return(medal[position])
} else {
return(medal[0])
}
}
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.
Response:
statueOfFreedom
christRedentor
EiffelTower
tajMahal
colosseum
Response:
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:
Response:
function planetTemperature(planet){
return(planet.name + " has an average temperature of " +
planet.averageTemperature + " degrees")
}
Develop the moveFile procedure, which receives a record and a new path and modifies the
file with the new path.
Response:
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)
}
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;
}
}
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
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:
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
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.
Is there a problem with the gainSemester function we wrote above? Will it work with
quarterly balance sheets? What about quarterly quarters?
Response:
profitSemester
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 }
])
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
}
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 }
])
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;
}
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)
}
Seeing that we can do everything she asks us to do, Ana wants to know the average profit of
the positive balances.
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
}
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
}
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))
}
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))
}
Define the minimumPositiveProfit function that tells us what is the lowest profit of all
positive balances.
Response:
function minimumPositiveProfit(balancesOfAperiod){
return minimo(gananciasDeBalancesPositivos(balancesDeUnPeriodo));
}
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));
}