-
Mininmum
-
Recursion
-
Beam Counting
MINIMUM
function min(a, b){
if (a<b) return a;
else return b;
}
alert(min(1,9));
RECURSION:
function isEven(n){
if (n == 0) return true;
else if (n == 1) return false;
else if (n < 0) return isEven(-n);
else return isEven(n-2);
}
document.write(isEven (50) + "<br />");
document.write(isEven (75) + "<br />");
document.write(isEven (-1));
BEAN COUNTING:
function countChar(string, ch) {
let counted = 0;
for (let i = 0; i < string.length; i++) {
if (string[i] == ch) {
counted += 1;
}
}
return counted;
}
function countBs(string) {
return countChar(string, "B");
}
alert(countBs("BBC"));
document.write(countChar("kakkerlak", "k"));
function min( x,y){
if(x<y){
return x;
} if (x=y)
{return 0;} else {
return y
}
}
console.log(min(50,60));
2.function isEven(a){
if(a ==0){
return true;
}
if (a==1){return false;}
else if (a<0){return isEven(-a)}
else {return isEven(a-2);}
}
console.log(isEven(75));
3.function countBs(string){
return string.match(/B/gi).length;
}
console.log(countBs('BOB'))
let countChar=function(string,character){
let matchExp=new RegExp(character,'g');
return string.match(matchExp).length;
};console.log(countChar('fffffreak','f'));Preformatted text
- Minimum
A)
function min(x,y) {
if (x < y) return x;
else return y;
}
console.log(min(0, 10));
console.log(min(0, -10));
B)
function min(x,y) {
if (x < y){
document.write(x + " is less than " + y);
}
else {
document.write("<br>");
document.write(y + " is less than " + x);
}
}
min(0, 10);
min(0, -10);
- Recursion
function isEven(n){
if (n == 0) return true;
else if (n == 1) return false;
else if (n < 0) return isEven(-n);
else return isEven(n-2);
}
console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));
- Bean counting
function countBs(string){
let count = 0;
for (let n = 0; n < string.length; n++){
if (string[n] == "B") {
count +=1;
}
}
}
console.log(countBs("BBC"));
function countChar(string, char) {
let count = 0;
for (let i = 0; i < string.length; i++) {
if (string[i] == char) {
count += 1;
}
}
return count;
}
console.log(countChar("kakkerlak", "k"));
function countBs(string) {
return countChar(string, "B");
}
console.log(countBs("BBC"));
@iplotnik @Alexiaa @Tino @Parwiz @Capig
In forum communication, it helps a lot if you use code blocks. take a look at pic below
Thank you guys.
thanks man! will do from now on
So, here are my answers to the exercises in chapter 3,
with explanations for each one.
So, here are my answers to the exercises in chapter 3,
with explanations for each one.
- Minimum
Write a function min that takes two arguments and returns the smallest.
Okay so i really overdid it in this one and wasted some of time, but i had fun.
function min(a,b) {
if (typeof(a) != 'number' || typeof(b) != 'number') {
console.log("Try passing two different NUMERIC values")
}
else if (b === a) {
console.log("Try passing two DIFFERENT numeric values")
}
else if (a < b) {
console.log(a + " is less than " + b);
}
else if (b < a) {
console.log(b + " is less than " + a)
}
}
min(2, 4)
// -> 2 is less than 4
min(817230, 20)
// -> 20 is less than 817320
min(6, 6)
// -> Try passing two DIFFERENT numeric values
min(boat, turtle)
// -> Try passing two different NUMERIC values
I don’t think this requires too much of an explanation. The function decides which value is smallest by using an if
/ else if
/ else
-chain. Instead of returning values I decided to add a console.log
after each if
/ else
statement. If neither is smaller, then a hint is logged to the console as to how the function is supposed to be used. I decided to use console in this way because it’s easier to just write min(a,b)
than typing the entire console.log(min(2,4))
each time this function would be used.
(which it of course wouldn’t, it is pretty much useless. Unless if it were used in a bigger context, but then returning values might be better).
You can ignore the bonus feature if you’d like to.
i just wanted to add something that made sure that the function gave some hints if you tried to pass strings or two equal numbers into it. But i guess it was good learning for me, i both had to make use of thetypeof
operator and the exactly-equal-to (===
) operator to make it work, as well as shift the statements around.
When i originally hadif (a = b)
before the actual “which is greater” -statements, i think JavaScript’s automatic type conversion decided that “oh! so a and b are both numeric value types! i guess 2, 4 are equal then!” - and printed out the message where it asked for two different numeric values instead of saying that “2 is less than 4”. So thats why i used the exactly-equal-to (===) operator instead.
So yeah, i guess this whole added functionality was technically a waste if time, but at least i learned something. I think that’s what matters though.
Recursion
• Zero is even. • One is odd. • For any other number N, its evenness is the same as N - 2.
Define a recursive function isEven corresponding to this description. The function should accept a single parameter (a positive, whole number) and return a Boolean.
Test it on 50 and 75. See how it behaves on -1. Why? Can you think of a way to fix this?
This one was really tricky for me to figure out. I just couldn´t see the logic in this exercise at all. Thankfully I was able to understand it eventually by reading through some answers in this forum as well as the answer contain in the sandbox page in Eloquent JavaScript.
I can’t really take credit for the code at all, but I will explain how it works below.
function isEven(n) {
if (n == 0) {
return true;
}
else if (n == 1) {
return false;
}
else if (n < 0) {
return isEven(-n);
}
else {
return isEven(n - 2)
}
}
console.log(isEven(n))
So basically, the code is essentially an if
/ else if
-chain, where in the first check, if the number you give it is equal to 0 (which it probably isn’t), it returns true.
In the second check in the if
/ else if
-chain. It tests whether the number that you gave the function is equal to 1 (which again, it probably isn’t), if it is, it returns false.
So if neither of the two previous checks is evaluated to be true, what then?
The two following statements is where the recursiveness actually happens, and also where this whole function starts to make sense. The first (or third) else if
statement is there simply to solve the problem with negative numbers.
If the number you gave it is a negative number, the function calls itself minus whatever you gave it. So, if you gave it -1, neither of the first two checks would evaluate to true, control would then reach the third if-statement, and since if n
is equal to -1
, then (n < 0)
is evaluated to true, the function calls itself with (-n)
, (basically - -1), turning it into positive 1.
(This works the same for all negative numbers.)
The fourth and final if statement (with it’s embedded code) is really the most important, and also where almost all recursion occurs. This is where, no matter what numeric argument you called it with (unless negative, see above), the function calls itself, with whatever you gave it – 2
. Basically decreasing it’s value by two until either of the first two if-statements is evaluated to true and true or false is returned.
So, to summarize:
Giving it the number 21, for example, would cause the first three checks to evaluate to false. Causing the function to recurve with a new number, 19. It will then test whether or not any of the first three if
-statements evaluates to true, if not, it recurves again with n - 2
. This process then repeats itself until either of the first two conditions are met. In this case, recurving 10 times before finally producing 1, causing the second if- statement to evaluate true, and false is returned.
And voila, the number 21 is not an even number. Suprise.
- Bean counting
Write a function countBs that takes a string as its only argument and returns a number that indicates how many uppercase “B” characters there are in the string.
Next, write a function called countChar that behaves like countBs, except it takes a second argument that indicates the character that is to be counted (rather than counting only uppercase “B” characters). Rewrite countBs to make use of this new function.
So this exercise was also quite tricky for me to get, it involves using the .length property of whatever string you pass the function, while also creating an index to keep track and compare the character at position[index] with the letter (second argument) that you pass the function upon calling it.
function countChar(string, char){
let sum = 0;
for (let i = 0; i < string.length; i++){
if (string[i] == char)
sum += 1;
}
console.log(char + " appears " + sum + " times in " + string);
/* or "return sum;", but in this state,
i'd just rather use console.log */
}
So, first we declare the function countChar
, and it two parameters. I chose to name them string
and char
. One for the the word (string) to be “analyzed” by the function, and one for the character to be counted.
Secondly, We declare sum
to be zero (since we haven’t counted anyting yet).
The next two lines are the trickiest to understand, but it isn’t so hard when you pick it apart. We need a for
loop, and in that loop we first let i
(the index) be 0
, and then, while i
is less than the .length
of the string
(the amount of letters in the word to be analyzed, starting at the character in the first position, which is position zero), increment the index i
(by 1
).
For each iteration of this loop, the followingif
-statement then checks:
Is string at position[i
] (index) of the string
equal to the letter char
?
If so, add 1
; to the variable sum
.
Once the loop has finished, and all the positions of the string’s .length
have been compared using the if (string[i] == char)
- statement, and all the times the comparisson was true has been logged into sum, then control reaches the final part of my function.
console.log(char + " appears " + sum + " times in " + string);
so:
countChar("ivan liljeqvist", "i" )
//-> i appears 3 times in ivan liljeqvist
And then of course, if you really only wanted to test for uppercase B’s in whatever word, then you could make a new function that just calls the countChar one, with the second argument already passed as uppercase “B”, like this:
function countBs(string){
function countChar(string, "B")
}
- MINIMUM
function min(a,b){
if (a<b) { return a;
}
else return undefined;
}
console.log (min(3,5));
- RECURSION
function isEven(num) {
if (num == 1) return "Odd";
if (num == 0) return "Even";
if (num < 0) return undefined;
return isEven(num - 2);
}
console.log (isEven(75));
Got there eventually… seem to be having finger trouble on the keyboard and then couldn’t spot where I’ve gone wrong! Some of the logic has taken a bit of time to sink in and I have had to use examples to help me understand, but most of the time was trying to spot the mistake! In the end I cleared it down, started again and it worked. Here is the code I’ve done:
// MINIMUM TASK
//min that takes two arguments and returns their minimum
function min(a, b) {
if(a<b) {return (a);}
else if (a>b) {return (b);}
else if (a==b) {console.log("They are the same!")}
}
console.log (min(4,3));
console.log (min(-1,7));
console.log (min(5,5));
//Outputs
//3
//-1
//They are the same!
//RECURSION TASK
function isEven (n) {
if (n==0) {return true;} // if n is zero, return true, because zero is even
else if (n==1) {return false;} // if n is 1, return false, because it is odd
else if (n<0) {return isEven(-n);} // Needed for negative scenario, stops it from getting more negative
else {return isEven(n-2);} // recursive - it calls itself and then reduces to 1 or 0
}
console.log(isEven(50)); // tests even
console.log(isEven(75)); // tests odd
console.log(isEven(-1)); // tests negative scenario
//Outputs
// true
// false
// false
//BEAN COUNTING
//PART ONE - create countBs function that takes one string and indicates how many Bs.
function countBs(a){
let total = 0;
for (let count = 0; count < a.length; count++) {
if (a[count] == "B") {
total++;
}
}
return console.log(total);
}
console.log(countBs("there aren't any"));
console.log(countBs("a BaBy"));
console.log(countBs("Big Baby"));
console.log(countBs("BBBBcdB"));
//Outputs
//0
//2
//2
//5
//PART TWO - create countChar function
function countChar(a,b) {
let total = 0;
for (let count = 0; count < a.length; count++){
if(a[count] == b){
total++;
}
}
return console.log(total);
}
console.log(countChar("ABCDEDED","E"));
//Output
//2
//PART THREE - Rewrite countsB using countChar
function countsB(a) {
return countChar(a, "B");
}
console.log(countsB("A Big BaBy"));
//Output
//3
screenshots of the exercises completed, I am still so new to this, and this is a whole other language, but I am determined to make progress. It’s important for me to fully understand what it is I am doing, so the process is a bit slower for me at the moment. However, I am loving every moment of this!
function min(a,b){
if(a<b){
return a;
}
else
return b;
}
2.
function isEven(n){
if(n==0) return true;
else if(n==1) return false;
else if(n<0) return isEven(-n);
else return isEven(n - 2);
}
3.
function countChar(string,char){
let count=0;
for(let i=0; i<string.length; i++){
if(string[i]== char){
count++;
}
}
return count;
}
function countBs(string){
return countChar(string, “B”);
}
Here’s my take on Chapter 3 exercises. I haven’t checked the author’s solution’s yet:
Minimum:
/* Write a function
min that takes two arguments and returns their minimum.*/
let min = (x,y) => {
if(x<y)
return x;
else {
return y;
}
}
Recursion:
I used the function Math.abs() here, and maybe it is for that, but the maximum negative number I can process is -25171. No clue why.
/* Define a recursive function named isEven
The function should accept one single parameter (positive, whole number)
Must return a boolean
Logic:
• Zero is even.
• One is odd.
• For any other number N, its evenness is the same as N - 2.
*/
let isEven = num =>{
num = Math.abs(num); //Makes the number positive.
if (num == 0)
return true;
else if (num == 1)
return false;
else
return isEven(num - 2);
}
Bean Counting
/*
Write a function countBs
Takes a string as only argument
Returns a number that indicates how many
uppercase "B" characters there are in the string
Next, write a function countChar
Behaves liek countBs
takes 2 arguments
2nd argument indicates the character that needs to be counted
Rewrite countBs to make use of this new function
*/
//Original countBs
let countBs = word =>{
let beans = 0;
for (var i = 0; i < word.length; i++) {
if (word[i] == 'B')
beans++;
}
return beans;
}
//countChar function
let countChar = (word, char) =>{
let result = 0;
for (var i = 0; i < word.length; i++) {
if (word[i] == char)
result++;
}
return result;
}
//countBs Modded
let countBs = word =>{
return countChar(word, "B");
}
Min Function:
function min(x,y) {
if (x<y)
return (x);
else
return (y);
}
var answer = min(2,9);
alert(answer);
Recursion Function:
function isEven(num) {
if (num == 0) return "Even";
if (num == 1) return "Odd";
if (num < 0) return "Number is not a positive integer!";
return isEven(num - 2);
}
console.log(isEven(75));
console.log(isEven(50));
Bean Counting Function:
function countBs(z){
return countChar(z, “B”);
}
function countChar(word, char){
let count = 0;
for(var i = 0; i < word.length; i++){
if(char == word[i]) count++;
}
return count;
}
console.log(countBs("Dave n Busters!"));
console.log(countBs("Bilbo Bbbaggins!", 'i'));
Minimum:
<script>
// WRITE EXERCISE MINIMUM
var num1 = 10;
var num2 = 11;
function minime(x, y) {
if (x<y) {
return x;
}else if (x>y) {
return y;
}else {
return "Same number";
}
}
document.write("<h1>Min(" + num1 + "," + num2 + "): " + minime(num1, num2) + "<h1>");
</script>
// WRITE EXERCISE RECURSION
var number = prompt("Number please:");
var msj = isEven(number);
document.write(msj);
function isEven(x) {
if (x == 0) {
return ("Even");
}else if (x == 1) {
return ("Odd");
}else if (x < 0) {
return isEven(-x);
}else {
return isEven(x - 2);
}
}
- An example of a table of rows with people and their ages, in this case we are after the person who is the youngest.
Var rows = getAllRows();
var rowMinAge = _.Min(rows, getAge);
Console.log (rowMinAge.innerHTML);
Int SumEvenDigits (Int number) { //base case if ( number = 0 ) return 0 ' if ( number % 2 == 0 ) return number % 10 + sumEvenDigits (number/10 else return sumEvenDigits (number/10) }``Preformatted text
Can i have some help how this works. Im on YouTube trying to figure it out as the book hasn’t been much help to me so far unfortunately. I need to impalement it in a real world scenario.
- `function CountBs(string) {
// Create a result, set to 0
// Loop over the string
// If current character is a “B”
- An example of a table of rows with people and their ages, in this case we are after the person who is the youngest.
Var rows = getAllRows();
var rowMinAge = _.Min(rows, getAge);
Console.log (rowMinAge.innerHTML);
Int SumEvenDigits (Int number) { //base case if ( number = 0 ) return 0 ' if ( number % 2 == 0 ) return number % 10 + sumEvenDigits (number/10 else return sumEvenDigits (number/10) }``Preformatted text
Can i have some help how this works. Im on YouTube trying to figure it out as the book hasn’t been much help to me so far unfortunately. I need to impalement it in a real world scenario.
`function CountBs(string) {
// Return a call to counChar with input and "B"
return countChar(string, ' B');
}
function countChar(string, character) {
// Create a result, set to 0
let result = 0;
// Loop over the string
for (let i - 0; i <= string. length; i++) {
// If current character matches input character
if (string === character ) {
// Increment our result by 1
result = result + 1;
}
// return result
return result;
}
}
// return result;
}
function countChar(string, character) {
// WORKING HERE
}
console.log(countBs(2"BBCBBBCBBBBBC"))
// > 2
Console.log (CountChar("kakkerlak", "k"));
// > 4
This is just too much for my ability. Taking far too much time on thi sJS Course. Not enjoying it at all.
Having trouble devising my own solutions at this stage, but can follow other people’s solutions.
// Minimum Number
function minNum(numX,numY){
return Math.min(numX,numY);
}
console.log(“The smallest number is >> " + minNum(83,91) +”\n");
console.log("… >> " + minNum(17,76));
// Recursion
//numbers < 0 return false because isEven cannot determine even/odd for negative numbers; the result and solution is confusing to me.
var n1 = 50; n2 = 75;
function isEven(n) {
if (n == 0) return true;
else if (n == 1) return false;
else if (n < 0) return isEven(-n);
else return isEven(n - 2);
}
console.log(isEven(n1)); //true
console.log(isEven(n2)); //false
console.log(isEven(-1)); //false
//Bean Counting
function countChar(string, ch) {
let counted = 0;
for (let i = 0; i < string.length; i++) {
if (string[i] == ch) {
counted += 1;
}
}
return counted;
}
function countBs(string) {
return countChar(string, “B”);
}
console.log(countBs(“BoBBy”));
// → 3
console.log(countChar(“statuette”, “t”));
// → 4
console.log(countChar(“Possessionlessnesses”, “s”));
// → 9
I have serious issue with my console and needs to clarify. This is pissing me off.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
function greet(name){
console.log(greet);
}
greet('Azeez');
</script>
</body>
</html>
I want to believe that my script is very correct but my output on the console always look like
HTML1300: Navigation occurred.
Function.html (1,1)
function greet(name){
console.log(greet);
}
Function.html (9,2)****strong text
Please i need help
Without looking at the answers… Is anyone able to figure it out on their own the answers to the exercises?
Thanks Nick