Page 2 of 4 FirstFirst 1234 LastLast
Results 11 to 20 of 32

Thread: Beginner's Programming Challenge 18

  1. #11
    Join Date
    Oct 2007
    Beans
    74

    Re: Beginner's Programming Challenge 18

    Correct me if I'm wrong, but is this not an exact duplicate of a previous challenge?
    See: http://ubuntuforums.org/showthread.php?t=772016

  2. #12
    Join Date
    Jul 2007
    Location
    Austin, TX
    Beans
    Hidden!
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: Beginner's Programming Challenge 18

    Quote Originally Posted by sharpdust View Post
    Correct me if I'm wrong, but is this not an exact duplicate of a previous challenge?
    See: http://ubuntuforums.org/showthread.php?t=772016
    So much more activity back then. What happened to budding linux programmers?

  3. #13
    Join Date
    Apr 2008
    Beans
    286

    Re: Beginner's Programming Challenge 18

    Quote Originally Posted by sharpdust View Post
    Correct me if I'm wrong, but is this not an exact duplicate of a previous challenge?
    See: http://ubuntuforums.org/showthread.php?t=772016
    I had no idea, lol!

  4. #14
    Join Date
    Jun 2006
    Beans
    596
    Distro
    Kubuntu

    Re: Beginner's Programming Challenge 18

    My entry in ruby 1.9.x.
    Features:
    • prompts (as specified in the task! )
    • simultaneous encoding and decoding (accepts a ciphertext or plaintext message)
    • no hard-coded 'magic numbers'

    Code:
    #!/usr/bin/env ruby
    
    alphabet_length = 'Z'.ord - 'A'.ord + 1
    ciphertext = ""
    plaintext = ""
    
    print "Enter message: "
    message = gets.chomp
    print "Enter key: "
    key = gets.chomp
    
    # generate the key. it's not truncated to the message length.
    key = key * (message.size/key.size + 1)
    
    # split the message into an array of single-character strings, then iterate the
    # message array and key simultaneously, (en|de)coding as we go.
    message.split(//).each_with_index do |c,i|
    
      if (encoded_byte = c.ord + key.getbyte(i) - 'A'.ord) > 'Z'.ord
        encoded_byte -= alphabet_length
      end
      ciphertext << encoded_byte
    
      if (decoded_byte = c.ord - key.getbyte(i) + 'A'.ord) < 'A'.ord
        decoded_byte += alphabet_length
      end
      plaintext << decoded_byte
    end
    
    puts "Encoding: #{ciphertext}"
    puts "Decoding: #{plaintext}"
    Usage example:
    Code:
    $ ./vig.rb 
    Enter message: ATTACKATDAWN
    Enter key: LEMON
    Encoding: LXFOPVEFRNHR
    Decoding: PPHMPZWHPNLJ
    $ ./vig.rb 
    Enter message: LXFOPVEFRNHR
    Enter key: LEMON
    Encoding: WBRCCGIRFASV
    Decoding: ATTACKATDAWN
    $
    Last edited by krazyd; January 25th, 2011 at 05:02 PM.

  5. #15
    Join Date
    Aug 2005
    Location
    Sweden
    Beans
    407

    Re: Beginner's Programming Challenge 18

    Entering in the obscure languages division: gforth!
    you can run it with $ gforth vignere.fs (assuming you call the code file vignere.fs)
    Code:
    \ longest message we accept
    : buf-size 1024 chars ;
    
    \ reads a line from input into a string
    \ allocating a buffer for maxlen chars
    \ and resizes the string afterwards
    : read-string ( maxlen | "name" -- )
    create
        dup chars allocate ( maxlen addr wior )
        if ." memory allocation failure" 1 throw then
        dup rot ( addr addr maxlen )
        accept swap over ( newsize addr newsize )
        chars resize ( newaddr newsize wior )
        if ." memory resize failure" 2 throw then
        , ,
    does>
        dup @ swap cell+ @
    ;
    
    \ creates a keyword that each time when activated returns the next
    \ character in the string, restarting at the first character after
    \ rearching the end
    : mk-stringiterator ( addr len / "name" -- )
    create
        1- 0 ( addr length offset )
        , , ,
        ( map of varsis [ offset, length, addr ] - so base addr is vars )
    does>
        >r ( r:base )
    
        r@ @ chars ( char-offset )
        r@ 2 cells + @  ( char-offset char-addr )
        + c@ ( key-char )
    
        r@ dup @ swap 1 cells + @ over ( key-char offset length offset )
        > if 1+ else drop 0 then  ( key-char newoffset )
        r> ! ( key-char )
    ;
    
    \ converts a charecter to upercase
    \ bluntly assuming that it is a letter
    : to-uppercase
        dup 96 > 32 * +
    ;
    
    : encrypt ( msg-xt key-xt len -- addr )
        dup chars allocate ( msg-xt key-xt len addr wior )
        if ." memory allocation failure" 1 throw then
        ( msg-xt key-xt len addr )
        swap 0 do ( msg-xt key-xt addr )
            -rot dup execute to-uppercase 65 - ( addr msg-xt key-xt keych )
            rot dup execute to-uppercase 65 - ( addr key-xt keych msg-xt msgch )
            rot + 26 mod 65 + ( addr key-xt msg-xt resch )
            2swap -rot dup ( msg-xt key-xt resch addr addr )
            i chars + ( msg-xt key-xt resh addr next-addr )
            rot swap ! ( msg-xt key-xt addr )
        loop
        nip nip
    ;
           
    
    cr ." Please enter the key and press enter: " cr
    buf-size read-string encryptionkey
    cr ." Please enter the message and press enter: " cr
    buf-size read-string message
    
    encryptionkey mk-stringiterator keykey
    message mk-stringiterator msgkey
    
    ' msgkey ' keykey message nip encrypt
    dup message nip
    cr cr ." The encrypted message is" cr cr ." <" type ." >" cr cr
    
    encryptionkey drop message drop
    free free free
    
    bye
    Don't peach linux. Melon it!

  6. #16
    Join Date
    Aug 2005
    Location
    Sweden
    Beans
    407

    Re: Beginner's Programming Challenge 18

    Another one, this one in perl, a golfed (readability sacrificed for terseness)
    one, but for clarity's sake I've made one that works the same way, but is
    expanded and with comments.

    Short; the actual cipher substitution happens on line 9 only.
    Code:
    #!/usr/bin/env perl
    use warnings;
    use strict;
    print "Enter key please:\n";
    my @k = split '', <>;
    print "Enter message please:\n";
    my @m = split '', <>;
    print "Result:\n";
    print chr(((ord($m[$_])+ord($k[$_%$#k])-130)%26)+65) for 0..$#m-1;
    print "\n";
    Longer version, I haven't actually tested it, but it should work exactly
    the same, only that I buffer the first input line in a temporary variable
    for clarity.
    Code:
    #!/usr/bin/env perl                 # just tell bash that it is a perl program
    use warnings;                       # yell if I do something bad
    use strict;                         # be less permissive than default
    print "Enter key please:\n";        # text output
    my $line = <>;                      # define a scalar line, and read one line
                                        # from stdin into it
    my @k = split '', $line             # define an array and split $line into
                                        # individual chars and store into it
    print "Enter message please:\n";
    my @m = split '', <>;               # shorter version of the above
    print "Result:\n";
    
    
    # start a for loop, the loop variable is $_ by default, and it will iterate
    # through the values 0 to the index of the last value in @m minus 1:
    # if we have the array @a, then $#a will be the index of the last item in @a
    # ( we included '\n' when we read from stdin before, but we don't want it in
    # the cipher, so for a string 'FOO\n' => ('F', 'O', 'O', '\n') we want to
    # get the chars at 0, 1, 2 == 0..$#m-1 !!
    
    for (0..$#m-1) {
    print chr(
            (
                (
                    ord(        # ord get's the ascii value of a char  
                        $m[$_]) # if we have the array @a $a[4] will get the item at position 4 in @a
                    +ord(
                        $k[$_%$#k]) # modulus with length of key, since keylength can be < messagelength
                    -130        # same as -65 -65 to make A<->0 B<->1 etc ('A' has 65 as ascii value)
                )       # now we have summed the numerical values of the message char and the right key char
                % 26    # to keep the value from overflowing
            ) +65       # to convert back so that A<->65 B<->66 etc
        );
    }
    print "\n";
    Last edited by red_Marvin; January 29th, 2011 at 01:21 AM.
    Don't peach linux. Melon it!

  7. #17
    Join Date
    Mar 2006
    Location
    ~/
    Beans
    70
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: Beginner's Programming Challenge 18

    I'm not sure if this is still open, but I went ahead and gave it a try in Ada. It's not as short as the others, but I hope it is still readable.

    Code:
    ----------------------------------------------------------------------------
    --  Vigenère Cypher
    --
    --  compile with:
    --    gnatmake -gnat05 vigenere.adb
    --
    --------------------------------------------------------------------------
    
    with Ada.Text_IO;                   use  Ada.Text_IO;
    with Ada.Strings.Unbounded;         use  Ada.Strings.Unbounded;
    with Ada.Strings.Unbounded.Text_IO; use  Ada.Strings.Unbounded.Text_IO;
    with Ada.Command_Line;              use  Ada.Command_Line;
    with Ada.Characters.Handling;       use  Ada.Characters.Handling;
    
    --------------
    -- Vigenere --
    --------------
    
    procedure Vigenere is
    
       ---------------
       -- Variables --
       ---------------
    
       Keyword    : Unbounded_String;
       Input_Text : Unbounded_String;
       Decrypt    : Boolean := False;
    
       ----------------------
       -- Subprogram Specs --
       ----------------------
    
       function Rotate_Character (
          Msg     : Character;
          Key     : Character;
          Decrypt : Boolean  := False) return Character;
    
       function Cipher return Unbounded_String;
    
       -------------------------------------------------------------------------
    
       ---------------------
       -- Rotate_Character--
       ---------------------
    
       --  Find the encrypted (or decrypted) character from input and keyword
       --  characters.
       --  Encrypts input character unless Decrypt is set to True.
    
       function Rotate_Character (
          Msg     : Character;
          Key     : Character;
          Decrypt : Boolean  := False) return Character
       is
          Diff : Natural;
       begin
          --  Find the difference between the input and keyword characters.
          if Decrypt then
             Diff := (Character'Pos (Msg) - Character'Pos (Key)) mod 26;
          else
             Diff := (Character'Pos (Msg) + Character'Pos (Key)) mod 26;
          end if;
    
          --  Apply the difference to get the output character, and append it.
          return (Character'Val (Diff + Character'Pos ('A')));
       end Rotate_Character;
    
       ------------
       -- Cipher --
       ------------
    
       --  Encrypts input text unless Decrypt is set to True.
    
       function Cipher return Unbounded_String is
          Input_S   : constant String := To_String (Input_Text);
          Keyword_S : constant String := To_String (Keyword);
          Output    : Unbounded_String;
          Key_Char  : Character;
       begin
    
          for i in Input_S'Range loop
             --  Get the keyword character associated with the current input
             --  character. Keyword is repeated when its end is reached.
             Key_Char := Keyword_S (((i - 1) mod Keyword_S'Length) + 1);
    
             --  Get output character.
             Append (Output, Rotate_Character (Input_S (i), Key_Char, Decrypt));
          end loop;
    
          return Output;
       end Cipher;
    
       -------------------------------------------------------------------------
    
    begin
    
       --  If one or more args are given, the first is used as Decrypt,
       --  otherwise the default is used (encrypt).
       if Argument_Count >= 1 then
          if Argument (1) = "decrypt" or else Argument (1) = "d" then
             Decrypt := True;
          elsif Argument (1) = "encrypt" or else Argument (1) = "e" then
             Decrypt := False;
          else
             Put_Line ("Usage: vigenere [encrypt|decrypt] <keyword> <input>");
             return;
          end if;
       end if;
    
       --  If a second arg is given, it is used as the keyword.
       --  If not, then the user is prompted for the keyword.
       if Argument_Count >= 2 then
          Keyword := To_Unbounded_String (To_Upper (Argument (2)));
       else
          Put ("Keyword: ");
          Keyword := To_Unbounded_String (To_Upper (Get_Line));
       end if;
    
       --  All other arguments are used as input text.
       --  If no more are given, then the user is prompted for input.
       --  (Spaces are already removed and are not replaced.)
       if Argument_Count >= 3 then
          for i in Positive range 3 .. Argument_Count loop
             Append (Input_Text, To_Upper (Argument (i)));
          end loop;
       else
          Put ("Input Text: ");
          Input_Text := To_Unbounded_String (To_Upper (Get_Line));
       end if;
    
       --  Process the text.
       Put_Line (Cipher);
    
    end Vigenere;
    Here is a shorter version as well. About half the size, but i dont like it as much.
    Code:
    ----------------------------------------------------------------------------
    --
    --  Vigenère Cypher  (slightly shorter version)
    --
    --  compile with:
    --    gnatmake -gnat05 vig.adb
    --
    ----------------------------------------------------------------------------
    
    with Ada.Text_IO;             use  Ada.Text_IO;
    with Ada.Strings.Unbounded;   use  Ada.Strings.Unbounded;
    with Ada.Command_Line;        use  Ada.Command_Line;
    with Ada.Characters.Handling; use  Ada.Characters.Handling;
    
    procedure Vig is
    
       Keyword    : Unbounded_String;
       Input_Text : Unbounded_String;
       Decrypt    : Boolean := False;
    
       --  Encrypt or decrypt the input text.
       function Cipher return Unbounded_String is
          Input_S   : constant String := To_String (Input_Text);
          Keyword_S : constant String := To_String (Keyword);
          Output    : Unbounded_String;
          Key_Char  : Character;
          Diff      : Natural;
       begin
          for i in Input_S'Range loop
             --  Get the keyword character associated with the current input
             --  character. Keyword is repeated when its end is reached.
             Key_Char   := Keyword_S (((i - 1) mod Keyword_S'Length) + 1);
    
             --  Find the difference between the input and keyword characters.
             if Decrypt then
                Diff := (
                   Character'Pos (Input_S (i)) - Character'Pos (Key_Char)) mod 26;
             else
                Diff := (
                   Character'Pos (Input_S (i)) + Character'Pos (Key_Char)) mod 26;
             end if;
    
             --  Apply the difference to get the output character, and append it.
             Append (Output, Character'Val (Diff + Character'Pos ('A')));
          end loop;
    
          return Output;
       end Cipher;
    
    begin
       if Argument_Count = 0 then
          Put_Line ("Usage: vig [encrypt|decrypt] <keyword> <input>");
          return;
       end if;
    
       if Argument (1) = "decrypt" or else Argument (1) = "d" then
          Decrypt := True;
       end if;
    
       Keyword := To_Unbounded_String (To_Upper (Argument (2)));
    
       for i in Positive range 3 .. Argument_Count loop
          Append (Input_Text, To_Upper (Argument (i)));
       end loop;
    
       Put_Line (To_String (Cipher));
    end Vig;

  8. #18
    Join Date
    Aug 2007
    Location
    UK
    Beans
    427
    Distro
    Ubuntu UNR

    Re: Beginner's Programming Challenge 18

    Quote Originally Posted by Queue29 View Post
    So much more activity back then. What happened to budding linux programmers?
    Just a guess but I would say busy writing phone apps.

  9. #19
    Join Date
    May 2007
    Location
    Munich Germany
    Beans
    100
    Distro
    Ubuntu 15.10 Wily Werewolf

    Re: Beginner's Programming Challenge 18

    Here is my Java solution.

    I have also made a small UI in Swing

    Main Cipher class:
    Code:
    public class Cipher {
    
    	private String plainText;
    	private String key;
    	private char[][] vigenereTable;
    
    	private static final int rows = 26;
    	private static final int columns = 26;
    	private static final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    	/*
    	 * Constructor: initializes the Vigenere table and fills it
    	 */
    	public Cipher() {
    		this.vigenereTable = new char[rows][columns];
    		createVigenereTable();
    	}
    
    	/*
    	 * Creating the Vigenere Table
    	 */
    	public void createVigenereTable() {
    		int currentPos = 0;
    		for (int i = 0; i < rows; i++) {
    			for (int j = 0; j < columns; j++) {
    				currentPos = i + j;
    				if (currentPos >= alphabet.length()) {
    					currentPos = (-1) * (rows - (i + j));
    				}
    				vigenereTable[i][j] = alphabet.charAt(currentPos);
    			}
    		}
    	}
    
    	/*
    	 * Returns the line for the given character
    	 */
    	private int getLineForChar(String character) {
    		for (int i = 0; i < rows; i++) {
    			if (Character.toString(vigenereTable[i][0]).equals(character))
    				return i;
    		}
    		return 0;
    	}
    
    	/*
    	 * Returns the columns for the given character
    	 */
    	private int getColForChar(String character) {
    		for (int i = 0; i < columns; i++) {
    			if (Character.toString(vigenereTable[0][i]).equals(character))
    				return i;
    		}
    		return 0;
    	}
    
    	/*
    	 * Normalize the key
    	 */
    	public void normalizeTheKey(String plainText, String key) {
    		// repeate the key until it matches the length of the plainText
    		while (plainText.length() > key.length()) {
    			key += key;
    		}
    		setKey(key.substring(0, plainText.length()).toUpperCase());
    		setPlainText(plainText);
    	}
    
    	/*
    	 * Encripts the plainText parameter with the key, using the vigenereTable
    	 */
    	public String encrypt(String plainText, String key) {
    		String currentChar;
    		String encodedResult = "";
    		// loop through the plainText characters to encode them
    		for (int i = 0; i < plainText.length(); i++) {
    			currentChar = Character.toString(plainText.charAt(i)).toUpperCase();
    			encodedResult += vigenereTable[getLineForChar(currentChar)][getColForChar(Character
    					.toString(key.charAt(i)))];
    		}
    		return encodedResult;
    	}
    
    	public String decrypt(String encyiptedText, String key) {
    		String currentChar, currentKey;
    		String decryptedResult = "";
    		char decriptedChar = 'a';
    		// loop through the plainText characters to encode them
    		for (int i = 0; i < encyiptedText.length(); i++) {
    			currentChar = Character.toString(encyiptedText.charAt(i))
    					.toUpperCase();
    			currentKey = Character.toString(key.charAt(i));
    			// loop through the line of the encripted key
    			for (int j = 0; j < columns; j++) {
    				if (currentChar
    						.equals(Character
    								.toString(vigenereTable[getLineForChar(currentKey)][j]))) {
    					decriptedChar = vigenereTable[0][j];
    				}
    			}
    			decryptedResult += Character.toString(decriptedChar);
    		}
    		return decryptedResult;
    	}
    
    	public String getPlainText() {
    		return plainText;
    	}
    
    	public void setPlainText(String plainText) {
    		this.plainText = plainText;
    	}
    
    	public String getKey() {
    		return key;
    	}
    
    	public void setKey(String key) {
    		this.key = key;
    	}
    }
    Here is the Swing dialog

    Code:
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    
    public class VigenereUI extends JDialog {
    
    	private static final long serialVersionUID = 1L;
    	private Cipher cipher = new Cipher();
    	private GridBagLayout controlLayout = new GridBagLayout();
    	private JButton jBExit = new JButton("Exit");
    	private JButton jBGenerate = new JButton("Generate");
    	private JComboBox jCBCipherOption = new JComboBox();
    	private JTextField jTWorkingText = new JTextField(20);
    	private JTextField jTKeyText = new JTextField(20);
    	private JLabel jLResult = new JLabel();
    	private JLabel jLCipherTypeText = new JLabel("Text to encrypt");
    
    	public VigenereUI() {
    		super();
    		setTitle("Vigenère cipher");
    		setResizable(false);
    		fillCipherOptions();
    		jCBCipherOption.setPreferredSize(new Dimension(120, 20));
    		jBGenerate.setPreferredSize(new Dimension(100, 26));
    		jBExit.setPreferredSize(new Dimension(100, 26));
    		addComponentsToPane(getContentPane());
    
    	}
    
    	public void addComponentsToPane(final Container pane) {
    		pane.setLayout(controlLayout);
    		GridBagConstraints c = new GridBagConstraints();
    
    		c.weightx = 0.0;
    		c.gridwidth = 2;
    
    		c.gridx = 0;
    		c.gridy = 0;
    		c.insets = new Insets(10, 10, 10, 10);
    		pane.add(new JLabel("Cipher Type"), c);
    
    		c.gridx = 2;
    		c.gridy = 0;
    		pane.add(jCBCipherOption, c);
    
    		c.gridx = 0;
    		c.gridy = 1;
    		c.insets = new Insets(10, 10, 10, 10);
    		pane.add(jLCipherTypeText, c);
    
    		c.gridx = 2;
    		c.gridy = 1;
    		pane.add(jTWorkingText, c);
    
    		c.gridx = 0;
    		c.gridy = 2;
    		c.insets = new Insets(10, 10, 10, 10);
    		pane.add(new JLabel("Key"), c);
    
    		c.gridx = 2;
    		c.gridy = 2;
    		pane.add(jTKeyText, c);
    
    		c.gridx = 0;
    		c.gridy = 3;
    		pane.add(new JLabel("Result"), c);
    
    		c.gridx = 2;
    		c.gridy = 3;
    		pane.add(jLResult, c);
    
    		c.gridx = 0;
    		c.gridy = 4;
    		pane.add(jBGenerate, c);
    
    		c.gridx = 2;
    		c.gridy = 4;
    		pane.add(jBExit, c);
    
    		jBExit.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				dispose();
    			}
    		});
    		jCBCipherOption.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				if (jCBCipherOption.getSelectedItem().equals("Encrypt")) {
    						jLCipherTypeText.setText("Text to encrypt");
    				} else {
    					jLCipherTypeText.setText("Text to decrypt");
    				}
    			}
    		});
    		jBGenerate.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				if (jCBCipherOption.getSelectedItem().equals("Encrypt")) {
    					cipher.normalizeTheKey(jTWorkingText.getText(),
    							jTKeyText.getText());
    					jLResult.setText(cipher.encrypt(cipher.getPlainText(),
    							cipher.getKey()));
    				} else {
    					cipher.normalizeTheKey(jTWorkingText.getText(),
    							jTKeyText.getText());
    					jLResult.setText(cipher.decrypt(cipher.getPlainText(),
    							cipher.getKey()));
    				}
    			}
    		});
    
    		pack();
    		setVisible(true);
    
    	}
    
    	public void fillCipherOptions() {
    		jCBCipherOption.addItem("Encrypt");
    		jCBCipherOption.addItem("Decrypt");
    	}
    
    	public static void main(String args[]) {
    		java.awt.EventQueue.invokeLater(new Runnable() {
    			public void run() {
    				VigenereUI dialog = new VigenereUI();
    				dialog.addWindowListener(new java.awt.event.WindowAdapter() {
    					public void windowClosing(java.awt.event.WindowEvent e) {
    						System.exit(0);
    					}
    				});
    				dialog.setVisible(true);
    			}
    		});
    	}
    }
    I have also attached a few screenshots
    Attached Images Attached Images
    Intel i5 6500 | MSI z170a Gaming M5 | Corsair Vengence LPX 16Gb DDR4 @ 2400 | MSI GTX 970 gaming 4G | Ubuntu 15.10 Wily Werewolf / Windows 7

    http://ubuntutechnical.wordpress.com/

  10. #20
    Join Date
    Dec 2007
    Location
    Behind you!!
    Beans
    977
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: Beginner's Programming Challenge 18

    @roccivic

    Any idea when this will be judged?
    If you need any assistance from the beginners team, please send me a PM or drop into #ubuntu-beginners on irc and speak to any voiced user.

    Thanks,
    Bodsda
    computer-howto
    Linux is not windows
    Fluxbox & Flux menu how to
    Programming is an art. Learn it, Live it, Love it!


Page 2 of 4 FirstFirst 1234 LastLast

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •