PDA

View Full Version : Javascript help



hussainak
04-01-2007, 05:11 PM
Hello

I need some help with Javascript and i m stuck with this simple thing that i m unable to figure out.

i need some help with this....

Suppose i m having two words in an array

array = new Array();

array[0] = "abel";

array[1] = "able";

i need to check if all the letters in the array at position 0 and position 1 are the same... like at pos. 0 the letters in alphabetical order are "a", "b", "e", "l" adn if i can sort the word at pos. 1 in the same order and match it using an IF condition, i will achieve the result.

I want to get something like this

if(array[0] == array[1]){
alert("The word is an anagram");
}

any quick help with idea or code will be appreciated

Thanx

pcbrainbuster
04-01-2007, 05:42 PM
Well I barely am good at arrays but may be able to help you out, try this -

<script>
array = new Array()
array[0] = "abel"
array[1] = "able"
if (array[0].substring(0,0)==array[1].substring(0,0)) {
alert("The word is an anagram")}
</script>

Well it should work :)

hussainak
04-01-2007, 05:50 PM
thanx buddy :)

pcbrainbuster
04-01-2007, 05:55 PM
Anytime :)

jscheuer1
04-01-2007, 05:56 PM
That only seems to check the first letter but, it's a neat idea to use substring. This will work for the whole word:


<script type="text/javascript">
var words = [];
words[0] = "Abel";
words[1] = "able";
function pad_sort(w){
var t='';
for (var i_tem = 0; i_tem < w.length; i_tem++)
t+=w.charAt(i_tem).toLowerCase()+',';
return t.split(',').sort().join();
}
function isanagram(w1,w2){
if(pad_sort(w1)==pad_sort(w2))
alert('anagram');
}
isanagram(words[0],words[1]);
</script>

pcbrainbuster
04-01-2007, 06:02 PM
Or you could just do -

<script>
array = new Array()
array[0] = "abel"
array[1] = "able"
if (array[0]==array[1]) {
alert("The word is an anagram")}
</script>

An dif you want to include the else statement -

<script>
array = new Array()
array[0] = "abel"
array[1] = "able"
if (array[0]==array[1]) {
alert("The word is an anagram")}
else {
alert("The word is not an anagram")}
</script>

Though I am not sure what an anagram is....

jscheuer1
04-01-2007, 06:04 PM
Do you even know what an anagram is?

pcbrainbuster
04-01-2007, 06:06 PM
Lol you must of cross posted :)

jscheuer1
04-01-2007, 06:08 PM
That question was for both of the other two folks posting in this thread. Here's an answer to it:


Main Entry: 1an·a·gram
Pronunciation: 'a-n&-"gram
Function: noun
Etymology: probably from Middle French anagramme, from New Latin anagrammat-, anagramma, modification of Greek anagrammatismos, from anagrammatizein to transpose letters, from ana- + grammat-, gramma letter -- more at GRAM
1 : a word or phrase made by transposing the letters of another word or phrase
2 plural but singular in construction : a game in which words are formed by rearranging the letters of other words or by arranging letters taken (as from a stock of cards or blocks) at random

I think #1 is what we should be going for here.

pcbrainbuster
04-01-2007, 06:11 PM
I don't think I will be using that word :)

jscheuer1
04-01-2007, 06:36 PM
I don't think I will be using that word :)

Good thinking.

pcbrainbuster
04-01-2007, 06:55 PM
Whats that supposed to mean !!!

Twey
04-01-2007, 08:07 PM
String.prototype.isAnagram = function(s) {
return Array.prototype.slice.apply(this.toLowerCase()).sort().join("") === Array.prototype.slice.apply(s.toLowerCase()).sort().join("");
};

pcbrainbuster
04-01-2007, 08:13 PM
Wo, that is some complicated and sophisticated code !!! (how do you know how to do these things???)

Twey
04-01-2007, 08:24 PM
No it isn't, it's just stuffed into one statement. You can break it down if you want:
String.prototype.isAnagram = function(s) {
var thisAlph = this,
thatAlph = s,
anagram = false;

// Convert the strings to lowercase:
thisAlph = thisAlph.toLowerCase();
thatAlph = thatAlph.toLowerCase();
// Convert the strings to arrays of characters:
thisAlph = Array.prototype.slice.apply(thisAlph);
thatAlph = Array.prototype.slice.apply(thatAlph);
// Arrange them alphabetically (although any order would do):
thisAlph = thisAlph.sort();
thatAlph = thatAlph.sort();
// Join them back into strings so we compare value rather than identity:
thisAlph = thisAlph.join("");
thatAlph = thatAlph.join("");
// Compare them:
if(thisAlph === thatAlph)
anagram = true;

// Return.
return anagram;
};Actually, thinking about this, it would be easier to use String.prototype.split() rather than Array.prototype.slice():
String.prototype.isAnagram = function(s) {
return this.toLowerCase().split("").sort().join("") === s.toLowerCase().split("").sort().join("");
};The effect of splitting a string by an empty delimiter and applying Array.prototype.slice() is the same, but the former involves less code :)

You can then check if two strings are anagrams of one another:
"Lehol".isAnagram("Hello"); // true
"Fish".isAnagram("Bird"); // false

jscheuer1
04-01-2007, 08:29 PM
String.prototype.isAnagram = function(s) {
return Array.prototype.slice.apply(this.toLowerCase()).sort().join("") === Array.prototype.slice.apply(s.toLowerCase()).sort().join("");
};

That's nice but, if a space is introduced its output varies among browsers. My code may have done that too but, I had since amended it to this (with your code included beneath it to make sure I am using it right):


<script type="text/javascript">
var words = [];
words[0] = "A bel";
words[1] = "able";
function pad_sort(w){
var t=''
for (var i_tem = 0; i_tem < w.length; i_tem++)
t+=w.charAt(i_tem).toLowerCase()+' ';
return t.split(' ').sort().join('');
}
function isanagram(w1,w2){
if(pad_sort(w1)==pad_sort(w2))
alert('anagram');
}
isanagram(words[0],words[1])

String.prototype.isAnagram = function(s) {
return Array.prototype.slice.apply(this.toLowerCase()).sort().join("") === Array.prototype.slice.apply(s.toLowerCase()).sort().join("");
};
alert(words[0].isAnagram(words[1]))
</script>

Slice isn't supported in older browsers - a fine point. I'm uncertain but, seem to recall that the String prototype doesn't work as expected in older browsers either.

I'm also unclear about your use of what apparently is either a method or keyword - apply. I'll have to look into that.

Twey
04-01-2007, 08:37 PM
That's nice but, if a space is introduced its output varies among browsers.Really? It shouldn't, can you be more specific? I can understand that the space may be sorted into different positions depending on how the browser's JS engine thinks of it, but the key point is that it doesn't matter. The order doesn't even have to be alphabetical, the only criterion is that the two strings must be sorted in the same manner.
Slice isn't supported in older browsers - a fine point.Not one I made, I don't think... slice() has been supported for quite a while, certainly long enough that I no longer think of it as a consideration.
I'm uncertain but, seem to recall that the String prototype doesn't work as expected in older browsers either.I can't think of any examples, although perhaps Netscape 4 or something has issues. Anything that supports JS should be fine with it, though.
I'm also unclear about your use of what apparently is either a method or keyword - apply. I'll have to look into that.It's a method of changing the scope of a function.
myfunc.apply(x, [arg1, arg2]);is the same as calling
x.myfunc(arg1, arg2);if myfunc were a property of x. Applying Array.prototype.slice() is a nice way to convert things that can be accessed using array syntax (like collections or strings) into actual arrays.

One thing yours does that mine doesn't is ignore spaces. I hadn't thought of that, but you're right, many commonly seen anagrams do indeed include punctuation that should be ignored. Perhaps a replace():
String.prototype.isAnagram = function(s) {
return this.replace(/\W/g, "").toLowerCase().split("").sort().join("") === s.replace(/\W/g, "").toLowerCase().split("").sort().join("");
};

pcbrainbuster
04-01-2007, 08:43 PM
Well I can't relate to what you said because I do not know what the prototype thing is or any array stuff and have had once known slice but forgot it...

Is isAnagram really a method ???

(i guess i will have to lokk up alot...)

Twey
04-01-2007, 08:47 PM
Is isAnagram really a method ??? It is if you use the above code, I defined it :)
I do not know what the prototype thing isIt's OO stuff... you'll get to it in time, I should think.

pcbrainbuster
04-01-2007, 08:54 PM
By define do you in a sense mean you created it ?
If so then please explain how :)

mburt
04-01-2007, 09:06 PM
What Twey used is called a prototype function. Basically the syntax is as follows:

type of.prototype.functionname=function() {}

The type could be a Number, String or custom function attribute (new keyword required to create the object).

I recently made this phone number prototype:

Number.prototype.phone = function(sep) {
var s = this.toString(),
_1800num;
if (s.length == 10) _1800num=0; else if (s.length == 7) _1800num=0; else _1800num=1;
var num = _1800num == 0 ? 3 : 1,
offset = _1800num == 1 ? 0 : 1;
for (i = num;i < s.length-_1800num-1;i += 3+offset+_1800num) {
s = s.substring(0,i) + sep + s.substring(i);
}
return s;
}

That basically assigns the attribute "phone" as a function to any NUMBER:

var num = 17993922492;
alert(num.phone("-"));
Will return 1-799-392-2492

Notice that the variable "num" has the attribute phone(). Prototype assigns this.

pcbrainbuster
04-01-2007, 09:09 PM
I have decided I hate prototype... Maybe one day I will see its use....

Thanks :)

mburt
04-01-2007, 09:11 PM
It's very convenient actually. The script I gave (or Twey's, for that matter) is a perfect example of it.

jscheuer1
04-02-2007, 05:53 AM
That's nice but, if a space is introduced its output varies among browsers.

Really? It shouldn't, can you be more specific? I can understand that the space may be sorted into different positions depending on how the browser's JS engine thinks of it, but the key point is that it doesn't matter. The order doesn't even have to be alphabetical, the only criterion is that the two strings must be sorted in the same manner.

Like you really had to ask. But, just to be clear, I was talking specifically about the example in my last post in this thread and the browser was IE. I see you've updated your code at least twice since. I haven't played with those versions. So, I cannot say much about them now. At the moment I am also puzzled by IE's behavior. It was reporting true while Opera and FF were saying false.