logo
down
shadow

Caesar cipher only gets first value right


Caesar cipher only gets first value right

Content Index :

Caesar cipher only gets first value right
Tag : javascript , By : Jason Haar
Date : November 27 2020, 04:01 AM

should help you out When you use charCode, you get the unicode values of the characters, which are in the range 65–90 for the uppercase english alphabet. When you add 13, you get the unicode values for the characters "NOPQRSTUVWXYZ[]^_`abcdefg", which is not what you want.
You need to find a way to only make english characters map to the the english character 13 steps away, and make this wrap around so that the later characters map to the earlier ones (so that Z maps to M).
function rot13(str) {
  let x = str.toUpperCase();
  let y = [];
  let n = "";
  let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  for (let i = 0; i < x.length; i++) {
    if (alphabet.indexOf(x.charAt(i)) > -1) {
      n += alphabet.charAt((alphabet.indexOf(x.charAt(i)) + 13) % 26);
    } else {
      n += x.charAt(i);
    }
  }
  return n;
}

console.log(rot13("FREE PIZZA"));
function rot13(str) {
  let x = str.toUpperCase().split("");
  let table = {
    A: "N", B: "O", C: "P", D: "Q",
    E: "R", F: "S", G: "T", H: "U",
    I: "V", J: "W", K: "X", L: "Y",
    M: "Z", N: "A", O: "B", P: "C",
    Q: "D", R: "E", S: "F", T: "G",
    U: "H", V: "I", W: "J", X: "K",
    Y: "L", Z: "M"
  };
  for (let i = 0; i < x.length; i++) {
    if (table[x[i]]) {
      x[i] = table[x[i]];
    }
  }
  return x.join("");
}

console.log(rot13("FREE PIZZA"));

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Caesar Cipher in javascript: cipher broken


Tag : javascript , By : Mariocki
Date : March 29 2020, 07:55 AM
it should still fix some issue The undefined is a result of not initializing c_text before you try concatenate it with _x.
The code only works on one letter because alphabet.indexOf(x) returns -1 (not found). When using o_text = "abc", x equals 0, 1, and 2. Thus, the index of 0, 1, or 2 in alphabet is nonexistent (indicated by the -1 result). You need to relate those numbers back to o_text by changing indexOf(x) to indexOf(o_text[x]). Also, to prevent going outside the bounds of your array, you need a modulus operation to wrap values greater than 26 (I've used alphabet.length to allow this code to work with other alphabets) back around into a valid region. Thus, the correct code would be as follows (note: I've moved 'w' in your array into its proper location alphabetically, as I assumed its location in your example was an error and not intentional):
var currentkey = 5  //for example
function convertKey(str) {
    var o_text = str;
    var o_letters = o_text.split("");
    var 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']
    var c_text="", _x = "";
    for (x in o_letters) {
        if (currentkey > 0) {
            _x = alphabet[(alphabet.indexOf(o_letters[x]) + currentkey) % alphabet.length]
        } else {
            _x = alphabet[(alphabet.indexOf(o_letters[x]) + (26 - currentkey)) % alphabet.length]
        }
        c_text = c_text + _x;
    }
    return c_text;
}

alert(convertKey('abcdefghijklmnopqrstuvwxyz'));

PHP Caesar cipher


Tag : php , By : arcadian
Date : March 29 2020, 07:55 AM
I wish this helpful for you (jsfiddle example here: caesar cipher) , First,change
$string = "hello";
$string = $_POST['msg'];
$newstring = "hello";
$newstring = $string;
$sp = $_POST['sp']
$ascii++;
for ($i=0;$i<strlen($string);$i++) {...}
for ($i=0;$i<strlen($string);$i++) {

  $ascii = ord($string[$i]);
  for($j=0;$j<$sp;$j++){
    if($ascii == 90) { //uppercase bound
      $ascii = 65; //reset back to 'A' 
    } 
    else if($ascii == 122) { //lowercase bound
      $ascii = 97; //reset back to 'a' 
    } 
    else {
      $ascii++;
    }
  }
  $newstring[$i] = chr($ascii);

}

Break a Caesar-cipher cipher text without knowing the plaintext or the key through frequency-analysis


Tag : chash , By : user158220
Date : March 29 2020, 07:55 AM
it helps some times A Caesar cipher just replaces each plain text character with one a fixed number of places away down the alphabet. Assuming no casing, and English text, then it is trivial to produce all possible 26 decryptions and just pick out the correct one by eye.
For a substitution cipher you need to generalise your solution. A simplified method is to do a frequency count as you've suggested, and sort characters in descending order of frequency. Map those to the letters (again for English) ETAOINSRHOLUCMFYWGPBVKXQJZ (so for example assume the most frequent character represents an E, the next most frequent a T and so on). Use the mapping to do the decryption. The more cipher text you have the better the decryption will be. It is unlikely to be completely accurate but will give you enough information to fill in the gaps manually.

I am creating a caesar cipher in Ruby but the caesar function never finishes


Tag : ruby , By : walkah
Date : March 29 2020, 07:55 AM
Does that help You need a different variable for storing the result string. How about this:
  def caesar(string, shift_factor)
      alphabet = Array("a".."z")
      new_alph = alphabet.rotate(shift_factor)
      new_str = string.downcase.split("")
      caesar_string = []
      new_str.each do |i|
        if !alphabet.include?(i)
          caesar_string.push(i)
        else
          equals = alphabet.index(i)
          caesar_string.push(new_alph[equals])
        end
      end
      caesar_string
  end

  caesar_string = caesar("What a string!", 0)

  print caesar_string.join.capitalize!

Is there another way to check whether it's an integer in Caesar Cipher other than a for loop? CS50 pset2 Caesar Cipher


Tag : c , By : WellBeing
Date : March 29 2020, 07:55 AM
I wish this help you Because return exits the function, there’s no need to use an else after an if branch containing a return – if the if path is taken, nothing after the if keeps running.
int main(int argc, string argv[])
{
    if (argc != 2)
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }

    for (int i = 0; i < strlen(argv[1]); i++)
    {
        if (!isdigit(argv[1][i]))
        {
            printf("Usage: ./caesar key\n");
            return 1;
        }

        printf("Sucess\n");
        printf("%s\n", argv[1]);
    }
}
int main(int argc, string argv[])
{
    if (argc != 2)
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }

    for (int i = 0; i < strlen(argv[1]); i++)
    {
        if (!isdigit(argv[1][i]))
        {
            printf("Usage: ./caesar key\n");
            return 1;
        }
    }

    printf("Success\n");
    printf("%s\n", argv[1]);
}
Related Posts Related QUESTIONS :
  • Does using try / catch rather than `.catch` observable operator with XHR requests reduce performance?
  • In IE11 background colors not working on printing
  • TypeScript interface signature "(): string"
  • Is synchronous XMLHttpRequest supported in Internet Explorer 10 and 11?
  • Axios function not returning any values with js
  • How to use firestore TIMESTAMP to create time-stamp in JavaScript
  • Instantiate subclass without constructing
  • Outputing a created object in javascript to a server side JSON file
  • Transition the numeric labels in a bar chart
  • createBottomTabNavigator: hide just one tab from the tabBar
  • iife vs simple statement behavior with document.title
  • showDialogPopup Refresh Page after Click
  • Child component does not set the initial value passed from the parent: ReactJS
  • Nodejs javascript added to button not responding
  • Trying to define a promise.all
  • Python GEE to extract featurecollection timeseries from Landsat imageries
  • How to write negative binary number?
  • Unable to set property of individual object
  • Why Named Function Expression itself cannot assign Name to another Value?
  • How to reset scroll position on single page pagination
  • How to scroll to bottom of page, when a new message is sent - Socket.io
  • How to reconstruct audio blob from a base64 encoded String?
  • How to calculate numbers within an array of objects
  • Using JavaScript to change CSS properties of SVG circles for all circles that was not clicked
  • Is there value in propTypeing repeat required properties at every level of nested components?
  • Call function if variable does not exist in a filter
  • localStorage value doesn't get updated automatically
  • React not updating state with setState correctly inside promises
  • Direct native JavaScript or jQuery method to get containing block of an element
  • Dynamic JSON object to Html Table
  • How to send Id and file to same controller?
  • How to Make a jQuery Table Cell(td) clickable to Run a Function?
  • Prevent the duplicate function onchange event jQuery
  • Reactjs Input Upload doesn't return local URL
  • An unexpected 'StartObject' node was found when reading from the JSON reader. A 'PrimitiveValue' node was expected
  • How to filter a JSON Array, with an eventListener input value at keyup
  • How to separate the different properties of filter in css?
  • Why dont work change event of bootstrap input spinner?
  • How to hide overflow text content in react
  • Is there another way to write line 6
  • Cypress - how to find by text content?
  • How to setstate for the dynamic checkboxes in a loop in react?
  • Is display:none safe?
  • How to create a form to change part of a href url of a button?
  • Put many function inside function in Javascript
  • how to exit from loop after a ajax call
  • Do Angular Reactive Form Validator.min/max check Perform Type Conversions before checking the value?
  • How to Replace Text Within Script Tags Using JQuery
  • add variable to object if not undefined using short-hand
  • How can I effectively curve my items inside a list?
  • Add new record Keyboard Shortcut on Kendo Grid Mvc
  • Time and Date running on page
  • Looping through page links puppeteer doesn't return values from the newly loaded page
  • Problem with Navigator.geoLocation.getCurrentPosition not working
  • Trying to change the id of an element with Javascript
  • Embedded Schema Inserting Blank in Meteor using Collection2
  • avoid useEffect to render at first load?
  • Why is this CSS transition only working correctly on the some clicks? How to solve it?
  • Interpolated values does not reflect the latest values in an Angular app
  • Javascript classes define attribute in constructor or outside the class
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com