More results...

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

Stopwatch Class (JavaScript)

stopwatch-classIn this challenge we will create an interactive stopwatch using HTML, CSS and JavaScript. The aim of this blog post is to use Object Oriented Programming to create our own Stopwatch class.

Step 1: Stopwatch Class and its constructor

First we will create a class for our stopwatch and use its constructor to initialise all the properties of the class as follows:

  • state: the state of the stopwatch, either “paused” or “running”, initially set to “paused”.
  • delay: the delay/interval in ms between two “ticks” of the stopwatch. This defines the accuracy of the stopwatch. Per default it will be set to 100ms.
  • value: the number of milliseconds the stopwatch has been running for. Initialised to 0ms.
  • display: the HTML element where the stopwatch value will be displayed.

Here is the JavaScript code of our stopwatch so far:

class Stopwatch {
  constructor(id, delay=100) { //Delay in ms
    this.state = "paused";
    this.delay = delay;
    this.display = document.getElementById(id);
    this.value = 0;
  }
}

We can then create an HTML element (DIV tag) that will be used to display the stopwatch value.

<div id="stopwatch">00:00:00.0</div>

We can then create a stopwatch object/instance of the Stopwatch class as follows:

stopwatch = new Stopwatch("stopwatch");

When creating our stopwatch object, the constructor of the class is automatically called to initialise the stopwatch.

At this stage nothing happens yet, as we have not defined any behaviours/methods to our Stopwatch class.

Notice the naming convention: when creating classes and objects it is good practice for the identifier of a class to start with an uppercase letter (e.g. Stopwatch) whereas identifiers used for objects start with a lowercase letter (e.g. stopwatch).

Step 2: Adding a few methods

The main methods of our Stopwatch class will be:

  • start(): to start/resume the stopwatch!
  • stop(): to stop/pause the stopwatch
  • reset(): to stop and reset the stopwatch to 0ms.
  • update(): to increment the stopwatch (based on the set delay) and refresh its display with the current value.

The update() method of the stopwatch will use an extra formatTime() method used to convert a number of milliseconds into the HH:MM:SS format.

Here is the full code for the Stopwatch class including all 5 methods:

class Stopwatch {
  constructor(id, delay=100) { //Delay in ms
    this.state = "paused";
    this.delay = delay;
    this.display = document.getElementById(id);
    this.value = 0;
  }
  
  formatTime(ms) {
    var hours   = Math.floor(ms / 3600000);
    var minutes = Math.floor((ms - (hours * 3600000)) / 60000);
    var seconds = Math.floor((ms - (hours * 3600000) - (minutes * 60000)) / 1000);
    var ds = Math.floor((ms - (hours * 3600000) - (minutes * 60000) - (seconds * 1000))/100);

    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    return hours+':'+minutes+':'+seconds+'.'+ds;
  }
  
  update() {
    if (this.state=="running") {
      this.value += this.delay;
    }
    this.display.innerHTML = this.formatTime(this.value);
  }
  
  start() {
    if (this.state=="paused") {
      this.state="running";
      if (!this.interval) {
        var t=this;
        this.interval = setInterval(function(){t.update();}, this.delay);
      }
    }
  }
  
  stop() {
       if (this.state=="running") {
      this.state="paused";
    if (this.interval) {
      clearInterval(this.interval);
      this.interval = null;
    }
       }
  }
  
  reset() {
    this.stop();
    this.value=0;
    this.update();
  }
}

Note that the setInterval() function used in the start() method is used to constantly call the update() method at the specified interval/delay (in milliseconds).

Step 3: Using the stopwatch object

We have already (see step 1) created our stopwatch object using the following JavaScript code:

stopwatch = new Stopwatch("stopwatch");

We can now add three buttons in HTML to trigger the start(), stop() and reset() methods of our object:

<div id="stopwatch">00:00:00.0</div>
<button onclick="stopwatch.start();">Start</button> 
<button onClick="stopwatch.stop();">Stop</button>
<button onClick="stopwatch.reset();">Reset</button>
</div>

HTML – CSS & JavaScript Code

Here is the full code for our stopwatch with some extra CSS to improve the look & feel of our stopwatch.

See the Pen
Stopwatch Class
by 101 Computing (@101Computing)
on CodePen.

Your Challenge

Your challenge is to adapt this code to create a new timer class.
The timer will have the same look & feel as the stopwatch, but instead of counting up, it will count down from a pre-set time (e.g. 1 minute timer, 5 minute timer). The user should be able to set the pre-set time for the timer and start/pause/reset the timer using control buttons. The timer should automatically stop when it reaches 00:00:00.0.

Tagged with:

Poker Card Game (JavaScript)

playing-cardsIn this challenge we will create a one-player game of poker based on the rules of Texas Hold’em Poker.

In a game of Texas Hold’em Poker, for each round, five “community cards” are dealt face-up on the “board”. Each player is then dealt two private cards. All players in the game can use the “community” cards alongside their own private cards to make their best possible five-card poker hand.

At the start of each round, the 5 community cards are presented face-up. Players can only see their two private cards and can start betting. Then the first 3 cards of the board are revealed (The “flop”). Another round of betting can then take place. Then the 4th card is revealed (the “turn”), followed by another round of betting. The fifth card is then revealed (the “river”) and a final round of betting ensues. Finally the players who have not folded yet will reveal their cards and the player with the strongest hand wins the round.

The hands’ values are defined as follows: (From weakest to strongest)

  1. High card: Simple value of the card. Lowest: 2 – Highest: Ace
  2. Pair: Two cards with the same value
  3. Two pairs: Two sets of two cards with the same value
  4. Three of a kind: Three cards with the same value
  5. Straight: Sequence of 5 cards in increasing value (Ace can precede 2 and follow up King)
  6. Flush: 5 cards of the same suit
  7. Full house: Combination of three of a kind and a pair
  8. Four of a kind: Four cards of the same value
  9. Straight flush: Straight of the same suit
  10. Royal flush Straight: flush from Ten to Ace

JavaScript implementation

We will create our game using HTML, CSS and JavaScript.

Our JavaScript code will use two main classes as follows:
deck-card-classes

Deck ClassCard ClassMain Code
class Deck {
    constructor() {
    this.deck = [];
    this.reset(); //Add 52 cards to the deck
    this.shuffle(); //Shuffle the deck
  } //End of constructor
  
  
  reset() {
    this.deck = [];
    const suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades'];
    const values = ['Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King'];

    for (let suit in suits) {
      for (let value in values) {
        this.deck.push(values[value] + " of " + suits[suit]);
      }
    }
  } //End of reset()
  
  
  shuffle() {
    let numberOfCards = this.deck.length;  
    for (var i=0; i<numberOfCards; i++) {
      let j = Math.floor(Math.random() * numberOfCards);
      let tmp = this.deck[i];
      this.deck[i] = this.deck[j];
      this.deck[j] = tmp;
    }
  } //End of shuffle()
  
  deal(){
    return this.deck.pop();
  } //End of deal()
  
  isEmpty() {
    return (this.deck.length==0);
  } //End of isEmpty()
  
  length() {
    return this.deck.length;
  }
  
} //End of Deck Class
class Card {
  constructor(card) {
      this.card = card;
      const cardValues = {"Ace of Hearts":1, "2 of Hearts":2, "3 of Hearts":3, "4 of Hearts":4, "5 of Hearts":5, "6 of Hearts":6, "7 of Hearts":7, "8 of Hearts":8, "9 of Hearts":9, "10 of Hearts":10, "Jack of Hearts":11, "Queen of Hearts":12, "King of Hearts":13, "Ace of Diamonds":1, "2 of Diamonds":2, "3 of Diamonds":3, "4 of Diamonds":4, "5 of Diamonds":5, "6 of Diamonds":6, "7 of Diamonds":7, "8 of Diamonds":8, "9 of Diamonds":9, "10 of Diamonds":10, "Jack of Diamonds":11, "Queen of Diamonds":12, "King of Diamonds":13, "Ace of Clubs":1, "2 of Clubs":2, "3 of Clubs":3, "4 of Clubs":4, "5 of Clubs":5, "6 of Clubs":6, "7 of Clubs":7, "8 of Clubs":8, "9 of Clubs":9, "10 of Clubs":10, "Jack of Clubs":11, "Queen of Clubs":12, "King of Clubs":13, "Ace of Spades":1, "2 of Spades":2, "3 of Spades":3, "4 of Spades":4, "5 of Spades":5, "6 of Spades":6, "7 of Spades":7, "8 of Spades":8, "9 of Spades":9, "10 of Spades":10, "Jack of Spades":11, "Queen of Spades":12, "King of Spades":13};
    
    this.value = cardValues[card];
    this.suit = card.substring(card.indexOf(" of ")+4);
    this.placeHolder = null;
    this.flipped = false;
  
    var suits = {'Hearts':0, 'Diamonds':13, 'Clubs':26, 'Spades':39 }
    this.position = suits[this.suit] + this.value; //Position in a sorted deck
  } //End of Constructor
  
  displayCard(placeHolder,flipped=true) {
    this.placeHolder = document.getElementById(placeHolder);
    this.placeHolder.classList.add("card");
    this.flipped=flipped;
    if (flipped) {
      this.placeHolder.style.backgroundPosition = -150*this.position + "px";
    } else {
      this.placeHolder.style.backgroundPosition = "0px";  
    }
  }
  
  flip() {
    if (this.flipped) {
      this.placeHolder.style.backgroundPosition = "0px";
      this.flipped=false;
    } else {
      this.placeHolder.style.backgroundPosition = -150*this.position + "px";
      this.flipped=true;  
    }
  } //End of flip()
  
} //End of Card class
const deck = new Deck();
let card1,card2,card3,card4,card5,playerCard1,playerCard2;

function deal() {
  if (deck.length()<7) {
    deck.reset();
    deck.shuffle();
  }  
  card1 = new Card(deck.deal());
  card2 = new Card(deck.deal());
  card3 = new Card(deck.deal());
  card4 = new Card(deck.deal());
  card5 = new Card(deck.deal());
  playerCard1 = new Card(deck.deal());
  playerCard2 = new Card(deck.deal());
  
  card1.displayCard("card1",false);  
  card2.displayCard("card2",false);  
  card3.displayCard("card3",false);  
  card4.displayCard("card4",false);  
  card5.displayCard("card5",false);  
  playerCard1.displayCard("playerCard1",true);  
  playerCard2.displayCard("playerCard2",true); 
} //End of deal()

function nextStep(el) {
  if (!card1.flipped) {
    card1.flip();
    card2.flip();
    card3.flip();
    el.innerHTML="Reveal 4<sup>th</sup> card";
  } else if(!card4.flipped) {
    card4.flip();
    el.innerHTML="Reveal 5<sup>th</sup> card";
} else if(!card5.flipped) {
    card5.flip();
    el.innerHTML="New Round";
} else {
  deal();
  el.innerHTML="Reveal first 3 cards.";
}
} //End of nextStep()

deal();
//The user then clicks the button to call the nextStep() function...

Your Challenge

We have started the code for you. Investigate how this code works and how the Deck class and the Card class have been implemented and used in the game.

The code is incomplete as it does not output the hand’s value at the end of the round. Complete this code to work out and output the hand’s value.

See the Pen
Poker Card Game
by 101 Computing (@101Computing)
on CodePen.


Note that this script uses one picture. In case this picture is not displaying properly, you may have to replace its URL in the CSS code, using the following address:

Note that the following picture gives you additional information on how each card is displayed using a single picture (png file) containing all 52 cards. The right section of the picture is displayed by re-positioning (translating) the background image to match the position of the desired card (using the background-position-x CSS property of the card):
card-css

Tagged with:

Stacks and Queues in LMC

In this post we will investigate how to implement a queue and a stack data structure using low-level programming. We will use an upgraded version of Little Man Computer (LMC) that supports indirect addressing to to do.

Implementing a Queue in LMC


A queue is a FIFO data structure: First-In First-Out in other words, it is used to implement a first come first served approach. An item that is added (enqueue) at the end of a queue will be the last one to be accessed (dequeue).

queue-diagram

Two pointers are needed to implement a queue data structure: A front pointer which holds the memory address of the first item of the queue and a rear pointer which holds the memory address of the last item of the queue.

When implementing a Queue data structure we need to implement two algorithms/functions to enqueue a new value at the end of the queue and to dequeue a value from the front of the queue.

Algorithm to enqueue a value to a queue:

FUNCTION ENQUEUE(value):
     If queue IS NOT FULL:
            rearPointer = rearPointer + 1
            queue[rearPointer] = value

Algorithm to dequeue a value from a queue:

FUNCTION DEQUEUE():
     If queue IS NOT EMPTY:
            value = queue[frontPointer]
            frontPointer = frontPointer + 1
            RETURN value

Low Level Implementation of a queue using LMC:

menu    INP
        SUB one
        BRZ enqueue 
        SUB one 
        BRZ dequeue
        BRA exit
	
exit    HLT
 
enqueue LDA max
        SUB rear
        BRZ full
        INP
        STA @rear
        LDA rear
        ADD one
        STA rear
        BRA menu

full    LDA error1
        OUT
        BRA menu

dequeue LDA front
        SUB rear
        BRZ empty
        LDA @front
        OUT
        LDA front
        ADD one
        STA front
        BRA menu

empty   LDA error2
        OUT
        BRA menu

front   DAT 50
rear    DAT 50 
one     DAT 1 
max     DAT 100 
error1  DAT -1  
error2  DAT -2

The above algorithm works as follows:

  • The user needs to input one of the following three menu options:
    • 1: To enqueue a new value,
    • 2: To dequeue a value,
    • Any other value: To exit the program.
  • If the user opts for option 1, they will then need to input the value to enqueue. They will then be redirected to the start of the program to input their next option from the menu. If the queue is full, the program will output the error code -1. The queue will be stored in memory starting at memory location 50. The queue will be full once it reaches memory location 99.
  • If the user opts for option 2, a value will be removed from the queue and displayed as an output. They will then be redirected to the start of the program to input their next option from the menu. If the queue is empty, the program will output the error code -2.
  • The program will stop if the user selects a value different from 1 or 2 from the menu.

Direct vs indirect addressing:
The LMC language was initially implemented to only support direct addressing: Each operand is a memory location of where the data to be used is stored. However to access the value stored at the front (dequeue) or rear (enqueue) memory locations of the queue it is necessary to use indirect addressing. The above code will hence only work with an LMC simulator that supports indirect addressing. In the code above the @ sign is used to indicate when indirect addressing is used. The following page gives more explanations of the main memory address modes used in low-level languages.

You can try code provided above in our LMC simulator as it does support indirect addressing:
LMC SimulatorOpen in New Window

Test Plan:

Test # Input Values Expected Output Pass/Fail?
#1 1,10 – 1,11 – 1,12 – 2 – 2 – 2 – 2 – 3 LMC-Queue-Test-2
#2 1,1 – 1,2 – 1,3 – 2 – 1,4 – 2 – 1,5 – 2 – 3 LMC-Queue-Test-1

Implementing a Stack in LMC


A stack is a FILO data structure: First-In Last-Out. Imagine a stack of books piled up on a table. When you add (push) a book on top of the pile, it will be the first book that you will then take (pop) from the pile (stack).

stack-diagram

Only one pointer is needed to implement a stack data structure: An End of Stack pointer which holds the memory address of the last item of the stack.

When implementing a Stack data structure we need to implement two algorithms/functions to push a new value at the end of the stack and to pop a value from the end of the stack.

Algorithm to push a value to a stack:

FUNCTION PUSH(value):
     If stack IS NOT FULL:
            stackPointer = stackPointer + 1
            stack[stackPointer] = value

Algorithm to pop a value from a stack:

FUNCTION POP():
     If stack IS NOT EMPTY:
            value = stack[stackPointer]
            stackPointer = stackPointer - 1
            RETURN value

Your Challenge:
Your challenge is to adapt the code given to implement a queue in order to implement a stack instead. You will need to apply the right terminology (push and pop instead of enqueue and dequeue) and apply the above two algorithms in LMC.

Tagged with:

Algebraic Pyramid Challenge

algebraic-pyramidFor the purpose of this challenge we will use algebraic pyramids pointing downwards (or upside down pyramids!).

The idea of this mathematical puzzle is to fill in all the bricks of a pyramid based on the following rule:

  • To work out the value of a brick, add the values of the two adjacent bricks above it.

algebraic-pyramid-rule

Python Challenge #1: Fix sized pyramids


This Python challenge will consist of writing a procedure that will take a list of values as a parameter, and will as a result generate and output an upside down pyramid where the top layer of the pyramid will contain all the values from the given list.

To simplify this problem, we will first assume that the list of number will always contains exactly 4 values.
For example:
algebraic-pyramid-list

The output of our procedure should be as follows:
algebraic-pyramid

Challenge #1: Python Code:


You will need to complete the following python code to work out and print all the layers of the pyramid.

Challenge #1: Test Plan


Check that your code is working using the following list of 4 values.

Test # List Expected Output Pass/Fail?
#1 [4,6,8,2] algebraic-pyramid-test-2
#2 [30,12,10,5] algebraic-pyramid-test-1
#3 [3,6,9,12] algebraic-pyramid-test-3

Challenge #2: Using lists of different sizes


The second challenge consists of adapting the code from challenge 1 to make sure that it works for any list (of any length) of values.

Challenge #2: Test Plan

Test # List Expected Output Pass/Fail?
#1 [3,6,9] algebraic-pyramid-test-3-layers
#2 [30,12,10,5] algebraic-pyramid-test-1
#3 [1,2,3,4,5,6] algebraic-pyramid-test-6-layers
Tagged with:

Bracket Validator

bracketsThe aim of this Python Challenge is to write a script to validate an arithmetic expression by checking that it has a valid sequence of opening and closing brackets.

Let’s consider the following arithmetic expressions to decide whether they contain a valid or invalid combination of brackets:

Arithmetic Expression Valid/Invalid? Justification
(5+2)/3 Valid
(((5+2)/3)-1)*4 Valid
(5+2)*(3+4) Valid
(5+2 Invalid Missing closing bracket
(5+2)*)3+4( Invalid Invalid use of brackets
(5+2)/3)-1 Invalid Missing an opening bracket

Opening & Closing Brackets Count

In order to validate whether an expression is valid or not, we could count the number of opening brackets and the number of closing brackets and see if both numbers are the same. Though this would detect a lot of invalid expressions, not all invalid expressions would be detected. For instance, using this approach, the expression (5+2)*)3+4( would appear valid as it contains 2 opening brackets and 2 closing brackets.

Using a stack

A more effective approach is to parse the expression one character at a time and every time an opening bracket is met, the bracket is pushed into a stack. Every time a closing bracket is found, we pop the last opening bracket from the stack (if when a closing bracket is met, the stack is empty then the expression is invalid). Once all characters of the expression have been checked, the stack should be empty. If not the expression is invalid.

Here is the implementation of this approach in Python:

Using multiple types of brackets

More complex expressions may use different types of brackets such as square brackets [], curly brackets {} and parentheses (). We can adapt our script to validate an expression by making sure that when a closing bracket is found, the algorithm checks that it is of the same type as the last bracket that has been pushed into the stack.

Proportions and cross products

A proportion is simply a statement that two ratios are equal. The following are examples of proportions:

  • 1/4 = 25/100
  • 8/24 = 1/3
  • 40/60 = 2/3

Proportions are often use in Maths to simplify a fraction or to represent a fraction as a percentage.
percentage

In order two find out if two fractions are equal, we can use one of the following three methods:

  • Calculate and compare their decimal values: e.g. 25/100 = 0.25 and 1/4 = 0.25 so 25/100 = 1/4
  • Simplify both fractions: e.g. 75/100 = 3/4 and 18/24 = 3/4 so 75/100 = 18/24
  • Compare cross products: e.g. 3 x 6 = 2 x 9 so 2/6 = 3/9

Cross Products


You can compare two fractions to find out if they are equal or not if their cross products are equal:
cross-products

Python Challenge


Your aim is to write a Python program that will check if two fractions are equal or not using the cross products approach. The program will take 4 inputs: the numerator and denominator of both fractions.
It will then compare the cross products to decide and output if the two fractions are equal or not.

You will not to complete the following code:

Test Plan


Complete the following tests to check that your code is working as expected:

Test # Input Values Expected Output Actual Output
#1 Fraction #1: 4/6
Fraction #2: 20/30
These fractions are equal.
#2 Fraction #1: 4/6
Fraction #2: 20/40
These fractions are not equal.
#3 Fraction #1: 75/100
Fraction #2: 3/4
These fractions are equal.
#4 Fraction #1: 1/3
Fraction #2: 30/100
These fractions are not equal.
unlock-access

Solution...

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

Linked Lists

A linked-list is a dynamic data structure used in computer science. It consists of a collection of nodes where each node contains a piece of data (value) and a pointer (memory location) to the next node in the list.

The first node of the list is called the head, whereas the last node is the tail.
linked-list

The following tables represent how the above linked list is stored in memory:

Memory Address linked-list-nodeNode Value linked-list-pointerPointer
0 21 1
1 35 2
2 47 3
3 89 Null

The linked-list data structure is more flexible than the array data structure as it allows for efficient insertion or removal of elements from any position in the sequence.

Inserting a value in a linked list:

Let’s see how we can add the value 52 in the correct (sorted) position:
linked-list-before-insertion
linked-list-after-insertion
As you cans see on the table below, we have been able to add the value 52 to the linked list, in the desired position, without the need to move any other value in memory. The pointer of the previous node in the list has been updated accordingly.

Memory Address linked-list-nodeNode Value linked-list-pointerPointer
0 21 1
1 35 2
2 47 4
3 89 Null
4 52 3

Though the data does not appear to be sorted in memory, the use of pointers enables the linked-list to have its own sequence. This makes the process of inserting and removing values from a linked list far more efficient as it does not require other values to be moved around in memory (a fairly slow process when manipulating a large amount of data).

Removing a value from a linked list:

Let’s now remove value 35 from the list:
linked-list-deletion

Memory Address linked-list-nodeNode Value linked-list-pointerPointer
0 21 2
1 35 2
2 47 4
3 89 Null
4 52 3

Circular list

Imagine all the children in the “pass the parcel” game. The parcel is passed around the children and when the last child receives the parcel, they then pass it on back to the first child in the list.

A circular list is when the pointer of the tail node points towards the head node of the linked list.
circular-list

Memory Address linked-list-nodeNode Value linked-list-pointerPointer
0 21 1
1 35 2
2 47 3
3 89 0

Double linked list

A double linked list uses two pointers per node, one pointer pointing towards the next node in the list and one pointer pointing towards the previous node in the list. It makes it easier to “navigate through” the list in both directions!
double-linked-list

Memory Address linked-list-nodeNode Value linked-list-previous-pointerPrevious Node Pointer linked-list-pointerNext Node Pointer
0 21 Null 1
1 35 0 2
2 47 1 3
3 89 2 Null

Circular Double linked list

A Circular double linked list is when the tail node points back to the head node and vice versa:
circular-double-linked-list

Memory Address linked-list-nodeNode Value linked-list-previous-pointerPrevious Node Pointer linked-list-pointerNext Node Pointer
0 21 3 1
1 35 0 2
2 47 1 3
3 89 2 0

Other use of linked lists…

Linked-lists can be used to implement more abstract data types such as queues, stacks and binary trees.

XOR Encryption Algorithm

The XOR Encryption algorithm is a very effective yet easy to implement method of symmetric encryption. Due to its effectiveness and simplicity, the XOR Encryption is an extremely common component used in more complex encryption algorithms used nowadays.

The XOR encryption algorithm is an example of symmetric encryption where the same key is used to both encrypt and decrypt a message.

Symmetric Encryption: The same cryptographic key is used both to encrypt and decrypt messages.

Symmetric Encryption: The same cryptographic key is used both to encrypt and decrypt messages.

The XOR Encryption algorithm is based on applying an XOR mask using the plaintext and a key:

Reapplying the same XOR mask (using the same key) to the cipher text outputs the original plain text. The following truth table (based on the XOR truth table) demonstrates how the encryption process works.

P (Plain text) K (Key) C (Cipher)
=
P XOR K
K (Key) P (Plain Text)
=
C XOR K
0 0 0 0 0
1 0 1 0 1
0 1 1 1 0
1 1 0 1 1

The XOR encryption algorithm can be applied to any digital/binary information, included text based information encoded using the 8-bit ASCII code. In this case the encryption key can be expressed as a string of characters.

By itself, the XOR encryption can be very robust if:

  • It is based on a long key that will not repeat itself. (e.g. a key that contains as many bits/characters as the plaintext)
  • A new key is randomly generated for any new communication.
  • The key is kept secret by both the sender and the receiver.

When a large quantity of text is to be encrypted, a shorter repeating encryption key is used to match the length of the plain text. However re-using the same key over and over, or using a shorter repeating key results in a less secure method where the cipher text could be decrypted using a frequency analysis.
xor-encryption-keys

Python Code


In this Python code we are using the XOR bitwise operator (in Python: ^) to apply the XOR mask using the plain text and the key.

To improve readability, we are displaying the cipher text in different format: Ascii, Denary, Hexadecimal and Binary format.

Tagged with: ,

Eureka! (and King Hiero’s Crown)

Archimedes is one of the most famous physicist, mathematician, astronomer and inventor of the classical age.

Archimedes is one of the most famous physicist, mathematician, astronomer and inventor of the classical age.

Did you know?


Archimedes is one of the most famous physicist, mathematician, astronomer and inventor of the classical age: He lived in Syracuse on the island of Sicily in the third century B.C. Many of his inventions and theories are still being used today.

This Python challenge will be based on Archimedes’ most famous “Eureka!” moment: At the time, Hiero, The King of Syracuse (Sicily, Italy), had given his goldsmith some pure gold and asked him to make a crown out of this gold. On reception of the crown, Hiero suspected he had been cheated by the goldsmith. He believe the goldsmith had replaced some of the pure gold with the same weight of silver. However Hiero needed to be able to prove that his suspicion was correct and that the crown was not made of pure gold.

Knowing the weight/mass of the crown was not enough to confirm whether the crown was made of pure gold (as opposed to a mix of gold and silver). However if Archimedes knew that if he could accurately measure the volume of the crown, he could work out its density. (Density = mass / volume). He could then compare this density with the density of pure gold to see if they are the same. If not, this would be the proof that the crown is not just made of pure gold which would confirm Hiero’s suspicion. The issue was that, though it was easy at the time to precisely measure the mass of an object, there was no method for working out the exact volume of an irregular object (such as a crown!).

It’s while stepping into a bath that Archimedes noticed that the water level rose: he immediately deducted that the volume of water displaced must be equal to the volume of the part of his body he had submerged. He then realised that the volume of irregular objects could be measured with precision using this submersion approach. He is said to have been so eager to share his discovery that he leapt out of his bathtub and ran naked through the streets of Syracuse shouting Eureka! Eureka! (Greek for “I have it!”).

The volume of an object is equal to the volume of the water displaced when this object is submerged.

The volume of an object is equal to the volume of the water displaced when this object is submerged.

By applying this approach to the golden crown, Archimedes was able to get an accurate measure of the volume of the crown and could hence calculate the density of the crown which effectively turned out to be of a lesser density than pure gold. This confirmed Hiero’s suspicion that his goldsmith had stolen some of the pure gold he was given to make this crown!

Python Challenge


In this Python challenge we will use a program to help identify the density of an object and compare with the known density of different metals such as gold, silver, bronze, etc.

Our algorithm will:

  1. Ask the user to enter the mass of an object. (in Kg)
  2. Ask the user to enter the volume of an object. (in m3)
  3. Calculate and output the density of this object (mass/volume)
  4. Compare this density with the densities of different metals such as pure gold, silver and bronze and output the corresponding metal if there is a match.

Our algorithm will use the following data:

Metal Density
Aluminium Between 2400 kg/m3 and 2700 kg/m3
Bronze Between 8100 kg/m3 and 8300 kg/m3
Silver Between 10400 kg/m3 and 10600 kg/m3
Lead Between 11200 kg/m3 and 11400 kg/m3
Gold Between 17100 kg/m3 and 17500 kg/m3
Platinum Between 21000 kg/m3 and 21500 kg/m3

Your Challenge


Complete the code below and use your code to work out what the following four crowns are made of…

Test # Object Input Values Output
#1 crown-1 Mass:0.567kg
Volume: 54cm3 = 0.000054m3
#2 crown-2 Mass:1.213kg
Volume: 70cm3 = 0.00007m3
#3 crown-3 Mass:0.731kg
Volume: 65cm3 = 0.000065m3
#4 crown-4 Mass:0.585kg
Volume: 71cm3 = 0.000071m3

Python Code


You will need to complete the code provided below:

unlock-access

Solution...

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

Searching & Sorting Algorithms Practice

weather-chartThe searching and sorting algorithms are key algorithms that you will study in computer science. Most computer programs involve some searching and sorting features so these key algorithms are often used when coding various computer programs. Searching and sorting algorithms are also useful to develop your algorithmic thinking skills and your ability to compare and evaluate the effectiveness of an algorithm to perform a specific task.

You will find in this blog a range of activities on sorting and searching algorithms. This online task will help you demonstrate or practise your understanding of the key searching and sorting algorithms by applying these to a list of 10 randomly generated numerical values.

Practise your Searching & Sorting Algorithms online
Linear SearchBinary SearchInsertion SortBubble SortMerge SortQuick Sort
card-sort-linear-search
card-sort-binary-search
card-sort-insertion-sort
card-sort-bubble-sort
card-sort-merge-sort
card-sort-quick-sort
Tagged with: