Skip to content
Learn javascript using boscode https://www.npmjs.com/package/boscode
JavaScript HTML Other
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.vs/config
code
images
.editorconfig
.eslintrc.js
.gitignore
.jshintrc
LICENSE
README.md
boscode-learn.njsproj
boscode-learn.sln
package-lock.json
package.json

README.md

Learn pseudocode with javascript compliant with Board of studies, New South Wales, Australia, Software Design and Development Stage 6, Software and Course Specifications Higher School Certificiate 2012

See also boscode.

Table of Content

Installation
Useful bash terminal commands

Example code
01 Console output: Display
02 Console input: Get
03 Creating a sequential file
04 Printing the contents of a file using sentinel value
05 Printing the contents of a file using EOF (end of file)
06 Appending rows to an existing sequential file
07 Creating a relative file
08 Reading from a relative file
09 Updating records in a relative file

Tasks
01 Variables
02 Strings
03 String length
04 Revising strings
05 Numbers
06 Rounding numbers
07 Number to string
08 If statement
09 For loop
10 Arrays
11 Array filtering
12 Accessing array values
13 Looping through arrays
14 Objects
15 Object properties
16 Functions
17 Function arguments
18 Sum
19 Highindex
20 Binary sum
21 Integer addition
22 Comparing strings
23 Digit sum
24 Highest digit
25 Test length
26 How many e's
27 Camel case
28 Valid 24 hours
29 AM & PM
30 Word index
31 Sorted index
32 Formatted index
33 Length conversion
34 Highest Integer
35 Multiple words
36 Odd numbers
37 Vowels
38 Bar code
39 Runs
40 Printing numbers
41 Average
42 Counting $
43 Words and characters
44 Kaprekar Numbers
45 Digital Roots
46 Plurals
47 Team Counts
48 Staircases
49 Two-up
50 Rank Generator
51 Range check
52 Grade
53 Repeat the character
54 Group bits
55 Peasant multiplication
56 Two words
57 Sum all between
58 Number words
59 Count special characters
60 Replace the second character
61 Sixty Four Doors
62 Goonerism Spenerator
63 Partitions
64 Murlin
65 Math input
66 Word times
67 Binary left shift
68 Binary inverse
69 Averages
70 Newton Raphson
71 Human Time
72 Traffic
73 Three strings
74 Ascii border
75 Crosses and Noughts
76 Random grid
77 Storing dates
78 Uppercase
79 Integers continued
80 Total capitals
81 Triangular numbers
82 Letter Word Game
83 Daily step targets
84 Rats
85 Queue Jumpers
86 Inheritance
87 Lowest of three
88 Repeat the string
89 Lower to Uppercase
90 Product of fractions
91 Buckets
92 Suffixes

Codecademy Tasks
codecademy tasks

Arduino Tasks
arduino tasks

Electron Tasks
electron tasks

Object oriented paradigm
1 Object oriented paradigm

Google Apps Script Tasks
Google Apps Script Tasks

Web tasks
Web tasks

LibreOffice

LibreOffice tasks

Installation

  1. Install nodejs https://nodejs.org/en/download/ and Visual Studio Code https://code.visualstudio.com/download

  2. Download boscode-learn zip file

    Mac https://github.com/Quobject/boscode-learn/releases/download/1.0.5/boscode-learn_1.0.5_Mac.zip. Unzip into a new folder /code/boscode-learn

    Windows https://github.com/Quobject/boscode-learn/releases/download/1.0.5/boscode-learn_1.0.5_Win.zip. Unzip into a new folder C:\code\boscode-learn

  3. Open Visual Studio Code

  4. File -> Open Folder ...

  • select C:\code\boscode-learn
  1. View -> Integrated Terminal

  2. Change directory into C:\code\boscode-learn

Useful bash terminal commands

  • pwd:
{yourname}:~/workspace (master) $ pwd
/home/ubuntu/workspace

print working directory

  • ll:
{yourname}:~/workspace (master) $ ll
total 64
drwxr-xr-x  7 ubuntu ubuntu 4096 Jan 21 01:57 ./
drwxr-xr-x 21 ubuntu ubuntu 4096 Jan 21 01:57 ../
drwxr-xr-x  3 ubuntu ubuntu 4096 Jan 21 01:56 .c9/
-rw-r--r--  1 ubuntu ubuntu  208 Jan 21 01:56 .editorconfig
drwxr-xr-x  8 ubuntu ubuntu 4096 Jan 21 01:56 .git/
-rw-r--r--  1 ubuntu ubuntu 4290 Jan 21 01:56 .gitignore
-rw-r--r--  1 ubuntu ubuntu  249 Jan 21 01:56 .jshintrc
drwxr-xr-x  4 ubuntu ubuntu 4096 Jan 21 01:56 .vs/
-rw-r--r--  1 ubuntu ubuntu 1075 Jan 21 01:56 LICENSE
-rw-r--r--  1 ubuntu ubuntu 2284 Jan 21 01:56 README.md
-rw-r--r--  1 ubuntu ubuntu 3850 Jan 21 01:56 boscode-learn.njsproj
-rw-r--r--  1 ubuntu ubuntu  971 Jan 21 01:56 boscode-learn.sln
drwxr-xr-x  3 ubuntu ubuntu 4096 Jan 21 01:56 code/
drwxr-xr-x  3 ubuntu ubuntu 4096 Jan 21 01:57 node_modules/
-rw-r--r--  1 ubuntu ubuntu  621 Jan 21 01:56 package.json

list files

Example code

01 Console output: Display

  1. Open Visual Studio Code. In the file tree open the folder: code/examples/01
  2. Double click the file app.js inside this folder. Observe the code:
var boscode = require('boscode');

boscode.display('Hello world');

boscode.display('The answer is ', 4, 'km');
  1. Right click the file app.js and choose Open Terminal Here.
  2. Type ll to see the content of the current directory:
{yourname}:code/examples/01 (master) $ ll
total 12
drwxr-xr-x  2 ubuntu ubuntu 4096 Jan 21 01:56 ./
drwxr-xr-x 11 ubuntu ubuntu 4096 Jan 21 01:56 ../
-rw-r--r--  1 ubuntu ubuntu  115 Jan 21 01:56 app.js
  1. Type node app.js to run this code:
{yourname}:code/examples/01 (master) $ node app.js 
Hello world
The answer is 4km
  1. Follow similar procedure to see/run the other code examples.

See also: https://github.com/Quobject/boscode#display

02 Console input: Get

Pseudocode

Get firstNumber

Javascript

var firstNumber = boscode.get();

In Visual Studio Code run the file app.js code/examples/02/app.js.

03 Creating a sequential file

Pseudocode

BEGIN CreateASequentialFile
  Open FriendsData for output

  firstName = "Joe"
  lastName = "Bloggs"
  emailAddress = "jbloggs@example.com"

  Write FriendsData from firstName, lastName, emailAddress

  firstName = "Jim"
  lastName = "Doe"
  emailAddress = "jdoe@example.com"

  Write FriendsData from firstName, lastName, emailAddress

  Close FriendsData
END CreateASequentialFile


Javascript

var createASequentialFile = function () {
  var friendsData = boscode.open('friendsData.txt', 'output');

  var firstName = 'Joe';
  var lastName = 'Bloggs';
  var emailAddress = 'jbloggs@example.com';

  var row = [firstName, lastName, emailAddress].join(','); // creates a comma separated string

  friendsData.write(row);  

  firstName = 'Jim';
  lastName = 'Doe';
  emailAddress = 'jdoe@example.com';

  row = [firstName, lastName, emailAddress].join(','); // creates a comma separated string

  friendsData.write(row);

  friendsData.close();
};

// content of friendsData.txt:
// Joe,Bloggs,jbloggs@example.com
// Jim,Doe,jdoe@example.com

In Visual Studio Code run the file
app.js code/examples/03/app.js.

04 Printing the contents of a file using sentinel value

Pseudocode

BEGIN DisplayFileContents
  Open FriendsData for input

  Read firstName, lastName, emailAddress from FriendsData
  ’This is a priming read, performed just before entering the loop to provide
  'the first record (if there is one) for printing

  WHILE firstName <> “xxx”
    Display firstName, lastName, emailAddress
    Read firstName, lastName, emailAddress from FriendsData
    ’this reads subsequent records which can then be tested for the sentinel
    'value before they are processed
  END WHILE

  Close FriendsData
END DisplayFileContents

Javascript

var displayFileContents = function () {
  var friendsData = boscode.open('friendsData.txt', 'input');

  var row = friendsData.read();
  var tempArray = row.split(',');
  var firstName = tempArray[0];
  var lastName = tempArray[1];
  var emailAddress = tempArray[2];

  while ( firstName !== 'xxx' ) {
    boscode.display(firstName, lastName, emailAddress);

    row = friendsData.read();
    tempArray = row.split(',');
    firstName = tempArray[0];
    lastName = tempArray[1];
    emailAddress = tempArray[2];
  }

  friendsData.close();
};

In Visual Studio Code run the file
app.js code/examples/04/app.js.

05 Printing the contents of a file using EOF (end of file)

Pseudocode

BEGIN DisplayFileContents
  Open FriendsData for input

  Read firstName, lastName, emailAddress from FriendsData
  ’This is a priming read, performed just before entering the loop to provide
  'the first record (if there is one) for printing

  WHILE not EOF
    Display firstName, lastName, emailAddress
    Read firstName, lastName, emailAddress from FriendsData
    ’this reads subsequent records which can then be tested for the sentinel
    'value before they are processed
  END WHILE

  Close FriendsData
END DisplayFileContents

Javascript

var displayFileContents = function () {
  var friendsData = boscode.open('friendsData.txt', 'input');

  var row = friendsData.read();

  var tempArray, firstName, lastName, emailAddress;

  while (row !== boscode.EOF) {
    tempArray = row.split(',');
    firstName = tempArray[0];
    lastName = tempArray[1];
    emailAddress = tempArray[2];
    boscode.display(firstName, lastName, emailAddress);

    row = friendsData.read();
  }

  friendsData.close();
};

In Visual Studio Code run the file
app.js code/examples/05/app.js.

06 Appending rows to an existing sequential file

Pseudocode

BEGIN AppendNewRows
  Open FriendsData for append

  Display “Please enter the details for the first new person to be added:”
  Display “Enter xxx for first name to indicate there are no more rows to be added.”

  Get firstName, lastName, emailAddress

  WHILE firstName <> “xxx”
    Write FriendsData from firstName, lastName, emailAddress

    Display “Please enter the details for the next new person to be added:”

    Get firstName, lastName, emailAddress
  END WHILE

  Close FriendsData
END AppendNewRows

Javascript

var appendNewRows = function () {
  var friendsData = boscode.open('friendsData.txt', 'append');

  boscode.display('Please enter the details for the first new person to be added:');
  boscode.display('Enter xxx for first name to indicate there are no more rows to be added.');

  var firstName = boscode.get('First Name:');
  var lastName = boscode.get('Last Name:');
  var emailAddress = boscode.get('Email Address:');
  var row = [firstName, lastName, emailAddress].join(',');

  while (firstName !== 'xxx') {

    friendsData.write(row);

    boscode.display('Please enter the details for the next new person to be added:');

    firstName = boscode.get('First Name:');
    lastName = boscode.get('Last Name:');
    emailAddress = boscode.get('Email Address:');
    row = [firstName, lastName, emailAddress].join(',');
  }

  friendsData.close();
};

In Visual Studio Code run the file
app.js code/examples/06/app.js.

07 Creating a relative file

Pseudocode

BEGIN CreateARelativeFile
  Open ProductData for relative access

  productNumber = 1
  description = "Laundry Liquid 2L"
  quantity = 100
  price = 1.49

  Write ProductData from productNumber, description, quantity, price using productNumber

  ’note the use of the variable productNumber as the key field, specifying where this record will be written in the file.

  productNumber = 2
  description = "Mate Laundry Liquid 1L"
  quantity = 300
  price = 3.99

  Write ProductData from productNumber, description, quantity, price using productNumber

  Close ProductData
END CreateARelativeFile

Javascript

var createARelativeFile = function () {
  var productData = boscode.open('productData.txt', 'relative_access');

  var productObject = {
    productNumber: 1,
    description: 'Laundry Liquid 2L',
    quantity: 100,
    price: 1.49
  };

  productData.write(productObject, 'productNumber');

  productObject = {
    productNumber: 2,
    description: 'Mate Laundry Liquid 1L',
    quantity: 300,
    price: 3.99
  };

  productData.write(productObject, 'productNumber');

  productData.close();
};

In Visual Studio Code run the file
app.js code/examples/07/app.js.

08 Reading from a relative file

Pseudocode

BEGIN ReadRecordsFromARelativeFile
  Open ProductData for relative access

  RequiredProdNumber = 1

  Read ProductData into productNumber, description, quantity, price using RequiredProdNumber
  ’note the use of the variable RequiredProdNumber as the key field, specifying where this record will be found in the file
  
  IF RecordNotFound THEN
    ’note the use of the flag RecordNotFound returned by the operating system 
    Display “Sorry – no such product”
  ELSE
    Display productNumber, description, quantity, price
  END IF
  
  Close ProductData
END ReadRecordsFromARelativeFile

Javascript

var readRecordsFromARelativeFile = function () {
  var productData = boscode.open('productData.txt', 'relative_access');

  var requiredProdNumber = 1;

  var productRecord = productData.read(requiredProdNumber);

  if (productRecord === boscode.RECORD_NOT_FOUND) {
    boscode.display('Sorry - no such product');
  } else {
    boscode.display( JSON.stringify(productRecord) );
  }    

  productData.close();
};

//{"productNumber":1,"description":"Laundry Liquid 2L","quantity":100,"price":1.49}

In Visual Studio Code run the file
app.js code/examples/08/app.js.

09 Updating records in a relative file

Pseudocode

BEGIN UpdateRecordsInARelativeFile
  Open ProductData for relative access

  RequiredProdNumber = 1

  Read ProductData into productNumber, description, quantity, price using RequiredProdNumber
  
  IF RecordNotFound THEN
    'note the use of the flag RecordNotFound returned by the operating system 
    Display “Sorry – no such product”
  ELSE
    Display productNumber, description, quantity, price
    newPrice = 1000

    Write ProductData from productNumber, description, quantity, newPrice using productNumber
    'update record using data for the new price and the existing data in the other fields

  END IF
  
  Close ProductData
END UpdateRecordsInARelativeFile

Javascript

var updateRecordsInARelativeFile = function () {
  var productData = boscode.open('productData.txt', 'relative_access');

  var requiredProdNumber = 1;

  var productRecord = productData.read(requiredProdNumber);

  if (productRecord === boscode.RECORD_NOT_FOUND) {
    boscode.display('Sorry - no such product');
  } else {
    boscode.display(JSON.stringify(productRecord));
    productRecord.price = 1000;

    productData.write(productRecord, 'productNumber');
  }

  productData.close();
};

In Visual Studio Code run the file
app.js code/examples/09/app.js.

Tasks

01 Variables

A variable is a name that can reference a specific value. Variables are declared using var followed by the variable's name.

Here's an example:

var example;

The above variable is declared, but it isn't defined (it does not yet reference a specific value).

Here's an example of defining a variable, making it reference a specific value:

var example = 'some string';
NOTE

A variable is declared using var and uses the equals sign to define the value that it references. This is colloquially known as "Making a variable equal a value".

The challenge:

In Visual Studio Code edit the file code/tasks/01/app.js.

In that file declare a variable named example.

Make the variable example equal to the value 'some string'.

Then use boscode.display() to print the example variable to the console.

Check to see if your program is correct.


02 Strings

A string is any value surrounded by quotes.

It can be single or double quotes:

'this is a string'

"this is also a string"
NOTE

Try to stay consistent. In this workshop we'll only use single quotes.

The challenge:

In Visual Studio Code edit the file code/tasks/02/app.js.

In that file declare a variable named someString:

var someString = 'this is a string';

Use boscode.display() to print the variable someString to the terminal.

Check to see if your program is correct.


03 String length

You will often need to know how many characters are in a string.

For this you will use the .length property. Here's an example:

var example = 'example string';
example.length

NOTE

Make sure there is a period between example and length.

The above code will return a number for the total number of characters in the string.

The challenge:

In Visual Studio Code edit the file code/tasks/03/app.js.

In that file, create a variable named example.

Assign the string 'example string' to the variable example.

Use boscode.display() to print the length of the string to the terminal.

Check to see if your program is correct.


04 Revising strings

You will often need to change the contents of a string.

Strings have built-in functionality that allow you to inspect and manipulate their contents.

Here is an example using the .replace() method:

var example = 'this example exists';
example = example.replace('exists', 'is awesome');
boscode.display(example);

Note that to change the value that the example variable references, we need
to use the equals sign again, this time with the example.replace() method to
the right of the equals sign.

The challenge:

In Visual Studio Code edit the file code/tasks/04/app.js.

Define a variable named pizza that references this string: 'pizza is alright'

Use the .replace() method to change alright to wonderful.

Use boscode.display() to print the results of the .replace() method to the terminal.

Check to see if your program is correct.


05 Numbers

Numbers can be integers, like 2, 14, or 4353, or they can be decimals,
also known as floats, like 3.14, 1.5, or 100.7893423. Unlike Strings, Numbers do not need to have quotes.

The challenge:

In Visual Studio Code edit the file code/tasks/05/app.js.

In that file define a variable named example that references the integer 123456789.

Use boscode.display() to print that number to the terminal.

Check to see if your program is correct.


06 Rounding numbers

We can do basic math using familiar operators like +, -, *, /, and %.

For more complex math, we can use the Math object.

In this challenge we'll use the Math object to round numbers.

The challenge:

In Visual Studio Code edit the file code/tasks/06/app.js.

In that file define a variable named roundUp that references the float 1.5.

We will use the Math.round() method to round the number up. This method rounds either up or down to the nearest integer.

An example of using Math.round():

Math.round(0.5);

Define a second variable named rounded that references the output of the Math.round() method, passing in the roundUp variable as the argument.

Use boscode.display() to print that number to the terminal.

Check to see if your program is correct.


07 Number to string

Sometimes you will need to turn a number into a string.

In those instances you will use the .toString() method. Here's an example:

var n = 256;
n = n.toString();

The challenge:

In Visual Studio Code edit the file code/tasks/07/app.js.

In that file define a variable named n that references the number 128;

Call the .toString() method on the n variable.

Use boscode.display() to print the results of the .toString() method to the terminal.

Check to see if your program is correct.


08 If statement

Conditional statements are used to alter the control flow of a program, based on a specified boolean condition.

A conditional statement looks like this:

if (n > 1) {
  boscode.display('the variable n is greater than 1.');
} else {
  boscode.display('the variable n is less than or equal to 1.');
}

Inside parentheses you must enter a logic statement, meaning that the result of the statement is either true or false.

The else block is optional and contains the code that will be executed if the statement is false.

The above javascript code in pseudocode (see also):

IF n > 1 THEN
  Display "the variable n is greater than 1."
ELSE
  Display "the variable n is less than or equal to 1."
ENDIF

The challenge:

  1. In Visual Studio Code edit the file code/tasks/08/app.js.

In that file, declare a variable named fruit.

Make the fruit variable reference the value orange with the type of String.

Then use boscode.display() to print "The fruit name has more than five characters." if the length of the value of fruit is greater than five. Otherwise, print "The fruit name has five characters or less."

Check to see if your program is correct.

  1. In Visual Studio Code edit the file code/tasks/08/pseudocode.txt.

In this file write your javascript solution as pseudocode. Note: Assume LENGTH( varName ) exists that returns the number of characters of a string variable.


09 For loop

For loops allow you to repeatedly run a block of code a certain number of times. This for loop logs to the console ten times:

for (var i = 0; i < 10; i++) {
  // log the numbers 0 through 9
  boscode.display(i)
}

The first part, var i = 0, is run once at the beginning of the loop. The variable i is used to track how many times the loop has run.

The second part, i < 10, is checked at the beginning of every loop iteration before running the code inside the loop. If the statement is true, the code inside the loop is executed. If it is false, then the loop is complete. The statement i < 10; indicates that the loop will continue as long as i is less than 10.

The final part, i++, is executed at the end of every loop. This increases the variable i by 1 after each loop. Once i reaches 10, the loop will exit.

The above javascript code in pseudocode (see also):

FOR i = 1 TO 9 STEP 1
  Display i 
NEXT i

The challenge:

  1. In Visual Studio Code edit the file code/tasks/09/app.js.

In that file define a variable named total and make it equal the number 0.

Define a second variable named limit and make it equal the number 10.

Create a for loop with a variable i starting at 0 and increasing by 1 each time through the loop. The loop should run as long as i is less than limit.

On each iteration of the loop, add the number i to the total variable. To do this, you can use this statement (equivalent to total = total + i):

total += i;

After the for loop, use boscode.display() to print the total variable to the terminal.

Check to see if your program is correct.

  1. In Visual Studio Code edit the file code/tasks/09/pseudocode.txt.

In this file write your javascript solution as pseudocode.


10 Arrays

An array is a list of values. Here's an example:

var pets = ['cat', 'dog', 'rat'];

//or

var pets = [];

pets[0] = 'cat';
pets[1] = 'dog';
pets[2] = 'rat';

The above javascript code in pseudocode (see also):

pets(0) = "cat"
pets(1) = "dog"
pets(2) = "rat"

The challenge:
  1. In Visual Studio Code edit the file code/tasks/10/app.js.

In that file define a variable named pizzaToppings that references an array that contains three strings in this order: tomato sauce, cheese, pepperoni.

Use boscode.display() to print the pizzaToppings array to the terminal.

Check to see if your program is correct.

  1. In Visual Studio Code edit the file code/tasks/10/pseudocode.txt.

In this file write your javascript solution as pseudocode.


11 Array filtering

There are many ways to manipulate arrays.

One common task is filtering arrays to only contain certain values.

For this we can use the .filter() method.

Here is an example:

var pets = ['cat', 'dog', 'elephant'];

var filtered = pets.filter(function (pet) {
  return (pet !== 'elephant');
});

The filtered variable will now only contain cat and dog.

!== is a comparison operator (see w3schools).

The challenge:

In Visual Studio Code edit the file code/tasks/11/app.js.

In that file, define a variable named numbers that references this array:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

Like above, define a variable named filtered that references the result of numbers.filter().

The function that you pass to the .filter() method will look something like this:

function evenNumbers (number) {
  return number % 2 === 0;
}

Use boscode.display() to print the filtered array to the terminal.

Check to see if your program is correct.


12 Accessing array values

Array elements can be accessed through index number.

Index number starts from zero to array's property length minus one.

Here is an example:

var pets = ['cat', 'dog', 'rat'];

boscode.display(pets[0]);

The above code will print the first element of pets array - string cat.

The challenge:

In Visual Studio Code edit the file code/tasks/12/app.js.

In that file, define array food :

var food = ['apple', 'pizza', 'pear'];

Use boscode.display() to print the second value of array to the terminal.

Check to see if your program is correct.


13 Looping through arrays

For this challenge we will use a for loop to access and manipulate a list of values in an array.

Accessing array values can be done using an integer.

Each item in an array is identified by a number, starting at 0.

So in this array hi is identified by the number 1:

var greetings = ['hello', 'hi', 'good morning'];

It can be accessed like this:

greetings[1];

So inside a for loop we would use the i variable inside the square brackets instead of directly using an integer.

The challenge:

In Visual Studio Code edit the file code/tasks/13/app.js.

In that file, define a variable named pets that references this array:

['cat', 'dog', 'rat'];

Create a for loop that changes each string in the array so that they are plural.

You will use a statement like this inside the for loop:

pets[i] = pets[i] + 's';

After the for loop, use boscode.display() to print the pets array to the terminal.

Check to see if your program is correct.


14 Objects

Objects are lists of values similar to arrays, except values are identified by keys instead of integers.

Here is an example:

var foodPreferences = {
  pizza: 'yum',
  salad: 'gross'
};

The challenge:

In Visual Studio Code edit the file code/tasks/14/app.js.

In that file, define a variable named pizza like this:

var pizza = {
  toppings: ['cheese', 'sauce', 'pepperoni'],
  crust: 'deep dish',
  serves: 2
};

Use boscode.display(pizza) to print the pizza object to the terminal.

Check to see if your program is correct.


15 Object properties

You can access and manipulate object properties –– the keys and values that an object contains –– using a method very similar to arrays.

Here's an example using square brackets:

var example = {
  pizza: 'yummy'
};

boscode.display(example['pizza']);

The above code will print the string 'yummy' to the terminal.

Alternately, you can use dot notation to get identical results:

example.pizza;

example['pizza'];

The two lines of code above will both return yummy.

The challenge:

In Visual Studio Code edit the file code/tasks/15/app.js.

In that file, define a variable named food like this:

var food = {
  types: 'only pizza'
};

Use boscode.display() to print the types property of the food object to the terminal.

Check to see if your program is correct.


16 Functions

A function is a block of code that takes input, processes that input, and then produces output.

Here is an example:

var example = function (x) {
  return x * 2;
}

We can call that function like this to get the number 10:

example(5)

The above example assumes that the example function will take a number as an argument –– as input –– and will return that number multiplied by 2.

The challenge:

In Visual Studio Code edit the file code/tasks/16/app.js.

In that file, define a function named eat that takes an argument named food
that is expected to be a string.

Inside the function return the food argument like this:

return food + ' tasted really good.';

Inside of the parentheses of boscode.display(), call the eat() function with the string bananas as the argument.

Check to see if your program is correct.


17 Function arguments

A function can be declared to receive any number of arguments. Arguments can be from any type. An argument could be a string, a number, an array, an object and even another function.

Here is an example:

var example = function (firstArg, secondArg) {
  boscode.display(firstArg, secondArg);
}

We can call that function with two arguments like this:

example('hello', 'world');

The above example will print to the terminal hello world.

The challenge:

In Visual Studio Code edit the file code/tasks/17/app.js.

In that file, define a function named math that takes three arguments. It's important for you to understand that arguments names are only used to reference them.

Name each argument as you like.

Within the math function, return the value obtained from multiplying the second and third arguments and adding that result to the first argument.

After that, inside the parentheses of boscode.display(), call the math() function with the number 53 as first argument, the number 61 as second and the number 67 as third argument.

Check to see if your program is correct.


18 Sum

  1. In Visual Studio Code edit the file code/tasks/18/app.js. In that file, write a program that reads in two numbers from the console and adds them up. Print the result to the console.
  1. In Visual Studio Code edit the file code/tasks/18/pseudocode.txt. In this file write your javascript solution as pseudocode.

19 Highindex

  1. Review https://github.com/Quobject/boscode-learn#10-arrays.

  2. In Visual Studio Code edit the file code/tasks/19/app.js. Create a js function that takes highIndex as input parameter and creates an array of integers 0 - highIndex that has every value set to its index. Call the function and display the result to the console.

  3. In Visual Studio Code edit the file code/tasks/19/pseudocode.txt. In this file write your javascript solution as pseudocode.


20 Binary sum

  1. Review: https://github.com/Quobject/boscode#printing-the-contents-of-a-file-using-eof-end-of-file

  2. In Visual Studio Code edit the file code/tasks/20/app.js. In this file write a program that reads a text file containing strings made up of zeroes and ones and outputs to the console. The program counts the number of ones per line and outputs the input - result.

Hint: You might find the JavaScript String split() Method http://www.w3schools.com/jsref/jsref_split.asp useful.

Example:

Input Output
0011 0011 - 2
0101010 0101010 - 3
01 01 - 1
00000000 00000000 - 0
1111 1111 - 4

21 Integer addition

The parseInt() function parses a string and returns an integer http://www.w3schools.com/jsref/jsref_parseint.asp.

  1. Review the JavaScript String split() Method http://www.w3schools.com/jsref/jsref_split.asp.

  2. In Visual Studio Code edit the file code/tasks/21/app.js. Write a program that reads a text file containing lines of two numbers and a plus character in the middle. The program should add the two numbers (as integers not strings) and print the input, = and the result to the console.

Example:

Input Output
1+1 1+1=2
99+2 99+2=101
1000+0 1000+0=1000

22 Comparing strings

  1. JavaScript Comparison and Logical Operators: read through the information provided at http://www.w3schools.com/js/js_comparisons.asp, especially Comparing Different Types.

  2. In Visual Studio Code edit the file code/tasks/22/app.js. In that file write a program that reads in two strings from the console and prints out the string that is alphabetically higher (e.g. B is higher than A)

Example:

Input Output
abc
def
def
A
a
a
node
javascript
node
  1. In Visual Studio Code edit the file code/tasks/22/pseudocode.txt. In this file write your javascript solution as pseudocode.

23 Digit sum

  1. Review the JavaScript String split() Method http://www.w3schools.com/jsref/jsref_split.asp and also parseInt http://www.w3schools.com/jsref/jsref_parseint.asp

  2. In Visual Studio Code edit the file code/tasks/23/app.js. In that file write a program that reads a text file containing lines of digits. For each line the program should add up all digits and show the result to the console.

Example:

Input Output
11 2
10000 1
123 6

24 Highest digit

  1. Review Find maximum value in an array.

  2. In Visual Studio Code edit the file code/tasks/24/app.js. In that file write a program that reads in a line of digits from the console. The program should print out the highest digit to the console.

Example:

Input Output
0000 0
10000 1
1230 3
43216 6

25 Test length

  1. In Visual Studio Code edit the file code/tasks/25/app.js. In that file write a program that reads in two lines from the console. The first input should be an integer indicating a length l. The second input should be a word. If the length of the word is less or equal to l then the output should be OK. If the length of the word is greater than l then the output should be TOO LONG.

  2. In Visual Studio Code edit the file code/tasks/25/pseudocode.txt. In this file write your javascript solution as pseudocode.

Example:

Input Output
5
cat
OK
5
kangaroo
TOO LONG
___

26 How many e's

  1. Review the JavaScript String substring() Method: http://www.w3schools.com/jsref/jsref_substring.asp

  2. In Visual Studio Code edit the file code/tasks/26/app.js. In that file write a program that reads in words from a text file, one word per line. If the word contains the letter a, the first part of the output should be a-yes otherwise it should be a-no. The second part of the output should count how many times the letter e occurs. Every word has only lowercase letters.

Example:

Input Output
text
many
reads
weather
a-no e-1
a-yes e-0
a-yes e-1
a-yes e-2

27 Camel case

CamelCase (also camel caps or medial capitals) is the practice of writing compound words or phrases such that each word or abbreviation begins with a capital letter. Camel case may start with a capital or, especially in programming languages, with a lowercase letter.

In Visual Studio Code edit the file code/tasks/27/app.js. In the file write a program that converts strings to camel case. Read in rows of words from a text file. Each row convert to camel case and print to the console.

Example:

Input Output
Foo Bar fooBar
convert to camel case convertToCamelCase

28 Valid 24 hours

In Visual Studio Code edit the file code/tasks/28/app.js. The 24-hour system of time uses four digits to represent a time to the nearest minute between midnight (0000) and one minute to midnight on the same day (2359). Write a program that reads 4-digit numbers from a text file and checks if the number is a valid time. The output should be to the console.

Example:

Input Output
0509 Valid time
0661 Invalid time
2609 Invalid time
1125 Valid time

29 AM & PM

In Visual Studio Code edit the file code/tasks/29/app.js. The 24-hour system of time uses four digits to represent a time to the nearest minute between midnight (0000) and one minute to midnight on the same day (2359). Write a program that reads 4-digit numbers from a text file and checks if the time is before or after noon. Print AM or PM to the console.

Example:

Input Output
0509 AM
0621 AM
2309 PM
1259 PM
1300 PM

30 Word index

In Visual Studio Code edit the file code/tasks/30/app.js. In that file write a program that generates a simple index from a list of words from a text file, one per line. The index shows each word and the position of the word in the list, counting from 1. Print the index to the console.

Example:

Input Output
Time
flies
like
an
arrow
but
fruit
flies
like
a
banana
Groucho
Marx
Time 1
flies 2
like 3
an 4
arrow 5
but 6
fruit 7
flies 8
like 9
a 10
banana 11
Groucho 12
Marx 13

31 Sorted index

  1. Review array sort and also http://stackoverflow.com/a/9645447/1109316.

  2. Same task as task 30 Word index i.e. write a program that generates a simple index from a list of words from a text file, one per line. The index shows each word and the position of the word in the list, counting from 1.

  3. In Visual Studio Code edit the file code/tasks/31/app.js. New in this task: the index should be sorted by word (case-insensitive).

Example:

Input Output
Time
flies
like
an
arrow
but
fruit
flies
like
a
banana
Groucho
Marx
a 10
an 4
arrow 5
banana 11
but 6
flies 2
flies 8
fruit 7
Groucho 12
like 3
like 9
Marx 13
Time 1

32 Formatted index

  1. Same task as task 31 Sorted index i.e. write a program that generates a simple index from a list of words from a text file, one per line. The index shows each word and the position of the word in the list, counting from 1. The index should be sorted by word (case-insensitive).

  2. In Visual Studio Code edit the file code/tasks/31/app.js. New in this task: It must be formatted so the word and the position are separated by dots and the last character of the position number is in a fixed column.

Example:

Input Output
Time
flies
like
an
arrow
but
fruit
flies
like
a
banana
Groucho
Marx
a............10
an............4
arrow.........5
banana.......11
but...........6
flies.........2
flies.........8
fruit.........7
Groucho......12
like..........3
like..........9
Marx.........13
Time..........1
___

33 Length conversion

  1. Review the JavaScript String indexOf() Method http://www.w3schools.com/jsref/jsref_indexof.asp.

  2. In Visual Studio Code edit the file code/tasks/33/app.js. In that file write a program that converts distances given in km, mm or cm into m. The program should read from the console and output to the console and stop if -1 is the input:

Example:

Input Output
1m
1m
1km
1000m
34cm
0.34m
900mm
0.9m
33km
33000m
-1

34 Highest Integer

  1. In Visual Studio Code edit the file code/tasks/34/app.js. In that file write a program that reads in three numbers from the console and prints out the highest number to the console.

  2. In Visual Studio Code edit the file code/tasks/34/pseudocode.txt. In this file write your javascript solution as pseudocode.

Examples:

Input Output
1
2
3
3
11
5
2
11

35 Multiple words

  1. In Visual Studio Code edit the file code/tasks/35/app.js. In that file write a program that reads in one number n and one string from the console. The program should print out n times the given string.

  2. In Visual Studio Code edit the file code/tasks/35/pseudocode.txt. In this file write your javascript solution as pseudocode.

Examples:

Input Output
1
hello
hello
3
world
world
world
world

36 Odd numbers

  1. In Visual Studio Code edit the file code/tasks/36/app.js. In that file write a program that produces a table containing numbers printed in three columns and several rows.
  • First column: the row number, starting at 1, then 2, 3, 4,
  • Second column: the corresponding odd number, starting at 1, then 3, 5, 7, ....
  • Third column: the sum of the numbers in column 2 up to and including that row. So the first row will show 1, then 1+3, then 1+3+5, ...
    The program should stop after the 15th row is displayed.
  1. In Visual Studio Code edit the file code/tasks/36/pseudocode.txt. In this file write your javascript solution as pseudocode.

Example:

1        1        1
2        3        4
3        5        ?
4        7        ?
5        9        ?  

37 Vowels

In Visual Studio Code edit the file code/tasks/37/app.js. In that file write a program that given a string, prints it out with the vowels (aeiouAEIOU) and spaces removed. The input needs to be read from a text file and the output should be the console.

Examples:

Input Output
Backwards Bckwrds
If at first you don't succeed... ftfrstydn'tsccd...
Aeiouuua

38 Bar code

Items purchased at supermarkets, bookshops and other retail outlets have a product bar code printed on the packaging. The bar code consists of lines of varying thickness, encoding a 13-digit product identifying number.

The number consists of four parts:

  • The first two digits represents a type code (93 is for Australian goods, 97 for books)
  • The next five digits is a manufacturer's identifying number (for example, 00652)
  • The next five digits is the product number assigned by the manufacturer (01091)
  • The last (thirteenth) digit is what is called a check digit.

The check digit is used to help detect if an error has occurred during scanning, or by someone incorrectly typing the number. It is chosen such that the sum of the digits in odd positions (the first, third, fifth and so on, including the check digit itself) plus three times the sum of the digits in the even positions is a multiple of 10. This means that if any one digit is misread as a different value, the sum will be inappropriate (not a multiple of 10) and the barcode can be rejected.

Example:

9300652010916

^ ^ ^ ^ ^ ^ ^ odd sum is 9+0+6+2+1+9+6 = 33

^ ^ ^ ^ ^ ^ even sum is 3+0+5+0+0+1 = 9


33 + 3\*9 = 60

and the number is valid since 60 mod 10 = 0.

In Visual Studio Code edit the file code/tasks/38/app.js. In that file write a program that reads in any number of bar codes and determines whether or not each is valid. The input consists of a sequence of lines, each containing a 13-digit number. The last line contains 13 zeroes to signal the end of input.

For each code, print the code and either the string "OK" or the string "INVALID". The input needs to be read from a text file and the output should got to the console.

Example:

Input Output
9300652010916
9300652040916
9315626000480
9780805300604
9780803500604
9781875932548
0000000000000
9300652010916 OK
9300652040916 INVALID
9315626000480 OK
9780805300604 OK
9780803500604 INVALID
9781875932548 INVALID

39 Runs

A run is a list of contiguous numbers that are either all increasing (ups) or all decreasing (downs). Up runs and down runs always alternate, and the last element of one run is the first of the next run.

In Visual Studio Code edit the file code/tasks/39/app.js. In that file write a program that counts the number of runs in several lists of numbers.

Examples:

Input Output
4 1 8 12 17 2
2 5 9 1
-4 -5 -2 0 1 0 3

You can assume that there are always at least three numbers. The input needs to be read from a text file and the output should go to the console.


40 Printing numbers

  1. In Visual Studio Code edit the file code/tasks/40/app.js. In that file write a program that reads in two numbers from the console and prints out every number between those two numbers including the two number to the console. You can assume the second number is always greater than the first.

  2. In Visual Studio Code edit the file code/tasks/40/pseudocode.txt. In this file write your javascript solution as pseudocode.

Input Output
1
2
1
2
1
3
1
2
3
5
10
5
6
7
8
9
10

41 Average

  1. In Visual Studio Code edit the file code/tasks/41/app.js. In that file write a program that, given a list of numbers calculates the average of those numbers. The list is terminated by a line containing -1 (sentinel value). Don't regard this value, it's there just to make it easy for you to tell that the list is finished. The input needs to be read from a text file and the output should go to the console.

  2. In Visual Studio Code edit the file code/tasks/41/pseudocode.txt. In this file write your javascript solution as pseudocode.

Examples:

Input Output
1
2
3
4
-1
2.5
3
5
7
2
-1
4.25
99.9
100.1
100.2
101.3
200
1000
-1
266.92

42 Counting $

In Visual Studio Code edit the file code/tasks/42/app.js. In that file write a program that reads a text file containing strings made up of #$%. The program counts the number of $ for each line.

Examples:

Input Output
#### 0
###%%%$ 1
$$$$$ 5

43 Words and characters

In Visual Studio Code edit the file code/tasks/43/app.js. In that file write a program that reads a text file containing words per line. The program should count the number of words and the number of characters for each line.

Examples:

Input Output
Hello world 2 words, 10 characters
Lorem ipsum dolor sit amet 5 words, 22 characters

44 Kaprekar Numbers

Mr D R Kaprekar (1905–1986), was an Indian schoolteacher and recreational mathematician. Among his many achievements is the discovery of a set of numbers with interesting properties that now bear his name.

Consider a positive integer k with n digits. Follow these steps:

  1. Square k.
  2. Split the result into two pieces, the last n digits and the rest.
  3. Add these pieces (if one is empty, treat as zero).
  4. If the sum is equal to k, then k is a Kaprekar number, otherwise it's not.

Example

1 and 45 are both Kaprekar numbers because

1*1 = 1 and 0 + 1 = 1
45*45 = 2025 and 20 + 25 = 45

but 123 is not since

123*123 = 15129 and 15 + 129 is not equal to 123

In Visual Studio Code edit the file code/tasks/44/app.js. In that file write a program that displays all the Kaprekar numbers less than 10000. A good solution is to write a function that tests an integer to see if it's a Kaprekar number, then use it in a loop that tries all possibilities. If your programming language doesn't support mixing integers and strings, you may need to use a built-in function to convert the number to a string so you can pick off the last n digits. (for javascript see e.g. JavaScript Number toString() Method).

If you've just started programming, for partial marks just write a program that reads a number, determines if it's a Kaprekar number or not, and displays a suitable message that includes the number. Test it, one at a time, with each of these numbers

45 673 272 2223 7381 7777 9998

45 Digital Roots

Numerologists ascribe certain magical properties to numbers, and in turn derive numbers from words or phrases. Nonsense like this can still provide an interesting computational exercise.

The two algorithms of interest to us are:

Given a positive integer N, add up the digits in its decimal representation. If that sum has more than one digit, add up its digits and so on until only a single digit remains. That's the digital root of N.

Given a phrase containing one or more words, assign a number to each letter equal to its position in the alphabet, so that a is 1, b is 2 and so on to z (26). Capital letters are counted the same as small letters, and non-letters are ignored. Now add up the values and reduce the sum to its digital root, which becomes the digital root of the phrase. This process is called gematria.

In Visual Studio Code edit the file code/tasks/45/app.js. In that file write a program that reads in up to 20 lines, preceded by the number of lines from a textfile. For each line, if it contains only a number, calculate and display the digital root, spaces and the number. If it's a phrase, calculate the letter sum, then display the digital root, the sum and the phrase, agsin separated by spaces. Input and calculated numbers are less than a billion and phases are shorter than 100 characters.

Example Input:

5
123
the quick brown fox
7823438
"640 K ought to be enough for anybody". Bill Gates, 1981.
Progcomp

Output:

6       123
4       211     the quick brown fox
8       7823438
1       406     "640 K ought to be enough for anybody". Bill Gates, 1981.
4       103     Progcomp

Test Data

You should test your program on the following data:

14
99999
10000
7
12345678
98765432
June
UNSW Progcomp Twenty-thirteen
the second figure thrice
"Tragedy is when I cut my finger,...
Comedy is when you walk into an open sewer and die" (attributed to Mel Brooks).
the thirty-sixth triangular number, declared the number of the beast
A Clockwork Orange, Stanley Kubrick: 3*114+1=343
(114 was Kubrick's signature code, it appears in four films as CRM114 or serum 114 or C-rm114.)
Nineteen associates attacked the World Trade Center in New York and the Pentagon in Washington.

46 Plurals

How many times has a computer told you something using phrases like these?

3 item(s) in your basket
1 message(s) in your inbox
0 day(s) to go

That's just lazy programming: the system knows exactly whether you have no items, one item or many items, so why can't it use the right words, like any five-year-old can?

To counter this insidious attitude of "Oh it's too much trouble, the user can work it out," this task produces the appropriate phrase based on quantity, assuming the noun isn't one of a number that form irregular plurals (leave that for another time).

Given a non-negative integer quantity Q and a word, the correct phrase to print is either

  • "no" and the plural of the word, if Q is zero;
  • "one" and the singular of the word, if Q is 1; or
  • the quantity as a decimal integer and the plural of the word, otherwise.

To form the plural of a word, use the following rules that cover common cases:

  • If the word ends in "s", "x", "z", "ch" or "sh", append "es";
  • If the word ends in "o" preceded by a consonant (that is, not "a", "e", "i", "o", "u" or "y" in this context), append "es";
  • If the word ends in "y" preceded by a consonant, remove the "y" and append "ies";
  • If the word ends in "fe" preceded by a letter other than another "f", remove the "fe" and append "ves";
  • If the word ends in "f" preceded by a letter other than another "f", remove the "f" and append "ves"; or
  • append "s" otherwise.

In Visual Studio Code edit the file code/tasks/46/app.js. In that file write a program that reads a quantity and word from each line of input from a textfle, separated by a space, and displays the appropriate phrase according to the rules above. The first input line contains the number of test cases that follow, which is a maximum of 30. Quantities are less than 10000 and no word is longer than 20 characters. Words are strictly in lower case.

Example

Input:

5
6 ferry
0 potato
1 camera
2 knife
243 box

Output:

6 ferries
no potatoes
one camera
2 knives
243 boxes

Test Data You should test your program on the following data:

27
1 caterpillar
101 dalmation
9999 cat
5 bee
0 computer
4 compass
2 bus
0 ibis
8 lynx
15 axe
15 ax
15 adze
4 waltz
7 church
3 wish
12 bath
8 potato
3 toe
6 embryo
6 kangaroo
5 whisky
3 kidney
52 handcuff
2 giraffe
3 dwarf
9 wife
4 handkerchief

47 Team Counts

The Progcomp 2011 rules state:

  • In addition to any number of teams of three, each high school will be allowed to register exactly ONE or TWO teams of 2 students.
  • A high school with a single outstanding student may register a team consisting only of that student, but only if no other team is registered from that school.

In Visual Studio Code edit the file code/tasks/47/app.js. In that file write a program that, given the number of participants a school has (1 or more), determines exactly how many teams of 3, teams of 2 and teams of 1 the school is allowed to register.

The first line of input to the program is the number of schools, followed by the number of participants for each school, each on a separate line. No other information is provided or needed.

The program should show the number of participants and how many teams of each size, using singular or plural terms as appropriate ("team" vs "teams"), and omitting mention of zero cases. Use the format shown below, including a comma to separate items and a full stop at the end. Marks are awarded both for computational correctness and following the format.

Example

Input:

4
7
9
2
1

Output:

7 participants = 1 team of 3, 2 teams of 2.
9 participants = 3 teams of 3.
2 participants = 1 team of 2.
1 participant = 1 team of 1.

Test Data

You should test your program on the following data:

9
3
22
1
8
120
121
4
5
2

Input from a textfile and output to the console.


48 Staircases

A certain integer sequence is constructed as follows: Start with the integer 1. Add 1 to it (giving 2), multiply the result by 1. Then add 2 to that, multiply by 2, add 3, multiply by 3 and so on.

The sequence thus begins

1  2  2  4  8  11  33  37  148...

Because you use the same factor to add and then multiply before incrementing it, let's call it the Staircase Sequence.

  1. In Visual Studio Code edit the file code/tasks/48/app.js. In that file write a program to print all values of the Staircase Sequence that are less than a million (1,000,000 or 10^6), one per line.

  2. In Visual Studio Code edit the file code/tasks/48/pseudocode.txt. In this file write your javascript solution as pseudocode.


49 Two-up

The traditional Australian gambling game of two-up can legally be played only on Anzac Day each year. Its rules are simple, especially in the limited form described here. One person, the Spinner, bets Heads (H) or Tails (T). He or she then throws two pennies up in the air. If the pennies land with one head showing and one tail showing, the result is called ODDS and the Spinner throws again. Otherwise the Spinner wins if the pennies (now both Heads or both Tails) match the bet they made, and loses otherwise.

If five ODDS are thrown in a row, the Spinner loses too.

In Visual Studio Code edit the file code/tasks/49/app.js. In that file write a program that scores this version of two-up. The input consists of several lines read from a textfile, each representing a throw, preceded by the number of throws. Each throw consists of a bet (H or T) followed by the result of the throw (two symbols, each H or T). The three letters are separated by a space.

The program should repeat the input and show the result of the throw on the same line. The result can be WIN, LOSE, ODDS or LOSE: 5 ODDS.

Example

Input:

9
T T H
T T T
H T T
H T H
H H T
H H T
H T H
H T H
T H H

Output:

T T H ODDS
T T T WIN
H T T LOSE
H T H ODDS
H H T ODDS
H H T ODDS
H T H ODDS
H T H LOSE: 5 ODDS
T H H LOSE

You can assume each line of input is a valid throw. Bets will only change after a win or loss.

Test Data You should test your program on the following data.

16
H H T
H T H
H H H
H T T
T H T
T H T
T T H
T H T
T T H
T T T
H T H
H T H
H H T
H H T
H T T
T H H

50 Rank Generator

In Visual Studio Code edit the file code/tasks/50/app.js. Given a list of scores, in order, write a program to generate a rank for each entry. An entry's rank is just its position in the sequence, starting at 1. If there are equal values, however, each of the equal values shares the same rank. This doesn't affect subsequent ranks. For example, here is a list of scores (in descending order) with the corresponding ranks written underneath:

134 109 109  104  94  94  94  67  42
1   2eq 2eq  4    5eq 5eq 5eq 8   9

The input format has one score per line. There is no formal limit to the number of values.

  • A score is a non-negative integer or real number. There will be at most 3 decimal places.
  • The list is terminated by a line containing -1. Don't rank this value, it's there just to make it easy for you to tell that the list is finished.
  • Valid numbers in the list are in descending order (each smaller than or equal to the previous, except for the first).
  • Equal values may have a different representation, such as 12 and 12.00.
  • The program's output should be a copy of the input, with each value followed by spaces and the rank. Non-equal ranks are positive integers; equal ranks have the common rank with eq appended.
  • You can reformat the value if you like, as long as the numeric value is apparent.
  • If a value is out of order (greater than the preceding valid value), show its rank as "--" and then ignore this value completely (that is, assume it didn't exist).

You may assume that all numbers are well-formed (legal integer or real format).

Test Data

You should test your program on the following examples.

Test 1 (all valid data)

100
100
99
98.5
98.4
98.40
98.4
98.399
97.1
92
92
92
92
0.000
0
-1

Test 2 (some out of order)

1243
1234
1243
1243
1243
1234
1234
1233
1222
1211
1233
1234
1222
1211
1211
1210
-1

Input should be from a textfile and output to the console.


51 Range check

In Visual Studio Code edit the file code/tasks/51/app.js. Write a node.js JavaScript program that reads words from the console. When the length of the word is less equal 3, the program should display the string “too short”, and when the length of the word is greater equals 10, the program should display the string “too long”. If the word length is greater 3 and less than 10 the output should be “ok”.

Example

Input:

a
word
Password12345

Output:

too short
ok
too long

52 Grade

In Visual Studio Code edit the file code/tasks/52/app.js. 2. Write a node.js JavaScript that reads from a text file. The text file contains rows of numbers each between 0 and 100. For every row the program should output the number, a dash “ - “ and a grade: A (for number >= 90), B (for number >= 70 and number < 90), and C (for number < 70).

Example

Input:

99
32
57
87
90

Output:

99 – A
32 – C
57 – C
87 – B
90 - A

53 Repeat the character

In Visual Studio Code edit the file code/tasks/53/app.js. 3. Write a node.js JavaScript program that reads input from a text file. The file contains rows each with a character and a non-negative number separated by a space. The output should show the character repeated n times, where n is the number.

Example

Input:

# 3
# 4
# 5
# 4
# 3
@ 1
@ 0
% 10

Output:

###
####
#####
####
###
@

%%%%%%%%%%

54 Group bits

In Visual Studio Code edit the file code/tasks/54/app.js. 4. Write a node.js JavaScript program that reads from a text file. The text file contains rows of strings containing 0 and 1. For each row the program should group the input into groups of 8 each group separated by a space. If the number of characters is not a multiple of 8 the program should fill up with zeros from the left.

Example

Input:

1010
111110000
10101010111101010101 

Output:

00001010
00000001 11110000
00001010 10101111 01010101

55 Peasant multiplication

In Visual Studio Code edit the file code/tasks/55/app.js. 5. Peasant multiplication is an ancient method of multiplication which does not require people to memorise their times tables. The algorithm for peasant multiplication is somewhat similar to that used by modern computers to perform binary multiplication and division. Here is an example of peasant multiplication used to calculate 13 times 14 (which gives the result 182).

example of peasant multiplication

Write a node.js JavaScript program that implements the peasant multiplication. The program should read from the console.

Example 1

Input:

13
14

Output:

182

Example 2

Input:

12
14

Output:

168

56 Two words

In Visual Studio Code edit the file code/tasks/56/app.js. Write a program that reads in two words from the console and prints out both words ordered by the length of the words with the longest word first. If both words have the same length then the first word should be printed first

Example 1

Input:

first
second

Output:

second first

Example 2

Input:

short
long

Output:

short long

Example 3

Input:

same
four

Output:

same four

57 Sum all between

In Visual Studio Code edit the file code/tasks/57/app.js. Write a program that reads in two numbers from the console and sums up all numbers that are in between those two numbers including both numbers.

You can assume the second number is always greater than the first.

Examples:

Example 1

Input:

1
2

Output:

3

Example 2

Input:

1
3

Output:

6

Example 3

Input:

5
10

Output:

45

58 Number words

In Visual Studio Code edit the file code/tasks/58/app.js. Write a program which, given a number between 1 and 20 prints out the number as a word. The input needs to be read from a text file. To get full marks your solution should be elegant (use of arrays, loop…).

You can assume the second number is always greater than the first.

Examples:

Input Output
1 one
11 eleven
19 nineteen
4 four

59 Count special characters

In Visual Studio Code edit the file code/tasks/59/app.js. Write a program that reads a text file containing strings made up of the three characters #$%. For each line the program counts how many times each character occurs.

Examples:

Input Output
#### #:4 %:0 $:0
###%%%$ #:3 %:3 $:1
$$$$$ #:0 %:0 $:5

60 Replace the second character

In Visual Studio Code edit the file code/tasks/60/app.js. Write a program that reads a text file containing words per line. The program should replace every second character of each word with ‘_’.

Examples:

Input Output
Hello world H_llo w_rld
Lorem ipsum L_rem i_sum
dolor sit amet D_lor s_t a_et

61 Sixty four Doors

In a monastery in a faraway country there is a chamber with 64 doors numbered 1 to 64. Every year the 64 monks that live in the monastery participate in the following ritual.

All doors in the chamber are initially closed. Each monk is assigned a unique integer between 1 and 64. The monks then enter the chamber one at a time, in numeric order (though that doesn't affect the outcome). If a monk is assigned the integer k, he changes the state of every k-th door. That is, if the door is closed he opens it and if it's open he closes it.

So the first monk changes every door (from closed to open), the second changes doors #2, #4, #6 etc, the third changes #3, #6, #9 etc, and so on until the last monk, who just changes #64.

At the end of the ritual the doors that are currently open lead to (spiritual) treasures, so their numbers are significant.

In Visual Studio Code edit the file code/tasks/61/app.js.

Write a program that simulates the ritual and displays the numbers of the doors that are open at the end, on one line.


62 Goonerism Spenerator

Spoonerisms are phrases where the non-vowel prefixes of non-trivial words are mixed up. For example, "a crushing blow" might become "a blushing crow". They are named after the Reverend William Spooner (1844–1930), an Oxford lecturer whose tongue (it is said) could never keep up with his thought processes.

The spoonerism generator to be written to solve this task must follow certain rules.

  1. Each input phrase consists of words in lower case separated by a space.
  2. Trivial words are unchanged (see list below).
  3. Words starting with a vowel (a e i o u) are unchanged.
  4. The prefix of each word starting with a non-vowel replaces the prefix in the next word to its right that has a prefix, with the last prefix replacing the first. A prefix consists either of all initial non-vowels or the special prefix "qu".

For the purposes of this task, trivial words are words with 2 or fewer letters, or any of the following:

for has have she that the this will with
"for", "has", "have", "she", "that", "the", "this", "will", "with"

The quoted list may be suitable to copy to your program.

Your task

In Visual Studio Code edit the file code/tasks/62/app.js. Write a program that reads in phrases from a text file and displays the corresponding spoonerisms. The first line of input contains the number of phrases (up to 20). The remaining lines have one phrase each. Each phrase has between 1 and 25 words, and a total length of up to 100 characters.

Examples:

4
bouncing tree
a blushing crow
we will have the flags hung out
the three little pigs and the big bad wolf

produces...

trouncing bee
a crushing blow
we will have the hags flung out
the wee thrittle ligs and the pig bad bolf

Test data

Test your program using the following input text.

18
belly jeans
bat flattery
flutter by
pop corn
this is the fun part
my spoonerism generator
a lack of pies
go and take a shower
i hate with my mind
pain in the posterior
anthropomorphism 
hickory dickory dock
the rain in spain falls mainly on the plain
pack my box with frumpy dozen lusty jugs
strange women lying in ponds distributing swords is no basis for a system of government
this caged parrot is no more
the quick brown fox jumps over the lazy dog
back home after jiving she expired with quizzicality

63 Partitions

A partitioning algorithm rearranges a list of values into contiguous groups that have similar properties. The boundary between adjacent groups is called a partition. The partitioning algorithm to be developed for this task moves negative elements to the left of the array, moves positive elements to the right of the array, and moves zero elements to the middle. Within the three partitioned groups the order of values doesn't matter (this is not a sorting algorithm on its own). Partitioning is trivial if an additional array is used, but the problem is more interesting if only scalar (single element) variables are used.

Your task

Write a program that partitions lists of integers. The first line of input contains the number of lists and their length (between 1 and 25). Each subsequent line contains a list, with elements separated by a space. The program should display the partitioned lists, one per line. For display purposes, the partitions are to be shown with a vertical bar and a space either side.

Example

The upper chart on right shows the list

4 0 -5 -2 1 0 8 -9 6 4 0 7 -5

It has many possible partitionings, one of which is shown on the lower chart. It would be displayed as

-5 -9 -5 -2 | 0 0 0 | 8 6 4 1 7 4

Restrictions

You may use only one array or list structure to hold the original list, and that array must be partitioned in place by moving or exchanging elements. Elements must be inspected and altered by indexing, no high order functions such as map or equivalent may be used. Apart from input and output, your algorithm must not make more than 2 passes over the array.

Recommended Approach

Although you can try to do a 3-way partition in one pass, a good approach is to write a much simpler 2-way partition procedure, and use it twice, once to push elements of a particular sign to the appropriate end, and then to partition out zeroes in the other part of the array. Each pass will handle zeroes slightly differently.

Test data

Test your program using the following input.

8 17
-7 -9 -3 -4 -66 -3 -2 1 7 5 32 1 4 67 8 5 3
1 2 4 3 7 2 0 3 1 0 0 4 1 8 0 3 0
-1 -2 -9 -4 -3 -1 -7 -88 -34 -21 -3 -76 -4 -9 -12 -51 -94
0 4 -3 0 1 1 0 -4 -5 5 0 3 -4 5 2 7 0
10 9 8 7 6 5 4 3 2 1 0 -1 -2 -3 -4 -5 -6
-1 -1 -1 -1 -1 3 -2 -3 1 0 1 1 0 1 1 1 1
0 1 2 3 2 1 0 -1 -2 -3 -2 -1 0 1 0 1 0
1 2 3 2 1 2 3 2 1 2 3 2 1 2 3 2 1

64 Murlin

Murlin is a wizard who decodes URLs that have been encoded to disguise the true address of a malicious website. The encoding itself is legitimate, and the codes are interpreted as the equivalent normal characters in an address, but the user who clicks on one rarely knows what such a URL really refers to.

A URL-encoded string consists of ordinary characters and 3-character escape sequences. An escape sequence begins with a percent character (%) and is followed by two hexadecimal digits, using either upper or lower case. The two hex digits represent the character code. Murlin only has to deal with character codes in the printable ASCII character range, space (32 or hex 20) through to ~ (126, or hex 7E). Ordinary characters are preserved and each escape sequence is replaced by the character it represents.

Write a program to provide Murlin’s functionality. Input consists up to 10 encoded strings, one per line, with the first line containing the number of strings. Each string is up to 100 characters in length. You may assume the strings are properly constructed from printable characters.

Example

##Input

3
Hello
http://%77%77%77%2E%6D%61%6C%77%61%72%65%52%75%73%2E%63%6F%6D/www.furrykittens.com
http://www.example.com.au/spaces%20%26%20funny%20%21%23%7c%20chars%20in%20name.pdf

##Output

Hello
http://www.malwareRus.com/www.furrykittens.com
http://www.example.com.au/spaces & funny !#| chars in name.pdf

##Hexadecimal

In case you haven’t interpreted hexadecimal (base-16) numbers before, here’s a quick summary:

Hex digit Decimal
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
A or a 10
B or b 11
C or c 12
D or d 13
E or e 14
F or f 15

The decimal value of a 2-digit number d1d2 in base b is equal to

b * dec(d1) + dec(d2)

where dec returns the decimal value of a base-b digit.

##Test Data

You should test your program on the following data:

8
progcomp%40cse
%3Ca%20href%3D%22www.don%27tgothere.info%22%3ETesting%3C%2Fa%3E
%77%77%77%2E%75%72%6D%79%62%2A%2A%2A%2A%2E%72%75%2F%63%6C%69%63%6B%68%65%72%65/kiddysafe.org
%66%74%70%3A%2F%2F%74%72%6F%6A%61%6E%73%34%75%2E%6F%72%67%2F%70%77%6E%65%64%21
100%5exy
ENCODED%20%25%37%34%25%37%37%25%36%39%25%36%33%25%36%35
!*%21%2a()%28%29;:%3b%3a@&%40%26=+%3d%2b$,/%24%2c?#%2f%3f%23
[]%5b%5d'%27<>%3c%3e{}%7b%7d"%22^~%5e%7e`.%60%2e

65 Math input

In Visual Studio Code edit the file code/tasks/65/app.js. Write a program that reads in one character from the console and if that character is ‘+’ it displays ‘addition’, if this character is ‘-‘ it displays ‘subtraction’, otherwise it displays ‘unrecognized input’

Input Output
+ addition
- subtraction
* unrecognized input

66 Word times

In Visual Studio Code edit the file code/tasks/66/app.js. Write a program that reads a word from the console and displays this word n-times, where n is the number of characters the word has.

Example 1

input

three

output

three
three
three
three
three

Example 2

input

one

output

one
one
one

Example 3

input

a

output

a

67 Binary left shift

In Visual Studio Code edit the file code/tasks/67/app.js. Write a program that reads from a text file that contains rows of 8 bits. For each row, the program should left shift the binary value one bit, i.e. remove the left bit and add a zero to the right. The output should be displayed to the console.

Example

Input Output
11111110 11111100
11101101 11011010
01011110 10111100
00001111 00011110

68 Binary inverse

In Visual Studio Code edit the file code/tasks/68/app.js. Write a program that reads from a text file that contains rows of 8 bits. For each row, the program should invert the bits, i.e. a 0 should become a 1 and a 1 should become a 0. The output should be displayed to the console.

Example

Input Output
11111110 00000001
11101101 00010010
01011110 10100001
00001111 11110000

69 Averages

In Visual Studio Code edit the file code/tasks/69/app.js. Write a program that reads from a text file that contains rows of comma separated numbers. For all the numbers in this file calculate the average. The output should be displayed to the console.

Example 1

Input

1,2
3,4

Output

The average of 4 numbers is 2.5

Example 2

Input

3,5,7,2
3,4,5,4
6,8,9,19

Output

The average of 12 numbers is 6.25

70 Newton Raphson

In Visual Studio Code edit the file code/tasks/70/app.js. The first consumer calculators provided four arithmetic operators and square root, the latter using an iterative algorithm based on the Newton Raphson method for finding roots of equations. To determine the square root of a positive real number k, given any approximation xi calculate:

newton rapshon image

To obtain a value closer to the root. Keep applying the formula to obtain better approximations. Stop when successive approximations differ by 1e-10. Write a program that calculates the square root of a number read from a text file. The initial approximation can be 1 or k, as the algorithm converges quite quickly.

Test Input:

2
9.8696044010893
1000000

71 Human time

In Visual Studio Code edit the file code/tasks/71/app.js. Telling the time on an analogue clock is one of the many things we have to learn as children. Digital clocks are accurate but boring, 10:45 is exactly what it says, 10 hours and 45 minutes. But to most people, that's a quarter to 11.

To humanise dull 24-hour digital robot times we will convert them to what a person might say if they saw the corresponding analogue clock (and knew what part of the day is it). Elements of the response include:

  • mention minutes before the hour, but skip minutes completely if it's zero.
  • use a minute if it's exactly 1 (by the way, any programmer whose software produces the phrase "1 items" or any other plural should be kicked out of the programmer's club).
  • if the time is before the half-hour it's so many minutes past the hour, otherwise it's so many minutes to the next hour.
  • use a quarter and half where appropriate.
  • am or pm follows the hour, except for 12 noon and 12 midnight.

Your task

Write a program that efficiently converts robot time to human time (efficiency is defined below). The first line of input contains the number of times to be converted, a maximum of 20. The remaining lines have one 24-hour time each, in the form of four decimal digits. Each time is valid: that is, the first two digits lie between 00 and 23 and the second pair between 00 and 59.

For each time, display the original time, "is" and the human time according to the guidelines above, and consistent with the following example:

Example Input:

7
0017
0400
0915
1155
1230
1445
2301

produces

0017 is 17 minutes past 12 midnight
0400 is 4am
0915 is a quarter past 9am
1155 is 5 minutes to 12 noon
1230 is half past 12 noon
1445 is a quarter to 3pm
2301 is a minute past 11pm

Test data

Test your program using the following input.

20
0000
0030
0315
0824
0830
0831
0845
1059
1100
1145
1155
1229
1244
1313
1533
2145
2252
2330
2337
2359

72 Traffic

In Visual Studio Code edit the file code/tasks/72/app.js.

Aspects of traffic flow can be analysed using quite simple models based on what are called cellular automata. One such model represents an intersection through which red cars move left to right and blue cars move top to bottom.

Each cycle of the model consists of two half-cycles,

the red half-cycle, where the red cars move if possible, followed by the blue half-cycle, where the blue cars move if possible. A car can move only when the cell ahead of it is empty at the start of the half cycle: consequently in any contiguous block of cars only the first one moves, not the whole block. The edges wrap around, so a car can move off the right edge to the left-most cell (if it's empty), and similarly from the bottom cell to the top cell. In the diagram below (a) shows a configuration of order N=3, which is the length of each arm (maximum 40 for this task). There are 4N+1 cells in all. During the first half-cycle (b) two of the four red cars move, one of which wraps around to the left-hand cell. To complete the cycle (c) two of the three blue cars move, including one into the central cell. The bottom one can't move because the top was occupied at the start of the half-cycle.

We define velocity as the proportion of cars that move in a cycle, in this case the velocity is (2+2)/(4+3) or about 0.571. Velocity can change over time, and can trend to 1 (freeflowing traffic with no blocked cars), or to 0 (gridlock), or it can become periodic as the system stabilises.

example of traffic cycle

Your task

Write a program that simulates this traffic flow model. Input consists of three lines: the first contains N, the system size, and the required number of cycles to be simulated. The second line contains the layout for the red row (left to right) and the third contains the layout for the blue column (top to bottom). R or B represents a car and a dot (.) represents an empty space. The central cell is shown twice. Assume the data is valid.

During the simulation you must keep track of the velocity on each cycle. At the end of the simulation display the last cycle velocity and the average velocity, then the final configuration in the same format as the input.

Example

This is the above example, but iterated over 5 complete cycles.

3 5
.RRR..R
B.BR..B

produces...

Current velocity: 0.714, average velocity = 0.600
.RR..RR
B.B.B..

Test data

Test your program using the following 3 test cases.

Test 1:

4 7
R..R..R..
..B..B..B

Test 2:

17 80
.RRRRRRRRRR.RRRRRBR..RRRRRRRRRRRRRR
BB.BBBB.BBBBBBBBBBB.BBBBBBB.BBBBBBB

Test 3:

40 100
.RRRR.RR..RR....RR..R.....R.R.RR......R....RR....RR..R..RR.RR..R....RR.R.....R.R.
..B.....B.BBB.BBB.B......B..B...B.B..BB.........B....B.B.BBB..B.B.B.BB.BBB...BB.B

73 Three strings

In Visual Studio Code edit the file code/tasks/73/app.js.

Write a program that reads in three strings from the console and checks if all three strings are equal.

Example:

Input Output
2
2
2
EQUAL
two
2
2
NOT EQUAL

74 Ascii border

In Visual Studio Code edit the file code/tasks/74/app.js.

Write a program that reads in a string of length 3 from the console and prints an ascii border around each character.

Example:

Input Output
XXX
-------
|X|X|X|
-------
XOX
-------
|X|O|X|
-------
XOO
    
-------
|X|O|O|
-------

75 Crosses and Noughts

In Visual Studio Code edit the file code/tasks/75/app.js.

Write a program that reads in a 3 x 3 bordered grid of noughts and crosses from a text file. The program should print out the total number of crosses and noughts to the console.

Example 1:

Input Output
-----------
 X | X | X 
-----------
 X | X | X 
-----------
 X | X | X 
-----------
X: 9
0: 0

Example 2:

Input Output
-----------
 X | 0 | X 
-----------
 X | X | 0 
-----------
 X | 0 | X 
-----------
X: 6
0: 3

76 Random grid

In Visual Studio Code edit the file code/tasks/76/app.js.

Write a program that creates a random 3 x 3 grid of X’s and 0’s with a border. The program should not get any input and should write all outputs to the console.

Examples:

Output
-----------
 X | X | 0 
-----------
 X | 0 | X 
-----------
 X | X | X 
-----------
-----------
 0 | 0 | X 
-----------
 0 | X | X 
-----------
 0 | 0 | X 
-----------
-----------
 X | 0 | X 
-----------
 0 | 0 | X 
-----------
 0 | X | X 
-----------

77 Storing dates

In Visual Studio Code edit the file code/tasks/77/app.js.

For some purposes, it is useful to store dates in the form YYYY/DDD, where YYYY is the year and DDD is an integer representing the number of days since the beginning of the year. Some accounting systems work this way, as do astronomical dates (with times as a fraction of the day!). Write a program that accepts any number of dates in the above format, one per line, and prints each one followed by the date in the more familiar Day Month Year form. The list is terminated by a zero year. The input needs to be read from a text file and the output should go to the console.

Examples:

Input Output
1997/1 1997/1 1 January 1997
2000/60 2000/60 29 February 2000
1985/366 1985/366 Date out of range
0000/0

78 Uppercase

In Visual Studio Code edit the file code/tasks/78/app.js.

Write a node.js JavaScript program that reads a name from the console, and checks if the name starts with an uppercase letter. The output should be “ok” or “Name must start with uppercase letter”.

Examples:

Input Output
Thomas ok
thomas Name must start with uppercase letter
James ok

79 Integers continued

In Visual Studio Code edit the file code/tasks/79/app.js.

Write a node.js JavaScript program that prints the positive integers 1, 2, 3… one number per line. The program should stop each time five numbers have been printed and ask the user by printing “Continue? (Y/N):”. If the user types “Y” it should continue printing the next five numbers … . If the user types “N” the program should stop. If the user types anything else (neither Y nor N) the program should print “Continue? (Y/N):” again.

Examples:

Input Output
1
2
3
4
5
Continue (Y/N)
Y 6
7
8
9
10
Continue (Y/N)
abc Continue (Y/N)
N

80 Total capitals

In Visual Studio Code edit the file code/tasks/80/app.js.

Write a node.js JavaScript program that reads text from a sequential text file and counts the total amount of capital letters.

Example 1:

Input Output
Sgt. Pepper's Lonely
Hearts Club Band 6

Example 2:

Input Output
Let me take you down,
because I'm going to
Strawberry Fields
Nothing is real and
nothing to get hung about
Strawberry Fields forever 7

81 Triangular numbers

In Visual Studio Code edit the file code/tasks/81/app.js.

Write a node.js JavaScript program that reads creates the triangular number sequence 1, 3, 6, 10, …

Rule: xn = n(n+1)/2

The program should have no input and should print one number per row, and stop before the number is greater than 2000.


82 Letter Word Game

In Visual Studio Code edit the file code/tasks/82/app.js.

You're probably familiar with a word game that goes like this: given a key word, find as many other words as you can that can be made up from the letters of the key word. The letter at each position in the key word can be used only once. For example, a new word can only have two Ns if there were at least two Ns in the key word.

Write a program that reads a key word followed by other words from a text file, and determines whether each word can be obtained from the letters of the key phrase in the manner described above. Every word is on a separate line.

The program's output consists of the key word on one line, then each following word and its classification in capitals (YES or NO) on one line. You may assume that the words will consist only of lower case letters.

Example 1:

Input Output
determination determination
nation nation YES
mine mine YES
mines mines NO
rare rare NO
tram tram YES
note note YES

Example 2:

Input Output
pleasures pleasures
assure assure YES
letters letters NO
rules rules YES
lapsus lapsus YES
pauses pauses YES
wording wording NO

83 Daily step targets

In Visual Studio Code edit the file code/tasks/83/app.js.

Smart watches now provide heart rate, walking speed, energy consumption, step counters and sometimes even the time. Everyone knows they should try to walk a certain minimum number of steps each day, and watches will often set a new target daily based on the number of steps taken over the last few days and the current target. Fitness Friend, a proposed software that will only get to market if you can implement it, goes one step further.

Some people are discouraged if they keep failing to reach their target: they have low motivation. Others try to outdo themselves every day and want an always-increasing target: they're highly motivated. Fitness Friend introduces a self-nominated motivation factor M, an integer between 0 and 100. The way it works is shown in the diagram below.

daily stesps image

Today's step target is a particular number represented by the red horizontal line. When you exceed the target (S > T, green dot), then if you have low motivation the new target (red dot) is only a bit more than the old one to make it more attainable, but if you have high motivation it moves closer to S. Conversely if you don't reach the target (S < T, blue dot), in the low motivation case the target moves a long way down, much less so for the high-motivation case.

The new-target calculation is given by two similar formulas, depending on whether today's target was reached:

daily stesps image

where S is today's step count, T is today's target, T ′ is tomorrow's target, rounded down to the next integer, and M is the Fitness Friend Motivation Factor. k is just M converted to the range 0 to 1.

For example, if M is 45, T is 7500 and S is 7125, the second formula gives

k = 0.45, (1–k) = 0.55*0.55 = 0.3025,
T ′ = 7500 + 0.3025 * (7125 – 7500) = 7500 + 0.3025 * (–375) = 7500 – 113.4375 = 7386.5625
which you round down to 7386.

Your task: Write a program that calculates the daily targets given motivation and daily step counts, collecting simple statistics to report at the end. Read the input from a textfile. The first line of input has the Motivation Factor and starting target, separated by a space. The rest of the input has the daily steps, one per line. A negative value ends the list (and isn't counted as step data of course).

Your program should list all the targets on one line, then on a new line show

  • motivation
  • the number of days
  • the mean (average) daily number of steps
  • the percentage of days when the target was reached
  • the final calculated target

All quantities are expressed as integers, rounded down.

Examples:

Input Output
80 7500 7500 7967 7956 8633 8527
8231 Motivation 80, days 4, mean steps 7736, goal reached 50%. Final target 8527
7700
9015
6000
-1

84 Rats

RATS (in this context) stands for Reverse, Add, Then Sort, applied to a positive decimal integer. It's the generating algorithm for an integer sequence that either diverges, or enters a reasonably short cycle. Consider the integer 180. Reversing the digits gives 081, or just 81. 180 + 81 = 261. Sorting the digits gives 126.

Continuing,

126 + 621 = 747, sorted = 477 
477 + 774 = 1251, sorted = 1125 
1125 + 5211 = 6336, sorted = 3366 
3366 + 6633 = 9999, sorted = 9999 
9999 + 9999 = 19998, sorted = 18999 
18999 + 99981 = 118980, sorted = 011889 
11889 + 98811 = 110700, sorted = 000117 
117 + 711 = 828, sorted = 288 
288 + 882 = 1170, sorted = 117 

So the sequence ends in a cycle of period 2 (the period of a cycle is the number of different values it contains).

Only a small number of different cycles can occur, we want to find them.

Your task

In Visual Studio Code edit the file code/tasks/84/app.js.

Write a program that identifies all cycles that occur for starting numbers less than 10000 (or 1000 for fewer marks). If any sequence element exceeds 10 , you may assume the sequence diverges. Complete answers depend on your computer using 64-bit arithmetic. In the event that your calculations use 32-bit arithmetic and overflow occurs, you will not be penalised provided the other cycles are reported correctly.

Your program's output should consist of one cycle on each line, ordered by period and then by the smallest member of the cycle. Each line should show three data items:

  • the cycle period;
  • the number of starting values that lead to that cycle; and
  • the members of the cycle in order of occurrence, starting with the smallest member.

Example:

For example, say you discovered that 100 starting values lead to the cycle above, your program's output should include the line

Period: 2, occurs 100 times, cycle: 117 288 

85 Queue Jumpers

The residents of Q-Town love queuing for the theatre. Some of them also consider particular position numbers to be lucky, so there can be a lot of undignified jostling while waiting in line. The Mayor of Q-Town wants to put a stop to this unseemly behaviour. She decrees that all theatregoers must adhere to the following rules:

  • People initially form a queue in the order they arrive at the theatre.
  • Just before the theatre opens, everyone in decreasing age order is allowed to nominate a position in the queue they would like to occupy.
  • Nobody can nominate a position that has already been nominated, so all nominations are distinct, and
  • Nominations are optional.

On the mayor's signal, everyone re-orders themselves in a dignified way. Those who did not nominate a position are shuffled up or down the queue as needed, maintaining their relative order.

Your task

Write a program to manage Q-Town's orderly queuing system. Input consists of one queuing problem per line, preceded by the number of problems. Each queuing problem consists of the number of patrons, to a maximum of 26, and the position each one would like to occupy. Positions are counted from 1, and 0 means no nomination.

People are allocated an upper-case letter in the original queue order, and the solution is the new arrangement of letters representing the revised queue. Assume the data is valid. The program should show both the original order and the final order on separate lines, with a space between each letter.

Example

3 
3 0 0 0 
9 9 8 7 6 5 4 3 2 1 
5 0 1 5 0 2 

produces...

A B C 
A B C 
 
A B C D E F G H I 
I H G F E D C B A 
 
A B C D E 
B E A D C 

Test data

Test your program using the following data.

5 
4 4 2 3 1 
6 0 0 5 3 4 1 
13 0 0 1 2 3 4 5 6 7 8 9 10 11
26 12 13 3 0 15 0 9 10 8 0 0 14 0 2 4 5 0 7 0 11 1 0 0 0 6 0 
1 0 

86 Inheritance

The system of inheritance that applied to most families with land or a title in England until recent times was called entailment. It was designed to keep the family estate intact as far as possible, by passing ownership to one (generally male) person at a time. Instead of all children, or even just all sons, inheriting the estate on the death of an owner, the eldest surviving son inherits the lot. This rule then applies recursively to his sons. Thus all his male descendents are ahead of his younger brothers, his brothers are ahead of his uncles, and so on. If all male descendents of the original owner are deceased, surviving females are next in line to inherit, but under these conditions:

  • The inheritance rules still follow the eldest male line in order to rank females, and
  • Sisters inherit equally (thus potentially breaking up the estate, which would be transferred to other families on marriage).

Example

The family tree below shows all the descendents of the original owner, M0. M0 and his eldest son M1 are deceased, and M1's eldest son is the present owner. The numbers in parentheses record the order of inheritance that would apply when M4 dies.

Inheritance

First in line is M4's brother M5 (because M4 has no male heirs), then M5's first son, his grandson, etc. Following all 10 surviving males, the same rules apply to females, starting with M4's daughters, who are jointly 10th in line. In practice males are assigned on a pre-order traversal of the male-line tree and females on a post-order traversal of the male-line tree, which is why F6 inherits ahead of F1.

Note that the structure doesn't depend on who's still alive: although dead people can't inherit, their living descendents can.

Your task

Write a program that analyses a family tree and prints the order of inheritance. Input consists of one line for each male, listing his children in descending order of age. The first input line is the number of males. Each person is identified by gender (M or F) and a non-negative integer, unique to that gender. The original owner is always M0, other numbers can be assigned in any order, but without gaps.

For each line the patriarch's ID is followed by an optional symbol and a colon, then the IDs of the children. The symbol is either

  • x, indicating the person is deceased, or
  • *, indicating the present owner.

Output is the present owner and the order of inheritance in one line, separated by spaces.

Sample data

This describes the tree above. It's already sufficiently complex to fully exercise your program.

12 
M0x: M1 F1 M2 M3 
M1x: M4 M5 F2 M6 F3 
M3: 
M4*: F4 F5 
M5: M8 M9 
M10: 
M8: M11 
M6: M10 
M7: F6 
M2: M7 
M9: 
M11:

produces...

M4 M5 M8 M11 M9 M6 M10 M2 M7 M3 F4+F5 F2+F3 F6 F1

Test data

Test your program using the following two test cases.

Test 1:

11 
M0*: M3 M6 
M1: M5 
M2: M1 
M3: 
M4: M10 M2 
M5: 
M6: M7 M9 
M7: 
M8: 
M9: M8 M4 
M10: 

Test 2:

17 
M0x: M3 M14 M11 
M4: 
M8x: F2 M4 M15 M5 
M12: M8 M10 
M16: 
M5: 
M14x: F3 M12 F5 
M3*: 
M9: 
M6: M13 F4 
M10: M9 M6 M2 
M2x: 
M13x: 
M11: M16 F1 M1 
M1: 
M15: M7 
M7: 

87 Lowest of three

Write a program that reads in three numbers from the console and prints out the lowest number to the console.

Example 1

Input Output
1
2 1
3

Example 2

Input Output
11
2 2
5

88 Repeat the string

Write a program that reads in one string and one number n from the console. The program should print out n times the given string. Examples:

Example 1

Input Output
hello hello
1

Example 2

Input Output
world world
3 world
world

89 Lower to Uppercase

Write a program that reads a word from the console and converts all letters to lowercase if all letters of the word are all uppercase and visa versa (converts all letters to uppercase if all letters of the word are lowercase. If the letters of the word are of mixed case no conversion should occur.

Example 1

Input Output
subway SUBWAY

Example 2

Input Output
CLEAN clean

Example 3

Input Output
tradeMarK tradeMarK

90 Product of fractions

Consider the following product of fractions:

Product Of Fractions

Your task

Write a program that determines the largest value of k for which Pk > 0.6666667000.


91 Buckets

If you had a 3 litre bucket called A, and a 5 litre bucket called B, and a water tap, you could measure 4 litres with the following procedure:

fill B from the tap 
tip 3 into A 
empty A 
tip 2 into A  
fill B from the tap 
tip 1 into A 
Done! 

Write a program which, given the size of A, the size of B, and the desired amount to measure, returns a series of lines describing how to measure it.

Output If there is no way of producing the desired amount print "No solution possible". Otherwise match the format of the output in the example above.

Hint You may assume that if there is a solution it can be obtained by repeatedly pouring one container into the other.

Test Data

Size of A (litres) Size of B (litres) Amount to measure (litres)
3 5 4
3 5 2
11 5 3
10 5 3

92 Suffixes

Find words that end in a particular suffix. The suffix is a string. The string is supplied on the first line of input. For the purposes of this task, a suffix is any non-empty sequence of letters and digits. The remaining input lines contain any amount of text, consisting of words (non-empty sequences of non-space characters). If the suffix read on the first line is n characters in length. The program must display each word that matches the suffix, that is, whose last n characters are exactly (case sensitive) the same as the suffix.

  • Display the words on separate lines.
  • Ignore all punctuation (defined as anything other than letters and digits).
  • Accept between one and ten suffixes on the first line, and display words that match any of them

Example

Input Output
ing Bring
Bring on the clowns, singing and singing
dancing; dancing
keywords: ping telnet TCP/IP finger ping
ning-nong ning
Titanic sinking sinking
You can’t perform that action at this time.