CTCI Ch.1.2 Check Permutation - javascript

Greetings and happy holidays,
My question involves problem "1.2 Check Permutation" from "Cracking The Coding Interview" 6th Ed.
When we compare the two strings, we check for any values in the array that are less than 0. This would indicate different char counts of our two strings. However, shouldn't the comparison be !== 0 instead of < 0? This would catch both over and undercounts of the chars. I didn't see this in the books Errata nor on any related search results.
Below is the provided code solution. (I mainly work in JS, so perhaps I'm reading the code incorrectly)
Many thanks in advance.
boolean permutation(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] letters = new int[128];
char[] s_array = s.toCharArray();
for (char c : s_array) {
letters[c]++;
}
for (int i = 0; i < t.length(); i++) {
int c = (int) t.charAt(i);
letters[c]--;
if (letters[c] < 0) { // this is the line in question
return false;
}
}
return true;
}

The comparison for != 0 only makes sense after all the differences are computed. The way the code is structured allows an early detection.
The very first test is for s.length() != t.length(). Once the code passed it, we know that there are equal number of characters. It means that - if the strings are not permutations - there is a character which appears more in t than in s. As soon as such character is found, we conclude that t is not a permutation.

Related

How does javascript do the comparison?

I have an object array that gets new values every time a new user is created. I need to do some search based on the person name and then do some operations with it and I implemented a binary search and in my code that I found in the internet but theres something thats bothering me with the search code.
The object looks as follows:
person = {
name: name,
password: password,
cartItems: '',
cartPrice: 0
}
then I push it to an array.
and the binary search code looks as follows:
searchValues(users, value) {
var startIndex = 0,
stopIndex = users.length,
middle = Math.floor((stopIndex + startIndex) / 2);
while(users[middle].name != value && startIndex < stopIndex){
//adjust search area
if (value < users[middle].name) {
stopIndex = middle - 1;
} else if (value > users[middle].name) {
startIndex = middle + 1;
}
//recalculate middle
middle = Math.floor((stopIndex + startIndex) / 2);
}
return (users[middle].name != value) ? -1 : middle;
}
My questions is: How does JavaScript do the comparison between string values, does it convert to ascii? I can understand the code if it was applied to numbers but I'm a bit confused when it comes to strings.
Thank you in advance for anyone willing to help
EDIT: I forgot to mention that i've sorted my array before hand.
The algorithm to compare two strings is simple:
Compare the first character of both strings.
If the first character from the first string is greater (or less) than the other string’s, then the first string is greater (or less) than the second. We’re done.
Otherwise, if both strings’ first characters are the same, compare the second characters the same way.
Repeat until the end of either string.
If both strings end at the same length, then they are equal. Otherwise, the longer string is greater.
reference find more detail here

As per my pattern, the output is not a meaningful word. Can anyone identify a different pattern to output a meaningful word

As per my pattern, the output is not a meaningful word. Can anyone identify a different pattern to output a meaningful word.
Consider the following pattern:
A → D; M → P; X → A;
a → d; m → p; x → a;
Solve the following message
Vrphwklqj phdqlqjixo
Hint: The answer is something meaningful.
I am considering that there should be a difference of two alphabets; which outputs: Yuskznotm.....(not meaningful at all).
Can anyone see a different pattern and help me out.
The question is wrong
The pattern should be D->A,P->M,X->U
That is Caesar cipher using -3 or +23 (NOT +3)
READ THE QUESTION PROPERLY
USE THIS TO CHECK
import java.io.*;
class CaesarCipher
{
public static void main(String s)throws IOException
{
for(int i=1;i<27;i++)
{
int l=s.length();
for(int j=0;j<l;j++)
if(Character.isLetter(s.charAt(j)))
{
if(((s.charAt(j))+i)>122)
System.out.print((char)((s.charAt(j))+i-26));
else
System.out.print((char)((s.charAt(j))+i));
}
else
System.out.print((char)s.charAt(j));
System.out.println();
}
}
}
ONLY LOWERCASE LETTERS
It adds a new shift every time to create a new string
1,2,3,......,26
You can see the answer for your question when adding 23 or by also subtracting 3 which should be the real question which you mistook
IT WILL DISPLAY ALL POSSIBLE CAESAR DECRYPTIONS LOOK WHAT'S MEANINGFUL
Thanks Paulsam. You got it right. There was a discrepancy in the assignment question. I figured it and wrote a javascript for it.
<!doctype html>
<html>
<head>
<title>Ceaser-Cipher-Convertion</title>
</head>
<body>
<script>
//This function takes the input and defines the logic for conversion
function convert()
{
//The input to be converted to the message is provided here
var input = "Vrphwklqj phdqlqjixo";
/* The convertion logic is based on Ceaser-Cipher method. We retrieve the ASCII values of the characters one be one from the string.
As per formulae; m = c + d mod 26. However we are using ASCII values, we have to replace mod 26 by - 26.
The decryption key from the pattern is 23. Hence m = c + 23-26 => m = c - 23. However for the ASCII values; a-c; the formulae returns
non-alphabetic ASCII values. As an exception to these three alphabets; m = c + 23;
The ASCII value thus attained are to be converted back to characters */
for(var i=0; i<input.length; i++)
{
var asc_code = input.charCodeAt(i);
var conv_code;
//Conversion of alphabets (a-c)
if((asc_code >= 65 && asc_code <= 67) || (asc_code >= 97 && asc_code <= 99))
{
conv_code = asc_code+23;
}
//Conversion of rest of the alphabets
else if((asc_code >= 68 && asc_code <= 90) || (asc_code >= 100 && asc_code <= 122))
{
conv_code = asc_code-3;
}
//Conversion of non alphabetic characters
else conv_code = asc_code;
//Output the message
var message = String.fromCharCode(conv_code);
document.write(message);
}
}
convert();
</script>
</body>
</html>

counting a word and returning a whether it is symmetric or not in Javascript

My whole goal was to write a loop that would take a string, count the letters and return two responses: one = "this word is symmetric" or two = "this word is not symmetric". However the code I wrote doesn't console anything out. Here's the code:
var arya = function(arraycount){
for (arraycount.length >= 1; arraycount.length <= 100; arraycount++) {
while (arraycount.length%2 === 0) {
console.log("This is a symmetric word and its length is " + " " arraycount.length " units.");
arraycount.length%2 != 0
console.log("Not a symmetric word");
}
}
}
arya("Michael");
There are many ways to accomplish your goal, but here are a few. The first is a somewhat naïve approach using a for loop, and the second uses recursion. The third asks whether the string equals the reverse of the string.
iterative (for loop) function
var isPalindromeIteratively = function(string) {
if (string.length <= 1) {
return true;
}
for (var i = 0; i <= Math.floor(string.length / 2); i++) {
if (string[i] !== string[string.length - 1 - i]) {
return false;
}
}
return true;
};
This function begins by asking whether your input string is a single character or empty string, in which case the string would be a trivial palindrome. Then, the for loop is set up: starting from 0 (the first character of the string) and going to the middle character, the loop asks whether a given character is identical to its partner on the other end of the string. If the parter character is not identical, the function returns false. If the for loop finishes, that means every character has an identical partner, so the function returns true.
recursive function
var isPalindromeRecursively = function(string) {
if (string.length <= 1) {
console.log('<= 1');
return true;
}
var firstChar = string[0];
var lastChar = string[string.length - 1];
var substring = string.substring(1, string.length - 1);
console.log('first character: ' + firstChar);
console.log('last character: ' + lastChar);
console.log('substring: ' + substring);
return (firstChar === lastChar) ? isPalindromeRecursively(substring) : false;
};
This function begins the same way as the first, by getting the trivial case out of the way. Then, it tests whether the first character of the string is equal to the last character. Using the ternary operator, the function, returns false if that test fails. If the test is true, the function calls itself again on a substring, and everything starts all over again. This substring is the original string without the first and last characters.
'reflecting' the string
var reflectivePalindrome = function(string) {
return string === string.split('').reverse().join('');
};
This one just reverses the string and sees if it equals the input string. It relies on the reverse() method of Array, and although it's the most expressive and compact way of doing it, it's probably not the most efficient.
usage
These will return true or false, telling you whether string is a palindrome. I assumed that is what you mean when you say "symmetric." I included some debugging statements so you can trace this recursive function as it works.
The Mozilla Developer Network offers a comprehensive guide of the JavaScript language. Also, here are links to the way for loops and while loops work in JS.

Writing function to Match words off by 1 character JavaScript

I am attempting to write a JavaScript function, OneLetterOff, that will take in a String, and an Array of accepted words (WordList).
It should return an array of words from the WordList that only differ from the word given in the String by only one letter, at a single position.
For example:
WordList = ["marc", "bark", "parc", "shark", "mark"];
OneLetterOff("park", WordList); // should return ["bark", "parc", "mark"]
Words that pass the test have to be of the same length, and we can safely assume they are all lower case letters.
How do I use Regular Expressions to solve this algorithm? Essentially, are there ways other than having to use Regular Expressions to solve it?
Thank you so much for your help.
Regular expressions are not the best for it but to give you an idea:
"mark".match(/.ark|p.rk|pa.k|par./) //true
You can, of course, build regular expressions automatically and just "." might not be what you are looking for, depending on the possible characters you need to include.
I suggest you figure out the rest on your own as it looks a lot like homework ;-)
There are many non-regexp ways to solve it. For short words pre-compiled regexp will probably be the most efficient though.
You are looking for words in a list with a Levenshtein distance of 1 from a given word.
As found at Algorithm Implementation/Strings/Levenshtein distance, a JavaScript implementation of the algorithm is as follows:
function levenshteinDistance (s, t) {
if (s.length === 0) return t.length;
if (t.length === 0) return s.length;
return Math.min(
levenshteinDistance(s.substr(1), t) + 1,
levenshteinDistance(t.substr(1), s) + 1,
levenshteinDistance(s.substr(1), t.substr(1)) + (s[0] !== t[0] ? 1 : 0)
);
};
Using that method with Array.prototype.filter (polyfill needed for IE<9) to include only items with a distance of 1, we get a very simple bit of code:
var oneLetterOff = function (word, list) {
return list.filter(function (element) {
return levenshteinDistance(word, element) === 1;
});
};
oneLetterOff('park', ['marc', 'bark', 'parc', 'shark', 'mark']);
// returns ["bark", "parc", "mark"]
One great feature to this approach is that it works for any distance--just change what you're comparing to in the filter.
If you really wanted to use regular expressions (which I would not recommend for this), you would need to:
Iterate the given word to create a set of strings representing regular expression subpatterns where each has one char optional
Combine those string subpatterns into a regular expression using new RegExp()
Iterate the list of words testing them against the expresison
When you get a match, add it to a set of matches
Return the set of matches
It wouldn't take long to write, but given the answer I gave above I think you'll agree it would be a silly approach.
Here is my solution inspired by JAAuide and using all the power of JavaScript functions
function lDist (s, t) {
/* If called with a numeric `this` value
returns true if Levenshtein distance between strings s and t <= this
else
returns the Levenshtein distance between strings s and t */
return this.constructor === Number ? lDist.call (null, s, t) <= this :
s.length && t.length
? Math.min (lDist (s.slice (1), t) + 1,
lDist (t.slice (1), s) + 1,
lDist (s.slice (1), t.slice (1)) + (s.charAt (0) !== t.charAt (0)))
: (s.length || t.length) };
['marc', 'bark', 'parc', 'shark', 'mark'].filter (lDist.bind (1, 'park'));
See the jsFiddle

Convert simple javascript program into C

Hello I have some experience with javascript but I would really like to learn how to program in C and one of the ways I am trying to learn is by converting some simple javascript code into C. My current attempt at converting a simple program compiles without any errors however doesn`t produce the answer I want it to. The javscript code produces the correct answer and I wrote it to solve project euler problem number 5 which can be found here: https://projecteuler.net/problem=5
Here is the working js code:
var number = 2520;
var count = 1;
var solved = false;
while (!solved) {
if (number % count === 0) {
if (count === 20) {
solved = true;
console.log(number);
} else {
count++;
}
} else {
number++;
count = 1;
}
}
Here is the C conversion which does not work:
#include <stdio.h>
int main () {
unsigned int number = 2520;
unsigned int count = 1;
unsigned int solved = 0;
while ((solved = 0)) {
if (number % count == 0) {
if (count == 20) {
solved = 1;
printf("%number");
} else {
count++;
}
} else {
number++;
count = 1;
}
}
return 0;
}
while ((solved = 0)) {
You can use the same syntax you would use in js here, namely, while (!solved), or ==, but just = is an assignment.
printf("%number");
Doesn't mean what you think it means, which is why it's not an actual error (%n is a distinct specifier, and with no corresponding input, you'd get umber as the output). To reproduce console.log() you'd want:
printf("%d\n", (int)number);
Or
printf("%u\n", number);
Notice the explicit \n, since printf() does not add a newline otherwise.
Replace
while (solved = 0)
with
while (!solved)
and
print("%number")
with
print("%u\n",number)
I know its already answered, but you should know why.
while ((solved = 0))
Will actually set solved to 0 AND return 0 (which is interpreted as false). So the while loop is exited right away.
printf also takes a pretty strictly formatted string for the first one (just typeing what makes sense is guarenteed to be wrong). The compiler has know way to know what is inside the string is anything other than a string (C++ has (almost) NO reflection, unlike javascript: your written code dissapears into ones and zeros). printf needs to take number in as the second argument. Try printf("%i\n",number);. That says "Print an integer followed by a newline. The integer's value is number."
Welcome to C! Your biggest problem going into is is going to be my biggest problem with Java Script: C is strictly typed with no reflection, while javascript has no types with almost everything relying on some sort of reflection.

Categories

Resources