More results...

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
post
page
Python IDE Dashboard

Step Count Algorithm in LMC

steps-count-controlled-loopCount-controlled loops are used in many programs to increment a counter for each iteration of the loop. Per default the increment for the counter is +1.

FOR counter FROM 1 TO 10:
    OUTPUT (COUNTER)

However you can specify a different step when incrementing your counter in a count-controlled loop. For instance to count in 5:

FOR counter FROM 0 TO 100 STEP 5:
    OUTPUT (COUNTER)

You can also use different starting and ending values:

FOR counter FROM 50 TO 250 STEP 5:
    OUTPUT (COUNTER)

A negative step can also be used to decrement the counter:

FOR counter FROM 20 TO 0 STEP -2:
    OUTPUT (COUNTER)

This challenge consists of writing a program using LMC to implement a count-controlled loop using a step defined by the end user. Your program will:

  • INPUT: Retrieve the starting value for the step count algorithm from the end user.
  • INPUT: Retrieve the ending value for the for step count algorithm from the end user.
  • INPUT: Retrieve the step value from the end user.
  • Count and output all the values (from the starting value to the ending value, using the given step).

Note that this algorithm is an implementation of an arithmetic number sequence.

To complete this challenge you will need to use one of the following online LMC Simulators:

The list of LMC instructions is provided at the bottom of this page.

You will be able to test your algorithm using the following input values:

Test # Input Values Expected Output Pass/Fail
#1 Start Value: 10
End Value: 20
Step: 2
10,12,14,16,18,20
#2 Start Value: 82
End Value: 100
Step: 5
82,87,92,97
#3 Start Value: 10
End Value: 1
Step: -1
negative-step
10,9,8,7,6,5,4,3,2,1

LMC Instruction Set


Note that in the following table “xx” refers to a memory address (aka mailbox) in the RAM. The online LMC simulator has 100 different mailboxes in the RAM ranging from 00 to 99.

Mnemonic Name Description Op Code
INP INPUT Retrieve user input and stores it in the accumulator. 901
OUT OUTPUT Output the value stored in the accumulator. 902
LDA LOAD Load the Accumulator with the contents of the memory address given. 5xx
STA STORE Store the value in the Accumulator in the memory address given. 3xx
ADD ADD Add the contents of the memory address to the Accumulator 1xx
SUB SUBTRACT Subtract the contents of the memory address from the Accumulator 2xx
BRP BRANCH IF POSITIVE Branch/Jump to the address given if the Accumulator is zero or positive. 8xx
BRZ BRANCH IF ZERO Branch/Jump to the address given if the Accumulator is zero. 7xx
BRA BRANCH ALWAYS Branch/Jump to the address given. 6xx
HLT HALT Stop the code 000
DAT DATA LOCATION Used to associate a label to a free memory address. An optional value can also be used to be stored at the memory address.
Tagged with: ,

Atbash Cipher Algorithm

The Atbash Cipher is a monoalphabetic substitution cipher that was originally used for the Hebrew alphabet. It is one of the earliest known subtitution ciphers to have been used. As opposed to a Caesar Cipher, the Atbash cipher does not need a key. It is hence easier to break!

The Atbash Cipher maps each letter of an alphabet it to its reverse, so that the first letter (e.g. A) becomes the last letter (e.g. Z), the second letter (B) becomes the second to last letter (Y), and so on.

Using the Latin Alphabet

Plain A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Cipher Z Y X W V U T S R Q P O N M L K J I H G F E D C B A

Using the Hebrew Alphabet

  Aleph Bet Gimel Daleth Heh Vav Zayin Het Tet Yodh Kaph Lamed Mem Nun Samech Ayin Peh Tzady Koof Reish Shin Taw
Plain א ב ג ד ה ו ז ח ט י כ ל מ נ ס ע פ צ ק ר ש ת
  Taw Shin Reish Koof Tzady Peh Ayin Samech Nun Mem Lamed Kaph Yodh Tet Het Zayin Vav Heh Daleth Gimel Bet Aleph
Cipher ת ש ר ק צ פ ע ס נ מ ל כ י ט ח ז ו ה ד ג ב א

Encryption/Decryption Algorithm


Note that the same algorithm can be used to encrypt a plaintext into a ciphertext or to decrypt a ciphertext into a plaintext.

The flowchart below is used to encrypt or decrypt text using the Atbash Cipher. To fully understand this algorithm, you will need to understand how ASCII code works. The algorithm above is using the ASCII codes for the uppercase alphabet from letter A (ASCII 65) to letter Z (ASCII 90).

Video TutorialFlowchart

atbash-algorithm-flowchart

We can then use this function in a program used to retrieve the plaintext to encrypt (or ciphertext to decrypt) from the end user:
Atbash-Cipher-Input-Output-flowchart

Python Code


Your task is to implement the above algorithms using Python:

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: ,

Polar vs. Cartesian Coordinates

radar-polar-coordinatesIn this blog post we will investigate two types of coordinates used to identify the location of a point on a 2D plan:

  • Cartesian Coordinates (x,y)
  • Polar Coordinates (r,θ)

Both sets of coordinates have their own applications and are often used in computer systems and video games. After reviewing how these sets of coordinates work we will write a Python script based on trigonometric formulas to convert Cartesian coordinates into Polar coordinates and vice versa.

Cartesian CoordinatesPolar Coordinates
Cartesian coordinates are used to identify the exact location of a point on a 2D plan. Two perpendicular axis (x axis and y axis) meet at the origin (0,0). The (x,y) cartesian coordinates are based on the distance of a point from these axis.

Look at the canvas below to understand how Cartesian coordinates work:

When using Cartesian coordinates, we can divide the 2D plan into four quadrants as follows:
xy-coordinates

polar-coordinates
Polar coordinates are also used to identify the exact location of a point on a 2D plan. Using a polar coordinate system, each point on a plane is determined by a distance from a reference point and an angle from a reference direction. The reference point is called the pole, and the ray from the pole in the reference direction is the polar axis.

Look at the canvas below to understand how Polar coordinates work:


Polar to Cartesian Coordinates Conversion Formulas


Using trigonometric formulas we can easily convert Cartesian coordinates to Polar coordinates and vice-versa.
cartesian-polar-coordinates-conversion-formulas

Python Turtle Implementation


Your Task


Adapt the above Python code to generate random polar coordinates and apply the conversion to calculate and output the matching Cartesian coordinates.

Python Turtle Radar Animation


To apply the conversion formulas we have created a radar animation using Python Turtle:

Tagged with:

MRX20 – Mission to Mars

mrx20-logoThe MRX20 probe was sent to Mars by the Inter-Continental Space Agency (ICSA) a few years ago. It was due to return to planet Earth just a few days ago. The probe collected a large amount of samples from the Martian soil and took thousands of high definition pictures of Mars. Initial analysis performed on site by the probe’s Artificial Intelligence seems to indicate that the probe may contain strong evidence that there is life on Mars.

Unfortunately just a few thousand miles away from Earth, the probe collided with an unidentified geostationary satellite. It was pulverised into small pieces. Most of these were either lost in space or burnt down when entering the Earth’s atmosphere. A few pieces did pierce through the atmosphere and crashed on Earth in various locations all around the globe.

The ICSA sent a team of Probe Debris Collectors (PDCs) to locate the various parts and submit back to the ICSA the exact locations and pictures of the debris found. Each PDC has been instructed to communicate with the ICSA using a secure connection using a range of encoding/encryption techniques.

The What3Words (W3W) geo-localisation system is used to inform of the exact location of the debris. Your mission is to decode the secured transmission messages to locate the position of the debris and to retrieve all the information that has been retrieved from the debris. Use this information to find out what you can learn about the existence of life on planet Mars.
login-ICSA

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: ,

Caesar Shift Decoder

A Caesar Shift cipher is a type of mono-alphabetic substitution cipher where each letter of the plain text is shifted a fixed number of places down the alphabet. For example, with a shift of 1, letter A would be replaced by letter B, letter B would be replaced by letter C, and so on. This type of substitution Cipher is named after Julius Caesar, who used it to communicate with his generals.

Key +5
Plain text alphabet:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
shift-5-places
Cipher text alphabet: F G H I J K L M N O P Q R S T U V W X Y Z A B C D E

This type of cipher is a form of symmetric encryption as the same key can be used to both encrypt and decrypt a message. (e.g. If a message is encrypted with a key of +5, it can be decrypted with a key of -5).

A cipher wheel is a tool used to help decipher a message encrypted using the Caesar cipher:

Caesar Shift Decoder


The Caesar Shift cipher is not a very secure cipher as it only has 26 different keys. It is hence possible to apply each of the 26 keys to a cipher text to retrieve the plaintext.

The aim of this challenge is to write a Python program to decode a cipher text using all 26 keys. The user will then be able to read the 26 outputs and find the output that correspond to the plaintext.

Here is the cipher text that we will try to decode:

FTMF’E AZQ EYMXX EFQB RAD YMZ, AZQ SUMZF XQMB RAD YMZWUZP. ZQUX MDYEFDAZS

From Flowchart to Python Code


Here is the flowchart for our Caesar Shift Decoder:
caesar-shift-decoder

To fully understand this algorithm, you will need to understand how ASCII code works. The algorithm above is using the ASCII codes for the uppercase alphabet from letter A (ASCII 65) to letter Z (ASCII 90).

Your task is to write the Python code corresponding to the above flowchart in the trinket box below.
You will then be able to use your Caesar Shift Decoder to decode the following messages:

OVBZAVU, AYHUXBPSPAF IHZL OLYL. AOL LHNSL OHZ SHUKLK. ULPS HYTZAYVUN

Message #1

FTMF'E AZQ EYMXX EFQB RAD YMZ. AZQ SUMZF XQMB RAD YMZWUZP – ZQUX MDYEFDAZS

Message #2

VYUONCZOF, VYUONCZOF. GUAHCZCWYHN XYMIFUNCIH. VOTT UFXLCH

Message #3

Python Code


Tagged with: ,

The Dobble Algorithm

Dobble (Spot It! in the US) is a speedy observation card game for 2 players or more. During the game, players have to spot the identical symbol between two cards as quickly as possible to collect cards and score points.

dobble-pair

The Dobble rule!


Each card of the deck contains 8 graphical symbols. The deck contains 55 cards in total and there is always one and only one symbol in common between any two cards of the deck.

In order to create a deck of cards to follow this rule we need to apply some mathematical logic.
The mathematics behind the game of Dobble is fully explained on this blog post: http://www.petercollingridge.co.uk/blog/mathematics-toys-and-games/dobble/.

We will base our algorithm based on the following key findings:
If a game of Dobble needs (n+1) symbols on each card, n being a primary number then we will need:

  • A collection of n2 + n + 1 symbols
  • We will be able to generate n2 + n + 1 unique cards

The Dobble Matrix


To complete this challenge, it may be easier to consider the following Matrix used for a game of Dobble with only 4 symbols per card (n=3).
We will use 32 + 3 + 1 = 13 symbols to generate 13 cards with 4 symbols per card.

This matrix enables us to visualise which symbols will appear on each card and it also enables us to check that any two cards of the deck have one and only one symbol in common.
dobble-matrix

The real game of Dobble has 55 cards with eight symbols on each card. Note that with 8 symbols per card, it would have been possible to create 57 cards following the Dobble rules (72 + 7 + 1 = 57) . For some reason, 2 cards were dismissed and the actual game only contains 55 cards.

The Dobble Algorithm


For this challenge we have decided to write an algorithm to generate the 57 possible cards for a game for Dobble. The algorithm will be based on the symbols used in the real game. The challenge consists of identifying the 8 symbols to be be used on each of the cards, making sure that the Dobble rule is always respected:

There must always be one and only one symbol in common between any two cards of the deck.

Python Code/Solution


Manhattan distance calculator

When calculating the distance between two points on a 2D plan/map we often calculate or measure the distance using straight line between these two points. Thought this “as the crow flies” distance can be very accurate it is not always relevant as there is not always a straight path between two points.

The perfect example to demonstrate this is to consider the street map of Manhattan which uses a grid-based layout: a mesh of horizontal and vertical roads crossing at a right angle.
taxicab-manhattan-grid-layout

Distance “as the crow flies”


The shortest distance between two points on a 2D grid is the distance using a straight line path between these two points.
taxicab-manhattan-grid-straight-path

On a 2D plan, using Pythagoras theorem we can calculate the distance between two points A and B as follows:
taxicab-manhattan-grid-straight-distance

Manhattan Distance (aka taxicab Distance)


The Manhattan distance (aka taxicab distance) is a measure of the distance between two points on a 2D plan when the path between these two points has to follow the grid layout. It is based on the idea that a taxi will have to stay on the road and will not be able to drive through buildings! The following paths all have the same taxicab distance:
taxicab-manhattan-grid-layout-paths

The taxicab distance between two points is measured along the axes at right angles.
taxicab-manhattan-grid-taxicab-distance
Note that the taxicab distance will always be greater or equal to the straight line distance.

Python Implementation


Check the following code to see how the calculation for the straight line distance and the taxicab distance can be implemented in Python.

Tagged with:

Secret Santa’s Ciphers

It’s only few days before Christmas so here are some secret messages from Santa for you to decode…

Secret Message #1, encoded using Maritime Signal Flags


secret-santa-maritime-flags
International maritime signal flags are various flags used to communicate with ships. Each flag represents a letter of the alphabet or a digit (0 to 9). You may need to research on the internet to find out the whole list of flags.


Secret Message #2, encoded using a Pigpen cipher


secret-santa-pigpen-cipher
A pigpen cipher is a type of visual cryptography where each character of the alphabet is replaced with a symbol.


Secret Message #3, encoded using Morse code


secret-santa-morse-code
Morse code is a method of transmitting text information as a series of on-off tones, lights, or clicks that can be directly understood by a skilled listener or observer without special equipment. Each character (letter or numeral) is represented by a unique sequence of dots and dashes. The duration of a dash is three times the duration of a dot.


Secret Message #4, encoded using Semaphore Flags


secret-santa-semaphore-flags
Flag semaphore is a telegraphy system conveying information at a distance by means of visual signals with hand-held flags. Information is encoded by the position of the flags. The current flag semaphore system uses two short poles with square flags, which a signalman holds in different positions to signal letters of the alphabet and numbers. The signalman holds one pole in each hand, and extends each arm in one of eight possible directions. At sea, the flags are coloured red and yellow, while on land, they are white and blue.


Secret Message #5, encoded using a rail-fence cipher


secret-santa-rail-fence
The rail fence cipher (sometimes called zigzag cipher) is a transposition cipher that jumbles up the order of the letters of a message using a basic algorithm.
The rail fence cipher works by writing your message on alternate lines across the page, and then reading off each line in turn. You can read more about the rail-fence cipher on this page.


Secret Message #6, encoded using a mono-alphabetic substitution cipher


A mono-alphabetic cipher (aka simple substitution cipher) is a substitution cipher where each letter of the plain text is replaced with another letter of the alphabet. It uses a fixed key which consist of the 26 letters of a “shuffled alphabet”.

You can decipher a mono-alphabetic cipher using a frequency analysis.

Cipher Text:

“G RGXX XGMK GO BAK YULB, BAK YHKLKOB, UOQ BAK PCBCHK!”, LNHIIZK HKYKUBKQ, UL AK LNHUVJXKQ ICB IP JKQ. “BAK LYGHGBL IP UXX BAHKK LAUXX LBHGMK RGBAGO VK. IA WUNIJ VUHXKS! AKUMKO, UOQ BAK NAHGLBVUL BGVK JK YHUGLKQ PIH BAGL! G LUS GB IO VS DOKKL, IXQ WUNIJ; IO VS DOKKL!”

AK RUL LI PXCBBKHKQ UOQ LI ZXIRGOZ RGBA AGL ZIIQ GOBKOBGIOL, BAUB AGL JHIDKO MIGNK RICXQ LNUHNKXS UOLRKH BI AGL NUXX. AK AUQ JKKO LIJJGOZ MGIXKOBXS GO AGL NIOPXGNB RGBA BAK LYGHGB, UOQ AGL PUNK RUL RKB RGBA BKUHL.

“BAKS UHK OIB BIHO QIRO”, NHGKQ LNHIIZK, PIXQGOZ IOK IP AGL JKQ–NCHBUGOL GO AGL UHVL, “BAKS UHK OIB BIHO QIRO, HGOZL UOQ UXX. BAKS UHK AKHK—G UV AKHK—BAK LAUQIRL IP BAK BAGOZL BAUB RICXQ AUMK JKKO, VUS JK QGLYKXXKQ. BAKS RGXX JK. G DOIR BAKS RGXX!”

AGL AUOQL RKHK JCLS RGBA AGL ZUHVKOBL UXX BAGL BGVK; BCHOGOZ BAKV GOLGQK ICB, YCBBGOZ BAKV IO CYLGQK QIRO, BKUHGOZ BAKV, VGLXUSGOZ BAKV, VUDGOZ BAKV YUHBGKL BI KMKHS DGOQ IP KEBHUMUZUONK.

“G QIO’B DOIR RAUB BI QI!”, NHGKQ LNHIIZK, XUCZAGOZ UOQ NHSGOZ GO BAK LUVK JHKUBA; UOQ VUDGOZ U YKHPKNB XUINIIO IP AGVLKXP RGBA AGL LBINDGOZL. “G UV UL XGZAB UL U PKUBAKH, G UV UL AUYYS UL UO UOZKX, G UV UL VKHHS UL U LNAIIXJIS. G UV UL ZGQQS UL U QHCODKO VUO. U VKHHS NAHGLBVUL BI KMKHSJIQS! U AUYYS OKR SKUH BI UXX BAK RIHXQ. AUXXI AKHK! RAIIY! AUXXI!”

AK AUQ PHGLDKQ GOBI BAK LGBBGOZ–HIIV, UOQ RUL OIR LBUOQGOZ BAKHK: YKHPKNBXS RGOQKQ.


unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: ,

Level generation using a 2D array

In this post we will investigate how to generate a level/stage for a platform game using a 2D array.

We will focus on the level for a 2D platform game such as Super Mario:
platform-level

By applying a grid layout to this stage, we can break down the stage in a collection of tiles. We can then store each tile using a 2D array as follows:

2d-array-level .

In this array, each tile can be associated with an integer value. For instance, in the above array/grid, a 1 represents a platform, a 2 represents a gold coin.

In javascript, the 2D array for this stage would be initialised as follows:

var grid = [
  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0],
  [0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0],
  [0,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0],
  [0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0],
  [0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0],
  [1,1,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0],
  [0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0],
  [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
];

Using nested loops, we can then write an algorithm to scan through all the values of the array and display each tile corresponding to their integer value accordingly.

See the Pen
Level Generator
by 101 Computing (@101Computing)
on CodePen.

Please note that using a 2D array approach to store the details of a stage/level is not the only approach available. Other approaches could be used such as storing the position and dimensions of each platform in a list. The use of a 2D array in a more advanced game could quickly become too “greedy” in terms of memory use.

Adapt the code…


Using a 2D array approach can be used to create games using a top-down view such as Pacman. You can adapt the above code to recreate a maze used in a Pacman game as follows:
2d-array-pacman-maze-layout

Tagged with:

Heads or Tails

flip-a-coinIn this challenge we will create a game of heads to tails using the following rules:

  • The game will consist of 5 rounds.
  • In each round:
    • the user will make a guess,
    • the computer will flip a coin,
    • the player will score 1 point for a correct guess.

In order to complete this game we will first create a function called flipCoin() to flip a coin and return the value “Heads” or “Tails”.

Here is the flowchart for this function:
flipcoin-function-flowchart

We will then use this function in our game:
heads-or-tails-flowchart

From flowchart to Python code


Using both flowcharts provided above, you can now implement the full code for this game:

Extension Task #1


Can you tweak this code so that the user can only enter the value “Heads” or “Tails” and nothing else. (If they do, the program should ask them to re-enter their guess until they enter a valid guess.)

Extension Task #2


Add some code so that when the 5 rounds are over, the user is given the option to either start a new game or to quit.
unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: