Skip to content

Instantly share code, notes, and snippets.

@yarwelp
Created November 29, 2011 07:17
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yarwelp/1403833 to your computer and use it in GitHub Desktop.
Save yarwelp/1403833 to your computer and use it in GitHub Desktop.
Truth table (JavaScript)
/* js-truth_table
*
* file: truth_table.js
*
* Copyright (c) 2011, Erik Nordstroem <contact@erikano.net>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
var row = [], values = ["a", "b", "c"]
for (var i = (Math.pow(2, values.length) - 1) ; i >= 0 ; i--) {
for (var j = (values.length - 1) ; j >= 0 ; j--) {
row[j] = (i & Math.pow(2,j)) ? true : false
}
print(row)
}
@yarwelp
Copy link
Author

yarwelp commented Nov 29, 2011

Output:

true,true,true
false,true,true
true,false,true
false,false,true
true,true,false
false,true,false
true,false,false
false,false,false

@yarwelp
Copy link
Author

yarwelp commented Nov 29, 2011

Obviously, you'll want to pass each row to a function (probably along with the original values) and do something more useful than just printing it.

@noorfathima11
Copy link

You have to keep in check if Math.pow(2, n) doesn't exceed the maximum safe integer value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment