neo4j traversal example it didn't give the right node number - neo4j

0i want to traversal using neo4j.
while it give me the output from newno1 like
(4354)
(4354)--[KNOWS,8335]-->(4358)
(4354)--[KNOWS,8335]-->(4358)--[KNOWS,8332]-->(4357)
(4354)--[KNOWS,8334]-->(4356)
why it didn't give me right node number from 0-4? and depth is from 1-3
thanks.
i just want to traversal in this graph like level by level and output the backward and forward separately.
The expected output should be like:
(1)
(1)--[KNOWS,0]-->(2)
(1)--[KNOWS,0]-->(2)--[KNOWS,2]-->(2)
(1)--[KNOWS,0]-->(4)
the number after KNOWS should also like smaller number. like neo4j example
the java code is :
public class TraversalExample
{
private GraphDatabaseService db;
private TraversalDescription friendsTraversal;
public TraversalExample( GraphDatabaseService db )
{
this.db = db;
// START SNIPPET: basetraverser
friendsTraversal = db.traversalDescription()
.depthFirst()
.relationships( Rels.KNOWS )
.uniqueness( Uniqueness.RELATIONSHIP_GLOBAL );
// END SNIPPET: basetraverser
}
public static void main( String[] args )
{
final String DB_PATH = "target/neo4j-hello-db";
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
TraversalExample op = new TraversalExample( db );
op.createTheGraph();
op.shutdownGraph();
}
public void shutdownGraph()
{
try
{
if ( db != null )
{
db.shutdown();
}
}
finally
{
db = null;
}
}
public Node createTheGraph()
{
try ( Transaction tx = db.beginTx() )
{
// START SNIPPET: createGraph
Node[] newno=new Node[5];
for(int i=0; i<newno.length; i++){
newno[i]=db.createNode();
}
newno[1].createRelationshipTo(newno[2], Rels.KNOWS );
newno[1].createRelationshipTo(newno[4], Rels.KNOWS );
newno[4].createRelationshipTo(newno[2], Rels.KNOWS );
newno[2].createRelationshipTo(newno[3], Rels.KNOWS );
System.out.println(knowsTraverserforward(newno[1]));
return newno[1];
}
}
public String knowsLikesTraverser( Node node )
{
String output = "";
// START SNIPPET: knowslikestraverser
for ( Path position : db.traversalDescription()
.depthFirst()
.relationships( Rels.KNOWS )
.relationships( Rels.LIKES, Direction.INCOMING )
.evaluator( Evaluators.toDepth( 5 ) )
.traverse( node ) )
{
output += position + "\n";
}
// END SNIPPET: knowslikestraverser
return output;
}
public String knowsTraverserforward( Node node )
{
String output = "";
// START SNIPPET: knowslikestraverser
for ( Path position : db.traversalDescription()
.depthFirst()
.relationships( Rels.KNOWS, Direction.OUTGOING )
.evaluator( Evaluators.toDepth(5 ) )
.traverse( node ) )
{
output += position + "\n";
}
// END SNIPPET: knowslikestraverser
return output;
}
public String traverseBaseTraverser( Node node )
{
String output = "";
// START SNIPPET: traversebasetraverser
for ( Path path : friendsTraversal.traverse( node ) )
{
output += path + "\n";
}
// END SNIPPET: traversebasetraverser
return output;
}
public String depth3( Node node )
{
String output = "";
// START SNIPPET: depth3
for ( Path path : friendsTraversal
.evaluator( Evaluators.toDepth( 3 ) )
.traverse( node ) )
{
output += path + "\n";
}
// END SNIPPET: depth3
return output;
}
public String depth4( Node node )
{
String output = "";
// START SNIPPET: depth4
for ( Path path : friendsTraversal
.evaluator( Evaluators.fromDepth( 2 ) )
.evaluator( Evaluators.toDepth( 4 ) )
.traverse( node ) )
{
output += path + "\n";
}
// END SNIPPET: depth4
return output;
}
public String nodes( Node node )
{
String output = "";
// START SNIPPET: nodes
for ( Node currentNode : friendsTraversal
.traverse( node )
.nodes() )
{
output += currentNode.getProperty( "name" ) + "\n";
}
// END SNIPPET: nodes
return output;
}
public String relationships( Node node )
{
String output = "";
// START SNIPPET: relationships
for ( Relationship relationship : friendsTraversal
.traverse( node )
.relationships() )
{
output += relationship.getType().name() + "\n";
}
// END SNIPPET: relationships
return output;
}
// START SNIPPET: sourceRels
private enum Rels implements RelationshipType
{
LIKES, KNOWS
}
// END SNIPPET: sourceRels
}

The internal node id of any node is a implementation detail. You should not take any assumptions on the node id.
I guess if you print the node id of the nodes being created they would pretty much with your traversal:
for(int i=0; i<newno.length; i++){
newno[i]=db.createNode();
System.out.println(newno[i].getId());
}

Related

Why does assignment not work the same in Dart as it does in Python?

When I run this code:
void readCard(db, [int card_id = -1]) {
if (card_id == -1) {
final ResultSet result = db.select('SELECT * FROM cards');
}
else {
final ResultSet result = db.select("""
SELECT * FROM cards
WHERE card_id=(?)
"""); // this doesn't work yet
}
for (final Row card in result) {
print(
"Card {'card_id': ${card['card_id']}, "
"'due': ${card['due']}, "
"'content': ${card['content']}}"
);
}
}
I get this error:
memotext.dart:66:25: Error: Getter not found: 'result'.
for (final Row card in result) {
^^^^^^
Because result is assigned regardless of whether the if statement or the the else statement runs shouldn't there be no error? Is this something to do with the way dart does assignment?
The result is declared in their respective blocks, it doesn't exist outside. Do this:
void readCard(db, [int card_id = -1]) {
ResultSet result;
if (card_id == -1) {
result = db.select('SELECT * FROM cards');
}
else {
result = db.select("""
SELECT * FROM cards
WHERE card_id=(?)
"""); // this doesn't work yet
}
for (final Row card in result) {
print(
"Card {'card_id': ${card['card_id']}, "
"'due': ${card['due']}, "
"'content': ${card['content']}}"
);
}
}

How to get first character from words in flutter dart?

Let's say we have a name set to "Ben Bright". I want to output to the user "BB", with the first characters of each word. I tried with the split() method, but I failed to do it with dart.
String getInitials(bank_account_name) {
List<String> names = bank_account_name.split(" ");
String initials;
for (var i = 0; i < names.length; i++) {
initials = '${names[i]}';
}
return initials;
}
Allow me to give a shorter solution than the other mentioned:
void main() {
print(getInitials('')); //
print(getInitials('Ben')); // B
print(getInitials('Ben ')); // B
print(getInitials('Ben Bright')); // BB
print(getInitials('Ben Bright Big')); // BB
}
String getInitials(String bank_account_name) => bank_account_name.isNotEmpty
? bank_account_name.trim().split(' ').map((l) => l[0]).take(2).join()
: '';
The take(2) part ensures we only take up to two letters.
EDIT (7th October 2021):
Or if we must be able to handle multiple spaces between the words we can do (thanks #StackUnderflow for notice):
void main() {
print(getInitials('')); //
print(getInitials('Ben')); // B
print(getInitials('Ben ')); // B
print(getInitials('Ben Bright')); // BB
print(getInitials('Ben Bright Big')); // BB
print(getInitials('Ben Bright Big')); // BB
}
String getInitials(String bankAccountName) => bankAccountName.isNotEmpty
? bankAccountName.trim().split(RegExp(' +')).map((s) => s[0]).take(2).join()
: '';
Notice that split takes a RegExp(' +') compared to the original solution.
Just a slight modification since you only need the first letters
String getInitials(bank_account_name) {
List<String> names = bank_account_name.split(" ");
String initials = "";
int numWords = 2;
if(numWords < names.length) {
numWords = names.length;
}
for(var i = 0; i < numWords; i++){
initials += '${names[i][0]}';
}
return initials;
}
Edit:
You can set the value of num_words to print the intials of those many words.
If the bank_account_name is a 0 letter word, then return an empty string
If the bank_account_name contains lesser words than num_words, print the initials of all the words in bank_account_name.
var string = 'William Henry Gates';
var output = getInitials(string: string, limitTo: 1); // W
var output = getInitials(string: string, limitTo: 2); // WH
var output = getInitials(string: string); // WHG
String getInitials({String string, int limitTo}) {
var buffer = StringBuffer();
var split = string.split(' ');
for (var i = 0 ; i < (limitTo ?? split.length); i ++) {
buffer.write(split[i][0]);
}
return buffer.toString();
}
A more general solution can be found below. It takes care of empty strings, single word strings and situations where anticipated word count is less than actual word count:
static String getInitials(String string, {int limitTo}) {
var buffer = StringBuffer();
var wordList = string.trim().split(' ');
if (string.isEmpty)
return string;
// Take first character if string is a single word
if (wordList.length <= 1)
return string.characters.first;
/// Fallback to actual word count if
/// expected word count is greater
if (limitTo != null && limitTo > wordList.length) {
for (var i = 0; i < wordList.length; i++) {
buffer.write(wordList[i][0]);
}
return buffer.toString();
}
// Handle all other cases
for (var i = 0; i < (limitTo ?? wordList.length); i++) {
buffer.write(wordList[i][0]);
}
return buffer.toString();
}
Edit:
I actually use this for CircleAvatars with no images in my projects.
I used CopsOnRoad solution but I was getting the following error.
RangeError (index): Invalid value: Only valid value is 0: 1
So I modified it to
String getInitials(String string, [int limitTo = 2]) {
if (string == null || string.isEmpty) {
return '';
}
var buffer = StringBuffer();
var split = string.split(' ');
//For one word
if (split.length == 1) {
return string.substring(0, 1);
}
for (var i = 0; i < (limitTo ?? split.length); i++) {
buffer.write(split[i][0]);
}
return buffer.toString();
}
Here are some tests in case you are interested
void main() {
group('getInitials', () {
test('should process one later word name correctly', () {
final result = getInitials('J');
expect(result, 'J');
});
test('should process one word name correctly', () {
final result = getInitials('John');
expect(result, 'J');
});
test('should process two word name correctly', () {
final result = getInitials('John Mamba');
expect(result, 'JM');
});
test('should process more than two word name correctly', () {
final result = getInitials('John Mamba Kanzu');
expect(result, 'JM');
});
test('should return empty string when name is null', () {
final result = getInitials(null);
expect(result, '');
});
test('should return empty string when name is empty', () {
final result = getInitials('');
expect(result, '');
});
});
}
String getInitials(full_name) {
List<String> names = full_name.split(" ");
print("org::: $full_name");
print("list ::: $names");
print("Substring ::: ${names[0].substring(0,1)}");
String initials = "";
int numWords = 2;
numWords = names.length;
for(var i = 0; i < numWords; i++)
{
initials += '${names[i].substring(0,1)}';
print("the initials are $initials");
}
return initials;
}
On Nov, 2022
Working solution using Regex:
String getInitials(String string) => string.isNotEmpty
? string.trim().split(RegExp(' +')).map((s) => s[0]).join()
: '' ;

Linked list: stored elements are not displaying completely

I am trying to store 5 elements in linked, the input code is working fine but the display code is not showing the 5th element "RollNumber".
I can't find where I did the mistake.
class Node
{
friend class LinkedList;
private:
string BookName;
string BookNo;
string Price;
string StudentName;
string RollNumber;
Node *next;
public:
Node(string bname = "", string bno = "", string pr = "", string sname = "", string rn = "", Node *nxt = NULL)
{
BookName=bname;
BookNo=bno;
Price=pr;
StudentName=sname;
RollNumber:rn;
next=nxt;
}
};
class LinkedList
{
private:
Node *head;
Node *tail;
int count;
public:
LinkedList()
{
head = NULL;
tail = NULL;
count = 0;
}
bool isEmpty()
{
if (head == NULL)
{
return true;
}
return false;
}
void add_input_head(string bname = "", string bno="", string pr="", string sname="", string rn="")
{
if (isEmpty())
{
head = new Node(bname, bno, pr, sname, rn, NULL);
tail = head;
count++;
}
else
{
Node *p = new Node(bname, bno, pr, sname, rn, head);
head = p;
count++;
}
}
void traverse()
{
Node *t = head;
for (int i = 1; i <= count; i++) {
cout <<endl<<endl<<endl<<endl<<"Book Name: "<< t->BookName << endl;
cout <<endl<<endl<<"Book No: "<< t->BookNo << endl;
cout <<endl<<endl<<"Price: "<< t->Price << endl;
cout <<endl<<endl<<"Stuent Name: "<< t->StudentName << endl;
cout <<endl<<endl<<"Roll No: "<< t->RollNumber << endl;
t = t->next;
}
}
void Exit()
{
cout<<"\t\t\tThank You for using this Program";
}
//Destructor for Linked List
~LinkedList()
{
Node *t;
while (head != NULL)
{
t = head;
head = head->next;
delete t;
}
head = NULL;
count = 0;
}
};
int main()
{
LinkedList l;
int ch;
string a,b,c,d,e;
do
{
cout<<"\n\t\t\t Press 1 for Addition";
cout<<"\n\t\t\t Press 2 for Display";
cout<<"\n\t\t\t Press 3 for Exit";
cout<<"\n\t\t\t Enter Option=";
cin>>ch;
switch(ch)
{
case 1:
cout<<endl<<endl<<endl<<endl<<"Enter Book Name: ";
cin>>a;
cout<<endl<<"Enter Book No: ";
cin>>b;
cout<<endl<<"Enter Price: ";
cin>>c;
cout<<endl<<"Enter Student Name: ";
cin>>d;
cout<<endl<<"Enter Roll No: ";
cin>>e;
l.add_input_head(a,b,c,d,e);
break;
case 2:
l.traverse();
case 3:
l.Exit();
break;
}
}while(ch!=6);
}
There is no error while compiling but it still misses the last element. I don't know if the error is in input or output function.
I am making a class project and I am unable to resolve this issue.
Can somebody help me to find the mistake?

Java: Indexoutofbound in Cellualar Automaton

Here is my code for a cellular automaton I am working on:
UPDATE:
public class Lif1ID {
private Rule rule;
private int stepCount;
public static void main (String [ ] args) {
Lif1ID simulation = new Lif1ID ( );
simulation.processArgs (args);
simulation.producePBM ( ); LINE 9
}
// Print, in Portable Bitmap format, the image corresponding to the rule and step count
// specified on the command line.
public void producePBM ( ) {
int width = (stepCount*2+1);
System.out.println("P1 " + width + " " + (stepCount+1));
String prev_string = "";
// constructs dummy first line of rule
for (int i = 0; i < width; i++){
if (i == stepCount+1){
prev_string += "1";
} else {
prev_string += "0";
}
}
// contructs and prints out all lines prescribed by the rule, including the first
for (int i = 0; i < stepCount; i++) {
String next_string = "";
for (int j = 0; j < width; j++) {
// prints next line, one character at a time
System.out.print(prev_string.charAt(j) + " ");
// specifies cases for the edges as well as for normal inputs to Rule
if (j == 0) {
next_string += rule.output(0, Character.getNumericValue(prev_string.charAt(0)), Character.getNumericValue(prev_string.charAt(1)));
} else if (j == width-1) {
next_string += rule.output(Character.getNumericValue(prev_string.charAt(width-2)), Character.getNumericValue(prev_string.charAt(width-1)), 0);
} else {
String rule_input = prev_string.substring(j-1, j+2);
int first = Character.getNumericValue(rule_input.charAt(0));
int second = Character.getNumericValue(rule_input.charAt(1));
int third = Character.getNumericValue(rule_input.charAt(2));
next_string += rule.output(first, second, third); LINE 43
}
}
// sets prev_string to next_string so that string will be the next string in line to be printed
prev_string = next_string;
System.out.println();
}
}
// Retrieve the command-line arguments, and convert them to values for the rule number
// and the timestep count.
private void processArgs (String [ ] args) {
if (args.length != 2) {
System.err.println ("Usage: java Life1D rule# rowcount");
System.exit (1);
}
try {
rule = new Rule (Integer.parseInt(args[0]));
} catch (Exception ex) {
System.err.println ("The first argument must specify a rule number.");
System.exit (1);
}
try {
stepCount = Integer.parseInt (args[1]);
} catch (Exception ex) {
System.err.println ("The second argument must specify the number of lines in the output.");
System.exit (1);
}
if (stepCount < 1) {
System.err.println ("The number of output lines must be a positive number.");
System.exit (1);
}
}
}
class Rule {
private int a, b, c;
private String rulebin;
public Rule (int ruleNum) {
rulebin = convertToBinary(ruleNum);
}
private String convertToBinary(int input) // get the binary presentation as you want
{ // if the input is 2 you'll get "00000010"
String binary = "";
for (int i = 0; i < 8; i++){
if ((1 << i & input) != 0)
binary += "1";
else
binary+= "0";
}
binary = new StringBuffer(binary).reverse().toString();
return binary;
}
// Return the output that this rule prescribes for the given input.
// a, b, and c are each either 1 or 0; 4*a+2*b+c is the input for the rule.
public char output (int a, int b, int c) {
return rulebin.charAt(7 - 4*a + 2*b + c); LINE 106
}
}
Here is the error message I get when I type in rule 30 with 3 timesteps:
java Life1D 30 3
UPDATED error message:
P1 7 4
0 0 0 0Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 151
at java.lang.String.charAt(String.java:686)
at Rule.output(Life1D.java:106)
at Life1D.producePBM(Life1D.java:43)
at Life1D.main(Life1D.java:9)
The corresponding lines are noted in the code. Why am I getting this error, and how can I fix it? I've been trying to find the error for hours, and it'll a blessing if I could be helped.
The problem is that Rule.output() expects three int parameters, but what you're calling it with on the line
next_string += rule.output(0, prev_string.charAt(0), prev_string.charAt(1));
is actually an int and then 2 chars. Now, the actual character is '0', but due to the implicit conversion the language does for you, you get the ASCII code of '0', which is 48 and that's what's passed to the function Rule.output().
Now, to fix this problem you need to use the method Character.getNumericValue() like so:
next_string += rule.output(0, Character.getNumericValue(prev_string.charAt(0)), Character.getNumericValue(prev_string.charAt(1)));
Don't forget to change the other two invocations of Rule.output()
However, note that this is not the only problem in your code, as I'm still getting String index out of range: 7, because the parameters with which the Rule.output() method is called with are now all 0, but I've answered your original question. If you need more help, let me know.

Java: Indexoutofrange what is going on?

Here is my code for a cellular automaton I am working on:
public class Life1D {
private Rule rule;
private int stepCount;
public static void main (String [ ] args) {
Life1D simulation = new Life1D ( );
simulation.processArgs (args);
simulation.producePBM ( );
}
// Print, in Portable Bitmap format, the image corresponding to the rule and step count
// specified on the command line.
public void producePBM ( ) {
int width = (stepCount*2+1);
System.out.println("P1 " + width + " " + (stepCount+1));
String prev_string = "";
// constructs dummy first line of rule
for (int i = 0; i < width; i++){
if (i == stepCount+1){
prev_string += "1";
} else {
prev_string += "0";
}
}
// contructs and prints out all lines prescribed by the rule, including the first
for (int i = 0; i < stepCount; i++) {
String next_string = "";
for (int j = 0; j < width; j++) {
// prints next line, one character at a time
System.out.print(prev_string.charAt(j) + " ");
// specifies cases for the edges as well as for normal inputs to Rule
if (j == 0) {
next_string += rule.output(0, prev_string.charAt(0), prev_string.charAt(1));
} else if (j == width-1) {
next_string += rule.output(prev_string.charAt(width-2), prev_string.charAt(width-1), 0);
} else {
String rule_input = prev_string.substring(j-1, j+2);
int first = rule_input.charAt(0);
int second = rule_input.charAt(1);
int third = rule_input.charAt(2);
next_string += rule.output(first, second, third);
}
}
// sets prev_string to next_string so that string will be the next string in line to be printed
prev_string = next_string;
System.out.println();
}
}
// Retrieve the command-line arguments, and convert them to values for the rule number
// and the timestep count.
private void processArgs (String [ ] args) {
if (args.length != 2) {
System.err.println ("Usage: java Life1D rule# rowcount");
System.exit (1);
}
try {
rule = new Rule (Integer.parseInt (args[0]));
} catch (Exception ex) {
System.err.println ("The first argument must specify a rule number.");
System.exit (1);
}
try {
stepCount = Integer.parseInt (args[1]);
} catch (Exception ex) {
System.err.println ("The second argument must specify the number of lines in the output.");
System.exit (1);
}
if (stepCount < 1) {
System.err.println ("The number of output lines must be a positive number.");
System.exit (1);
}
}
}
class Rule {
private int a, b, c;
private String rulebin;
public Rule (int ruleNum) {
rulebin = Integer.toBinaryString(ruleNum);
}
// Return the output that this rule prescribes for the given input.
// a, b, and c are each either 1 or 0; 4*a+2*b+c is the input for the rule.
public int output (int a, int b, int c) {
return rulebin.charAt(7 - 4*a + 2*b + c);
}
}
Here is the error message when I run it:
P1 7 4
0 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 151
at java.lang.String.charAt(String.java:686)
at Rule.output(Life1D.java:90)
at Life1D.producePBM(Life1D.java:35)
at Life1D.main(Life1D.java:9)
What the heck? Why am I getting this error, and how can I fix it? I've been trying to find the error for hours, and it'll a blessing if I could be helped.
In this particular part you are converting integer to binary string:
rulebin = Integer.toBinaryString(ruleNum);
Now let suppose your parameters are:
first parameter = 12
second parameter = any number
Now when this code will convert this number into binary string then you will get:
rulebin = "1100" (length 4)
Now in this function:
public int output (int a, int b, int c) {
return rulebin.charAt(7 - 4*a + 2*b + c);
}
When a = b = c = 0 then this function will try to access your "rulebin's character 8" but length of your rulebin is 4. That's why you are getting String Index out of bound exception.
Note: I am not sure if you have put any restrictions on your input parameters but this can be a potential problem.
No! the problem is that you're passing char instead of int to
public int output (int a, int b, int c) {
return rulebin.charAt(7 - 4*a + 2*b + c);
}
I tried it and when the prevString.charAt(0) and prevString.charAt(1) were 0 it send to the output method those parameters (0,48,48) (try to debug it and you'll)
this cause the index out of range!
and also the convertion to binary string doesn't return 7 digits format..
UPDATE:
public class Lif1ID {
private Rule rule;
private int stepCount;
public static void main (String [ ] args) {
Lif1ID simulation = new Lif1ID ( );
simulation.processArgs (args);
simulation.producePBM ( );
}
// Print, in Portable Bitmap format, the image corresponding to the rule and step count
// specified on the command line.
public void producePBM ( ) {
int width = (stepCount*2+1);
System.out.println("P1 " + width + " " + (stepCount+1));
String prev_string = "";
// constructs dummy first line of rule
for (int i = 0; i < width; i++){
if (i == stepCount+1){
prev_string += "1";
} else {
prev_string += "0";
}
}
// contructs and prints out all lines prescribed by the rule, including the first
for (int i = 0; i < stepCount; i++) {
String next_string = "";
for (int j = 0; j < width; j++) {
// prints next line, one character at a time
System.out.print(prev_string.charAt(j) + " ");
// specifies cases for the edges as well as for normal inputs to Rule
if (j == 0) {
// take a look at the 'getNumericValue' Method.. in your version it didn't pass 0 or 1, now it does..
next_string += rule.output(0, Character.getNumericValue(prev_string.charAt(0)), Character.getNumericValue(prev_string.charAt(1)));
} else if (j == width-1) {
next_string += rule.output(prev_string.charAt(width-2), prev_string.charAt(width-1), 0);
} else {
String rule_input = prev_string.substring(j-1, j+2);
int first = Character.getNumericValue(rule_input.charAt(0));
int second = Character.getNumericValue(rule_input.charAt(1));
int third = Character.getNumericValue(rule_input.charAt(2));
next_string += rule.output(first, second, third);
}
}
// sets prev_string to next_string so that string will be the next string in line to be printed
prev_string = next_string;
System.out.println();
}
}
// Retrieve the command-line arguments, and convert them to values for the rule number
// and the timestep count.
private void processArgs (String [ ] args) {
if (args.length != 2) {
System.err.println ("Usage: java Life1D rule# rowcount");
System.exit (1);
}
try {
rule = new Rule (Integer.parseInt(args[0]));
} catch (Exception ex) {
System.err.println ("The first argument must specify a rule number.");
System.exit (1);
}
try {
stepCount = Integer.parseInt (args[1]);
} catch (Exception ex) {
System.err.println ("The second argument must specify the number of lines in the output.");
System.exit (1);
}
if (stepCount < 1) {
System.err.println ("The number of output lines must be a positive number.");
System.exit (1);
}
}
}
class Rule {
private int a, b, c;
private String rulebin;
public Rule (int ruleNum) {
rulebin = convertToBinary(ruleNum);
}
private String convertToBinary(int input) // get the binary presentation as you want
{ // if the input is 2 you'll get "00000010"
String binary = "";
for (int i = 0; i < 8; i++){
if ((1 << i & input) != 0)
binary += "1";
else
binary+= "0";
}
binary = new StringBuffer(binary).reverse().toString();
return binary;
}
// Return the output that this rule prescribes for the given input.
// a, b, and c are each either 1 or 0; 4*a+2*b+c is the input for the rule.
public char output (int a, int b, int c) { // here you want to return a char, no?
return rulebin.charAt(7 - 4*a + 2*b + c); // there is a problem with your formula
}
}

Resources