I was bored, so here's an implementation of this in LISP (36 lines without all the comments):The best way to solve the above problem is actually with a reference chain. Basically, maintain just one map, from names to NameEntrys. There should be two types of NameEntrys: REFs, which contain a string (the name of another NameEntry to which it is aliased), and VALs, which contain a number (the ID of the name). When you alias a name you simply add a REF entry containing the name to which it is aliased to the dictionary.
To look up or change a name, you proceed as follows:
1. Grab the NameEntry associated with the name in dictionary.
2. If the NameEntry is a REF, set the name to the name of the REF and repeat step 1.
3. Otherwise, it is a VAL, so return (or change) the code.
This way, you can alias an alias, unlike the method proposed above. The problems it is asking about also disappear because there is no distinction between a name and an alias
(There is the possibility of the formation of what are called reference cycles under this scenario, where a chain of references is self-referential. You can make sure that a cycle can never form by disallowing the creation of aliases to names that don't exist yet).
; ****** INTERNAL interfaces.
; *** Entries
; Make a REF entry aliasing a name.
(defun make-ref-entry (name) `(ref ,name))
; Determine whether the given entry is a REF entry.
(defun ref-entryp (entry) (eq (car entry) 'ref))
; Extract the name of the REF entry.
(defun ref-entry-name (entry) (cadr entry))
; Make a VAL entry containing a code.
(defun make-val-entry (code) `(val ,code))
; Determine whether the given entry is a VAL entry.
(defun val-entryp (entry) (eq (car entry) 'val))
; Extract the code of the VAL entry.
(defun val-entry-code (entry) (cadr entry))
; *** Phonebooks
; Make a phonebook. We are making the phonebook mutable in this case.
(defun make-phonebook () (make-hash-table))
; Find the direct reference to this entry in the phonebook, if possible.
(defun phonebook-entry (phonebook name) (gethash name phonebook))
; Update the direct reference to this entry in the phonebook, or create a new one.
(defun phonebook-update (phonebook name entry) (setf (gethash name phonebook) entry))
; Follow a reference chain in a phonebook until you reach an entry that
; is not a reference.
(defun phonebook-deref (phonebook name)
(let ((entry (gethash name phonebook)))
(if (ref-entryp entry)
(phonebook-deref phonebook (ref-entry-name entry))
(cons name entry)))) ; Note that we return both the name and the value.
; We create a single phonebook behind the scenes, so you don't have to
; pass the phonebook around to add and lookup information per the API.
; If the API were modified slightly we could just pass the phonebook
; to add, lookup, alias, and change.
(defparameter *phonebook* (make-phonebook))
; ****** PUBLIC-FACING interface
; Add a new entry associated with the given name and code.
; Note that since we never allow REF chains that fail to terminate
; with a VAL entry, we just need to check whether there is any entry
; at all for add.
(defun add (name code)
(let ((entry (phonebook-entry *phonebook* name)))
(if entry
(error (format nil "An entry already exists for name: ~A" name))
(phonebook-update *phonebook* name (make-val-entry code)))))
; Given a name, retrieves the code for that name.
(defun lookup (name)
(let ((entry (cdr (phonebook-deref *phonebook* name))))
(if (val-entryp entry)
(val-entry-code entry)
(error (format nil "Could not find an entry for name: ~A" name)))))
; Given a name and an alias, make the alias a reference to the name.
; Note that we have to make the decision here of whether or not we want to
; allow "realiasing" of existing names and aliases. Currently, I'm going to
; say no.
(defun alias (name alias)
(cond
((phonebook-entry *phonebook* alias) (error (format nil "An entry already exists for name: ~A" alias)))
; This is the part where we eliminate reference cycles--whatever we are
; referring to has to already exist. Note that this could be more
; complex if we allowed realiasing, since we could form a cycle this way.
((phonebook-entry *phonebook* name)
(phonebook-update *phonebook* alias (make-ref-entry name)))
(t (error (format nil "Could not find an entry for name: ~A" name)))))
; Given a name and a code, change the entry associated with the given name and code.
(defun change (name code)
(let ((pair (phonebook-deref *phonebook* name)))
(if (cdr pair)
(phonebook-update *phonebook* (car pair) (make-val-entry code))
(error (format nil "Could not find an entry for name: ~A" name)))))
> (add 'keanu 12345)
(VAL 12345)
> (lookup 'keanu)
12345
> (alias 'keanu 'neo)
(REF KEANU)
> (change 'neo 54321)
(VAL 54321)
> (lookup 'keanu)
54321
#include <stdio.h>
#include <string.h>
#define NUM_WORDS 10
#define LENGTH 20
void sort(char words[][LENGTH], int num);
int main(void)
{
char words[NUM_WORDS][LENGTH] = {'\0'};
int i, num;
for(i = 0; i < NUM_WORDS + 1; i++)
{
printf("Enter a word: ");
scanf("%s", words[i]);
num = i;
}
printf("\nYour sorted list is: ");
sort(words, num);
printf("\n");
return 0;
}
void sort(char words[NUM_WORDS][LENGTH], int num)
{
char temp[LENGTH];
int i, j, min_index;
for(i = 0; i < num + 1; i++)
{
min_index = i;
for (j = i + 1; j < num + 1; j++)
if (strcmp(words[j], words[min_index]) < 0)
min_index = j;
if (i != min_index)
{
strcpy(temp, words[i]);
strcpy(words[i], words[min_index]);
strcpy(words[min_index], temp);
}
}
for (i = 0; i < num + 1; i++)
{
printf("%s ", words[i]);
}
}
Got yet another question, but I'm so close I can almost taste it!
So I have a program, sorts strings just fine:
My problem is that when the user enters a 0 as an input while inputting words, the program is supposed to immediately stop and sort the words already entered, NOT including the 0 entered at the end. I've tried a couple while and do while loops, but I can't seem to figure anything out.
I would probably read it in as a temporary variable first, and check if it's a 0. If it is, you can break out of your for loop early. If it's not a 0, then just throw it in your words array.
Would I use a temporary char array? If so, how can it check to see if it contains a 0? Every time I've tried to run a comparison (ie if words = '0' or whatever) it tells me I can't compare a pointer and an int.
What you are asking your compiler is:
(char []){ 'A', ' ', 's', 't', 'r', 'i', 'n', 'g', 0x00 } == (char)'0'
It doesn't know how to do this comparison.
So how would I go about doing that kind of a comparison? Sorry, but I'm completely new at this.
if (strcmp(words[i], "0") == 0) ...
for(i = 0; i < NUM_WORDS + 1; i++)
{
printf("Enter a word: ");
scanf("%s", words[i]);
if(words[i][0] == '0' && strlen(words[i]) == 1) {
break;
}
num = i;
}
Thank you guys so much. Working flawlessly now.
One of these days I'll get the hang of this.
Create a Display class that has a Document classs as member. The Constructor of the class will define the display area in terms of offset position from the top-left corner of the DOS window (the 5th row) and the height of the display area (10 rows). The Display class will get the keyboard input and move the DOS prompt based on the four arrows: Up, Down, Left, Right. Once the prompt reaches the top or bottom of the display area, the text is scrolled Down or Up respectively. To display the document’s content, the Display class will call repeatedly the getRow(nr) function The ESC button will terminate the program
Can someone help me with this or finding resources on what to do. I don't recall being taught this but the Assignment requires it so I'm a bit lost.
I have the majority of the Document class coded but need to make this Display class created to finish it off. I don't know where to begin creating the command line for usage on the app I'm making (a very simple text editor maybe something like VIM) and user input. I'll try to look over my notes for anything that will help me in the meantime
I'm not sure I understand.
If you build your executable as a console application, Windows will automatically create (and manage) a console window for your application. The console flag won't prevent you from using gui windows.
There's also a Windows API call to create a console window if your executable is built as a "windows" application, AllocConsole (wincon.h).
I somehow doubt that your teacher wants you to use that without explaining how the windows console works, unless he expects you to do your research, read the platform doc.
--
Does your teacher provides you with some library to manipulate the console?
I'm not sure. I'll email the teacher now and ask a friend who did a similar assignment last semester for help. I'll get back to you on that.
The teacher did provide resources using the <curses.h> package but isn't that a C package and not a C++ one?
Assembly question.
Could anyone explain to me how a nop sled works? I've been working on a buffer overflow assignment and in the last phase of it I have to run an exploit code five times but the stack shifts around so I can't just slap in the address for %ebp and the buffer. I was given the hint to look up nop sleds but after looking at some descriptions I'm still not sure of how they work.
Awesome yeah, I get it now. I managed to finish the last part of the phase. Felt like a genius when it said VALID.The idea is the you precede your exploit code with a large number of instructions that don't do anything. That way, you do not have to ensure that host's code jumps exactly to the beginning of your exploit code. As long as it jumps anywhere within that window of NOP instructions, it will run through them and eventually get to your exploit code.
C libraries can be used in C++.
Curses would make more sense, IMO, than using the Windows Console API in an assignment like this.
Back to your first question, I don't think PDCurses (assuming that's what you are provided) opens a console by itself. You'll most likely need to build the executable as a console application so the OS provides one automatically. And... that's assuming you are using Windows. On a *nix, it's a different story.
That's awesome. Sounds like you got a great thing going on. I'm glad you share this, it gives me something to look up to. I need to work harder.So I've been working this new job for about two months, and holy fuck have I learned a lot. I didn't realize how important javascript was to the web until recently, and I actually really enjoy it - luckily I work with some amazing people so I get some great tutelage too.
Anyway - I just finished Eloquent Javascript, and am in the process of reading Secrets of the Javascript Ninja as well as Mastering Web Applications with AngularJS. I'm also going through the Node.js/Mongo course on 10gen's website... and man, I am tired.
All that being said, I really enjoy this job and I'm really noticing myself improve. A little while ago I even presented a bit at a meetup. It wasn't earth shattering, and I was really talking about basic stuff but it was so awesome just having people assume that I knew what the fuck I was talking about.
My goal is, a year from now, to actually know what the fuck I am talking about.
BufferedReader fileOne = new BufferedReader(new FileReader("test.txt");
Char[][] testArray = {"test.txt"};
Ok, probably a dumb question, but I have to create a 2D array from a file, and right now I'm using:
Code:BufferedReader fileOne = new BufferedReader(new FileReader("test.txt"); Char[][] testArray = {"test.txt"};
But I'm getting an error of incompatible types with char and String.
Anyone have any advice on how to get this sorted out?
Your code thus far makes almost no sense.
You said that you want to read in data from a file into a 2D array - do you know how it will be broken up? Are you assuming that the character column and line row correspond to the 2D array (of characters) that you're trying to build?
You should also mention the language you're working in, but it looks like Java.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void arrayIns(int ary[], int size)
{
const int newSize = size + 1;
int *temp = new int[newSize];
temp[0] = 0;
for (int i = 0; i < size; i++)
{
temp[i + 1] = ary[i];
temp = ary;
}
}
int main()
{
int inSize;
cout << "Input array size: ";
cin >> inSize;
int* nArray = new int[inSize];
arrayIns(nArray, inSize);
for (int i = 0; i < inSize; i++)
{
cout << nArray[i] << endl;
}
cin.ignore();
cin.get();
return 0;
}
I'm getting the program to let me input a number, but the numbers that are outputted are in an assortment of numbers which I'll assume is hexadecimal.
/*
Write a function that accepts an int array and the array's size as parameters.
The function should create a new array that is one element larger than the array given as input.
The first element of the new array should be set to O.
Element 0 of the input array should be copied to element 1 of the new array,
element 1 of the input array should be copied to element 2 of the new array, and so forth.
The function should return a pointer to the new array.
*/
int* arrayIns(int ary[], int size) //function that accepts int array and array size as parameters
{
const int nSize = size + 1;
int *temp = new int[nSize];
temp[0] = 0;
for (int i = 1; i < size + 1; i++)
{
temp[i] = ary[i - 1];
}
return temp;
delete[]temp;
}
//Write driver code in main() to create an array, pass it to your function, and then print the resulting array.
int main()
{
int inSize;
cout << "Input array size: ";
cin >> inSize;
int* nArray = new int[inSize];
int* yieldedArray = arrayIns(nArray, inSize);
for (int i = 0; i < inSize; i++)
{
cout << yieldedArray[i] << endl;
}
delete[]nArray;
cin.ignore();
cin.get();
return 0;
}
You don't put anything in the array "nArray" before you pass it to the function. Thus it has garbage values by default. Garbage in, garbage out.Updated the code. Okay, now I get the first element 0 to print, but the remaining of the inputted number are garbage. Getting somewhere. Also tried to implement delete in the code, not sure if I'm using it the correct way.
Seems like anything after the first element isn't assigned, but I thought that is what the for-loop in arrayIns() was already doing.
Yup, Java, sorry about that. Forgot to mention the last time I needed help >.>
Basically the file is laid out like this:
4 4
FILE
WITH
SOME
INFO
So I need to be able to call from the file to print all that as the first part of my assignment (already figuring out a lot of the other part, but for some dumb reason this part is troubling me >.<).
Updated the code. Okay, now I get the first element 0 to print, but the remaining of the inputted number are garbage. Getting somewhere. Also tried to implement delete in the code, not sure if I'm using it the correct way.
Seems like anything after the first element isn't assigned, but I thought that is what the for-loop in arrayIns() was already doing.
Where? I don't see that.You're losing the original first element in the array, BTW.
You're losing the original first element in the array, BTW.
Where? I don't see that.
#include <algorithm>
...
std::copy_n(&arr[0], size, temp+1);
public interface IGameWorld
{
public Point getLocation(); // GameObject
public Color getColor();
public void setLocation(Point newCoord);
public void setColor(Color newColor);
}
public class GameWorld implements IGameWorld
{
// code implementing vectors etc.
publicGameWorld()
{
// add gameobjects etc.
}
public class GameObject
{
private Point location;
private Color color; // all objects have a random color
GameObject()
{
this.location = new Point(0, 0);
this.color = new Color(0, 0, 0);
}
public Point getLocation()
{
return location;
}
public Color getColor()
{
return color;
}
public void setLocation (Point newCoord)
{
this.location = newCoord; // new coordinates
}
public void setColor (Color newColor)
{
this.color = newColor;
}
}
}
hello once again. i'm stumped on a coding assignment and i get this "The type GameWorld must implement the inherited abstract method IGameWorld.insertmethod here."
Here's the basic rundown of the code
Code:public interface IGameWorld { public Point getLocation(); // GameObject public Color getColor(); public void setLocation(Point newCoord); public void setColor(Color newColor); }
and then
Code:public class GameWorld implements IGameWorld { // code implementing vectors etc. publicGameWorld() { // add gameobjects etc. } public class GameObject { private Point location; private Color color; // all objects have a random color GameObject() { this.location = new Point(0, 0); this.color = new Color(0, 0, 0); } public Point getLocation() { return location; } public Color getColor() { return color; } public void setLocation (Point newCoord) { this.location = newCoord; // new coordinates } public void setColor (Color newColor) { this.color = newColor; } } }
i'm stumped. i'm assuming that i have to put the methods in gameobject outside into the GameWorld class, which really doesn't make sense.
Your assumption is correct. Why doesn't it make sense? When a class implements an interface, you're basically saying "I promise that this class will have ALL the functions described in the interface," so when you say "public class GameWorld implements IGameWorld" you're saying the GameWorld class will have all of the functions described in IGameWorld. If you don't do it, then you get an error. If you have no intention of adding those functions to GameWorld then there's no point in having it implement IGameWorld. If your intention was for the GameObject class to have all those functions then maybe you should write "public class GameObject implements IGameWorld" instead. If it seems weird for GameObject to implement an interface called IGameWorld then maybe your interface name would make more sense if it was called IGameObject instead? Maybe those functions make more sense with a game object instead of a game world. It's all up to you, but if you say you're implementing an interface then those functions need to be there.
Been seeing you on their IRC channel since last week. It's a great language! Glad somebody else thinks so too.Just wanted to say thanks to usea for confirming my interest in Rust, I'm contributing some code to it nowCan't wait for it to hit 1.0.
Been seeing you on their IRC channel since last week. It's a great language! Glad somebody else thinks so too.
I think it's going to be big in a few years. Not like Java big, but at least in the top 50.
edit: I just looked up the top 50 according to this page http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html.
How is Go not in there, but things like Ada and Tcl are?
printf(univ[y][x] ? "\033[07m \033[m" : " ")
Ran into this from a snippet of C code for Conway's Game Of Life:
Code:printf(univ[y][x] ? "\033[07m \033[m" : " ")
And I've never seen the specifiers like that. Specifically "\033[07m" and "\033[m". It's printing out the values of the 2d board or a space but what the hell do those two values do in regards to printing it out? My C knowledge seems to be lacking in that regard.
Quick google search shows this: http://www.cplusplus.com/forum/unices/36461/