C++ Text Adventure, Trying to use vector as validation to create individualized story for that path and arrays if path is choosen - c++11

Im looking to take my vector and depending on the p_room[] choosen give a special dialog and crerate a array for that specific vector. for example if the user goes from startingRoom to startingEast then to eastlvl1 i want a special dialog for the eastlvl1 i tried if statments but they appear when the app is first ran. i want a way to create path specific dialog along with creating arrays along that path so if they reach a certain point and find an object i can create an array and store the object. but i dont want the user to always have an inventory i only want it to exist once they find an object if they find
#include <iostream>
#include <vector>
#include <string>
#include "Room.h"
using namespace std;
class Program{
public:
Program();
~Program();
void setUpRooms();
void Run();
private:
int createRoom(string name, string description);
void handleUserInput();
Room* p_ptrCurrentRooms;
vector<Room*> p_rooms;
bool p_done;
Room customRoom();
};
Program::Program(){
p_ptrCurrentRooms = nullptr;
setUpRooms();
p_done = false;
}
void Program::Run() {
string status = "";
while (!p_done){
p_ptrCurrentRooms->outputRoomInfo();
handleUserInput() ;
Menu::Pause();
}
}
void Program::setUpRooms() {
int spawn = createRoom("your house","theres a flash of light");
int startingRoom = createRoom("Town Center","You appear in a mysteries town");
int startingNorth = createRoom("Capital","You enter the capital");
int startingSouth = createRoom("Dense Forest","You enter a forest where light can barely reach the ground");
int startingEast = createRoom("Ocean","You have reached an ocean");
int startingWest = createRoom("Town","you have traveled deeper into town");
int northLevel1 = createRoom("Castle","you find a massive castle");
int northSthLevel1 = createRoom("Town center","Back at the town center but it looks different from before, yet you are unsure how");
int northEstLevel1 = createRoom("Ocean","You have reached a port");
int northWstLevel1 = createRoom("Slums","A dirtier and much more unpleasant place compared to previous surroundings ");
int northLvl2 = createRoom("Castle","you reach the castle gate and are stopped by guards, you explain your situation. They look you over and can clearly tell you arent"
" from there at least and allow you to pass with an escort. continue north to proceed with your escort. ");
//northSthLevel1
int northEstLvl2 = createRoom("Castle","You walk the castle wall, it is miles long and even taller. made from a hard stone you've never seen before");
int northWstLvl2 = createRoom("Castle","You walk the castle wall, it is miles long and even taller. made from a hard stone you've never seen before");
int southLevel1 = createRoom("Dense Forest","You travel deeper into the the dense forest, nothing interesting found");
int southNorthLevel1 = createRoom("Dense forest","The forest was so dark and dense when you entered... are you lost?");
int southEstLevel1 = createRoom("Dense Forest","just more forest nothing interesting.");
int southWstLevel1 = createRoom("Dense Forest","just more forest nothing interesting.");
int southLevel2 = createRoom("Dense Forest","You travel deeper into the the dense forest, nothing interesting found");
int southNrthLvl2 = createRoom("Dense Forest","You reach the edge of the forest, you've made it out.");
int southEstLvl2 = createRoom("Dense Forest","just more forest nothing interesting. its starting to get dark");
int southWstLvl2 = createRoom("Dense Forest","just more forest nothing interesting. its starting to get dark");
int eastLvl1 = createRoom("Ocean","You have entered the ocean continue east to swim further into ocean");
int eastNrthLvl1 = createRoom("Port","you found a port, continue east from here to board a ship");
int eastSthlvl1 = createRoom("Market","you find a market that sells a variety of the days catches");
//use northsthlvl1
int eastlvl2 = createRoom("Ocean","you have started your swim into the ocean");
int eastNrthLvl2 = createRoom("Port","you continue along the port, continue east from here to board a ship");
int eastSthlvl2 = createRoom("Market","you continue along the market that sells a variety of the days catches");
//use northSouthLevel1
int westLvl1 = createRoom("Town","The path you where walking opens into a large square with shops spread throughout the square");
int westNrthLvl1 = createRoom("Town","You come across a building marked Guild. by its stature maybe it has some importance or information. continue North to enter");
int westSthLvl1 = createRoom("Town","Hunters Lodge... wonder what information they may carry");
// use northSthLevel1
int westLvl2 = createRoom("Town square","You've entered teh center of the town square you are surrounded by shops. continue North, South, West to enter a shop and east to back up");
int westNrthLvl2 = createRoom("Guild","you've entered the guild the building seems bigger on the inside, it seems over whelming. - Continue North, West, or East to venture through guild and south to exit");
int westSthLvl2 = createRoom("Hunters Lodge","you have entered the lodge there are mounts of unknown animals on the wall. - Continue South, West, East to explore lodge and North to exit");
//use northSthLevel1
// NORTH, SOUTH, EAST, WEST
p_rooms[spawn]->setNeighbors( p_rooms[startingRoom],p_rooms[startingRoom], p_rooms[startingRoom], p_rooms[startingRoom]);
p_rooms[startingRoom]->setNeighbors(p_rooms[startingNorth],p_rooms[startingSouth],p_rooms[startingEast], p_rooms[startingWest]);
p_rooms[startingNorth]->setNeighbors(p_rooms[northLevel1], p_rooms[northSthLevel1], p_rooms[northEstLevel1], p_rooms[northWstLevel1]);
p_rooms[startingSouth]->setNeighbors(p_rooms[southNorthLevel1],p_rooms[southLevel1],p_rooms[southEstLevel1],p_rooms[southWstLevel1]);
p_rooms[startingEast]->setNeighbors(p_rooms[eastNrthLvl1],p_rooms[eastSthlvl1],p_rooms[eastLvl1],p_rooms[northSthLevel1]);
p_rooms[startingWest]->setNeighbors(p_rooms[westNrthLvl1], p_rooms[westSthLvl1], p_rooms[northSthLevel1], p_rooms[westLvl1]);
p_rooms[northLevel1]->setNeighbors(p_rooms[northLvl2],p_rooms[northSthLevel1], p_rooms[northEstLvl2], p_rooms[northWstLvl2]);
p_rooms[southLevel1]->setNeighbors(p_rooms[southNrthLvl2], p_rooms[southLevel2], p_rooms[southEstLvl2], p_rooms[southWstLvl2]);
p_rooms[eastLvl1]->setNeighbors(p_rooms[eastNrthLvl2], p_rooms[eastSthlvl2], p_rooms[eastlvl2], p_rooms[northSthLevel1]);
p_rooms[westLvl1]->setNeighbors(p_rooms[westNrthLvl2], p_rooms[westSthLvl2], p_rooms[northSthLevel1], p_rooms[westLvl2]);
p_ptrCurrentRooms = p_rooms[spawn];
}
int Program::createRoom(string name, string description){
int index = p_rooms.size();
Room* room = new Room;
room->setUp(name, description);
p_rooms.push_back(room);
return index;
}
void Program::handleUserInput(){
string userIn;
userIn = Menu::GetStringLine("What would you like to do next");
if(StringUtil::ToLower(userIn) == "north" || StringUtil::ToLower(userIn) == "n"){
if(p_ptrCurrentRooms->canGo(NORTH)){
cout << "you went North";
p_ptrCurrentRooms = p_ptrCurrentRooms->ptrNeighborNorth;
}else{
cout << "you cant go north";
}
}
else if(StringUtil::ToLower(userIn) == "south" || StringUtil::ToLower(userIn) == "s"){
if(p_ptrCurrentRooms->canGo(SOUTH)){
cout << "you went South";
p_ptrCurrentRooms = p_ptrCurrentRooms->ptrNeighborSouth;
}else{
cout << "you cant go South";
}
}
else if(StringUtil::ToLower(userIn) == "east" || StringUtil::ToLower(userIn) == "e"){
if(p_ptrCurrentRooms->canGo(EAST)){
cout << "you went East";
p_ptrCurrentRooms = p_ptrCurrentRooms->ptrNeighborEast;
}else{
cout << "you cant go East";
}
}
else if(StringUtil::ToLower(userIn) == "west" ||StringUtil::ToLower(userIn) == "w" ){
if(p_ptrCurrentRooms->canGo(WEST)){
cout<< "you went west";
p_ptrCurrentRooms = p_ptrCurrentRooms->ptrNeighborWest;
}else{
cout<< "you cant go west";
}
} else{
cout<< "Unknown command";
}
}
Program::~Program(){
for(auto ptrRoom : p_rooms){
if(ptrRoom!= nullptr){
delete ptrRoom;
}
}
}
ive tried p_room.at() or declaring the specific room in if staments but all that does is print the message first in the console

Related

I want to create an object at a position where there is nothing, but there is something wrong

I'm making a game in Unity2D where are 4 roads that tanks drive on, tanks spawn in random positions, I want to make sure that a tank can't spawn in a position that another tank is already in. When I start the game the Unity Editor crashes I think there is a problem somewhere in the do while loop but I haven't found it, hoping I described it right.
Thanks.
{
public GameObject tank;
public float spawnTime = 1f;
float positionX;
float positionY;
private bool check;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("TankSpawn", 1f, spawnTime);
}
void TankSpawn()
{
do
{
int rndY = Random.Range(1, 5);
float rndX = Random.Range(20.5f, 35.0f);
if (rndY == 1)
{
positionY = -3.5f;
positionX = rndX;
}
else if (rndY == 2)
{
positionY = 0.5f;
positionX = rndX;
}
else if (rndY == 3)
{
positionY = 4.5f;
positionX = rndX;
}
else if (rndY == 4)
{
positionY = 8.5f;
positionX = rndX;
}
GameObject[] tanks = GameObject.FindGameObjectsWithTag("tank");
foreach (GameObject tank in tanks)
{
if (tank.transform.position.x == positionX && tank.transform.position.y == positionY)
{
check = false;
}
else
{
check = true;
}
}
} while (check != true);
Instantiate(tank, new Vector2(positionX, positionY), transform.rotation);
}
}```
Firstly the problem that is doing you in:
By default bool variables. like check, are false. The while loops when check is false. The only way for check to be set to true is thru the forloop if the generated coordinates don't match any tank positions. The problem with that is that if there are no tanks in the scene the forloop is never even started meaning that there is no way for check to become true, ergo your while loop keeps looping and hangs up your editor.
A quick solution would be to check the length of found tanks array and if it is zero set check to true.
if (tanks.Length == 0)
{
check = true;
}
Sidenotes:
There is name ambiguity between the tank in the forloop and the tank in the prefab. Its good practice to avoid that.
It is extremely hard to match two float values with == due to rounding. They might be extremely close, but are still different.
With your method tanks will still overlap. I would recommend to check if a position is truly free, by using Physics2D.OverlapBox or Physics2D.OverlapCircle
If a lot of tanks spawn there might not be any valid positions. You should think of a way to timeout or impose some other limit, else you'll get softlocked in the while loop again.

How to rewrite "node->left->key" replacing -> with "(*)." in C++?

I'm new to the "->" symbol, so I'm instead replacing it with (*). . However, when I came across the line of code below, I tried replacing it and it didn't work. What am I doing wrong and is there any way to rewrite it?
I keep getting the error that "key" is a pointer and when I rewrite it, it doesn't work. I have triple checked my code, and yet I still don't understand.
struct Node{
int key;
Node *left;
Node *right;
};
Node* createNode(int key){
Node *node = new Node();
(*node).key = key;
(*node).left = NULL;
(*node).right = NULL;
return node;
}
int main(){
Node *root = createNode(1);
(*root).left = createNode(9);
cout << root->left->key; // Correct?
cout << " OR ";
cout << ((*root).left).(*key);
// this is where my code goes wrong and if I remove the (*) from key
// and just leave it like .key it's wrong because key has to be a pointer
return 0;
}
I expect the output to be "9 OR 9" but it doesn't even let me compile past that point.
If you really want to avoid the -> operator, you can write it like this:
cout << (*((*root).left)).key;
... but that's painful to write and painful to read, so it makes a great example of why the -> operator is useful :)

Trouble With Java Program using parameters and methods [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am stuck here with one programming code: Here are the instructions: http://my.fit.edu/~akhademzadeh2011/courses/cse1001/f2012/ass/ass04.pdf
And, this is my code:
import java.util.*;
public class PantherSolver {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
String input;
String p = "0| |";
int signcontrol = 1;
input = GUI(p);
int firstnumber = inputmethod(input);
int firstsign = sign(input,signcontrol);
String secondp = p1(firstsign,firstnumber,p);
String input2 = GUI(secondp);
}
public static String p1(int firstsign,int firstnumber, String p) {
if (firstsign>0) {
p = "0| "+ firstnumber +" |";
}
else {
p = "0| -"+ firstnumber +" |";
}
return p;
}
public static String GUI1(String secondp) {
Scanner kb = new Scanner(System.in);
String newinput = kb.nextLine();
System.out.println(" 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
System.out.println(" ========================================");
System.out.println(secondp);
System.out.println("1|--------------------------------------|");
System.out.println("2| OFF +/- AC |");
System.out.println("3| 1 2 3 4 5 , |");
System.out.println("4| 6 7 8 9 0 SOLVE |");
System.out.println(" ========================================");
System.out.println(" Key: " + newinput +"");
return newinput;
}
public static String GUI(String p) {
Scanner kb = new Scanner(System.in);
System.out.println(" 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
System.out.println(" ========================================");
System.out.println(p);
System.out.println("1|--------------------------------------|");
System.out.println("2| OFF +/- AC |");
System.out.println("3| 1 2 3 4 5 , |");
System.out.println("4| 6 7 8 9 0 SOLVE |");
System.out.println(" ========================================");
String input1=kb.nextLine();
System.out.println(" Key: " + input1 +"");
return input1;
}
public static int inputmethod(String input) {
Scanner kb = new Scanner(System.in);
int a = 0;
if (input.length()==2) {
if((input.charAt(0)=='0')||(input.charAt(0)=='1')) {
;
}
else if((input.charAt(0)=='2') && !((input.charAt(1)==('0'))||(input.charAt(1)==('1'))||(input.charAt(1)==('2'))||(input.charAt(1)==('S'))||(input.charAt(1)==('T'))||(input.charAt(1)==('U'))||(input.charAt(1)==('V'))||(input.charAt(1)==('W'))||(input.charAt(1)==('X'))||(input.charAt(1)==('Y'))||(input.charAt(1)==('Z')))) {
;
}
else if((input.charAt(0)=='3') && !((input.charAt(1)==('0'))||(input.charAt(1)==('2'))||(input.charAt(1)==('4'))||(input.charAt(1)==('6'))||(input.charAt(1)==('8'))||(input.charAt(1)==('T'))||(input.charAt(1)==('U')))) {
;
}
else if((input.charAt(0)=='4') && !((input.charAt(1)==('0'))||(input.charAt(1)==('2'))||(input.charAt(1)==('4'))||(input.charAt(1)==('6'))||(input.charAt(1)==('8'))||(input.charAt(1)==('U'))||(input.charAt(1)==('V'))||(input.charAt(1)==('W'))||(input.charAt(1)==('X'))||(input.charAt(1)==('Y'))||(input.charAt(1)==('Z')))) {
;
}
else if ((input.equals("20")) || (input.equals("21")) ||(input.equals("22")) ||(input.equals("2S")) ||(input.equals("2T")) ||(input.equals("2U")) ||(input.equals("2V")) ||(input.equals("2X")) ||(input.equals("2Y")) ||(input.equals("2Z")) ||(input.equals("30")) ||(input.equals("32")) ||(input.equals("34")) ||(input.equals("36")) ||(input.equals("38")) ||(input.equals("40")) ||(input.equals("42")) ||(input.equals("44")) ||(input.equals("46")) ||(input.equals("48")) ||(input.equals("4U")) ||(input.equals("4V")) ||(input.equals("4W")) ||(input.equals("4X")) ||(input.equals("4Y")) ||(input.equals("4Z"))) {
switch(input) {
case "20":
case "21":
case "22":
OFF();
break;
case "2X":
case "2Y":
case "2Z":
main(null);
break;
case "30":
a = 1;
break;
case "32":
a = 2;
break;
case "34":
a = 3;
break;
case "36":
a = 4;
break;
case "38":
a = 5;
break;
case "40":
a = 6;
break;
case "42":
a = 7;
break;
case "44":
a = 8;
break;
case "46":
a = 9;
break;
case "48":
a = 0;
break;
case "4U":
case "4V":
case "4W":
case "4X":
case "4Y":
case "4Z":
solve();
break;
}
}
else {
System.out.println("Invalid key.");
System.out.println(" Key: " + input+"");
inputmethod(input);
}
}
else {
System.out.println("Invalid key.");
System.out.println(" Key: " + input +"");
inputmethod(input);
}
return a;
}
public static int sign (String input, int signcontrol) {
int sign1 = signcontrol;
if ((input.equals("2S")) ||(input.equals("2T")) ||(input.equals("2U")) ||(input.equals("2V"))) {
sign1 = sign1 * -1;
}
else {
sign1=1;
}
return sign1;
}
public static void OFF() {
System.exit(0);
}
public static void solve() {
}
}
Where do I go from here? I'm stuck in many places. Can someone guide me? First, I'm having problems with the methods. I used a couple of methods to display the "Panther Solver" and get the input.
The assignment asks to display the "Panther Solve", then the user picks what digits he/she wants. IE "32" means 2. This is very tricky though. If the user selects the +/- sign before a digit, it changes the value that he/she is about the input to a negative. It however does NOT display the negative sign right away, but only after he/she selects the digits.
Each time you select the digit and press enter, the screen pretty much reloads itself, and in the answer key, it displays what you typed. In the "0", row, it also displays what you just selected.
If you select the +/- sign after a digit is selected, nothing will happen. If you select any valid key that does not correlate to an input, nothing should happen. Just like the quadratic equation, with a,b,c, you type in your first response (a), then input comma, then go to b, then comma, then c, then solve. Each time you input, the input is evaluated.
In the input, all letters must be capitalized, if required, or else you would return and "Invalid Key". Also, for the equation, if a=0, return "Error".
I also have to formulate a solution for imaginary numbers, using i.
I am stuck in all parts. My questions are, where do I go from here in my code.
My first problem is getting the "Panther Solver" to display first, then accept the input. The next one is evaluated the negative/positive sign, and if it comes after or before the number. If it comes after, do nothing. If before, change the value to negative.
The other one is trying to make a loop for all of this in the main statement. Because for "a" in the quadratic equation, the user could want to enter "100". So I have to loop that.
Last, on the "0" row, I have to display the previous user input, just like an actual calculator. I'm having trouble getting that, and making it fit. For example, "a" starts at two spaces from the enter. Obviously as much input is entered, "a" moves to the left.
Thanks
Like all beginners, you're making the problem too difficult by failing to decompose it into small enough chunks.
Forget about user input and interfaces. Get the base solver algorithm working with hard wired inputs that you know the answer to. Write it, test it, and put it aside. Then start developing another class that deals only with getting input values and passing them to the class that actually does the work.
When you find yourself overwhelmed by too much detail, simplify the problem into smaller parts that you can deal with. Then knit them together to solve your larger problem.
It's call decomposition. It's the basis for all problem solving, especially programming and computer science.
For goodness' sake, it's solving a quadratic equation. Panther? Unnecessarily confusing.
Don't be fooled by the name. Forget about all that fancy output and get the base solver working. There are special cases you'll need to concern yourself with:
Two real roots.
One zero root, one real root.
Two complex conjugate roots.

Simple encryption algorithm for homework. not getting decryption working properly

This is a homework question that I can't get my head around at all
Its a very simple encryption algorithm. You start with a string of characters as your alphabet:
ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!, .
Then ask the user to enter there own string that will act as a map such as:
0987654321! .,POIUYTREWQASDFGHJKLMNBVCXZ
Then the program uses this to make a map and allows you to enter text that gets encrypted.
For example MY NAME IS JOSEPH would be encrypted as .AX,0.6X2YX1PY6O3
This is all very easy, however he said that its a one to one mapping and thus implied that if I enter .AX,0.6X2YX1PY6O3 back into the program I will get out MY NAME IS JOSEPH
This doesn't happen, because .AX,0.6X2YX1PY6O3 becomes Z0QCDZQGAQFOALDH
The mapping only works to decrypt when you go backwards but the question implies that the program just loops and runs the one algorithm every time.
Even if some could say that it is possible I would be happy, I have pages and pages of paper filled up with possible workings, but I came up with nothing, the only solution to run the algorithm backwards back I don't think we are allowed to do that.
Any ideas?
Edit:
Unfortunately I can't get this to work (Using the orbit computation idea) What am I doing wrong?
//import scanner class
import java.util.Scanner;
public class Encryption {
static Scanner inputString = new Scanner(System.in);
//define alphabet
private static String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!, .";
private static String map;
private static int[] encryptionMap = new int[40];//mapping int array
private static boolean exit = false;
private static boolean valid = true;
public static void main(String[] args) {
String encrypt, userInput;
userInput = new String();
System.out.println("This program takes a large reordered string");
System.out.println("and uses it to encrypt your data");
System.out.println("Please enter a mapping string of 40 length and the same characters as below but in different order:");
System.out.println(alpha);
//getMap();//don't get user input for map, for testing!
map=".ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!, ";//forced input for testing only!
do{
if (valid == true){
System.out.println("Enter Q to quit, otherwise enter a string:");
userInput = getInput();
if (userInput.charAt(0) != 'Q' ){//&& userInput.length()<2){
encrypt = encrypt(userInput);
for (int x=0; x<39; x++){//here I am trying to get the orbit computation going
encrypt = encrypt(encrypt);
}
System.out.println("You entered: "+userInput);
System.out.println("Encrypted Version: "+encrypt);
}else if (userInput.charAt(0) == 'Q'){//&& userInput.length()<2){
exit = true;
}
}
else if (valid == false){
System.out.println("Error, your string for mapping is incorrect");
valid = true;//reset condition to repeat
}
}while(exit == false);
System.out.println("Good bye");
}
static String encrypt(String userInput){
//use mapping array to encypt data
String encrypt;
StringBuffer tmp = new StringBuffer();
char current;
int alphaPosition;
int temp;
//run through the user string
for (int x=0; x<userInput.length(); x++){
//get character
current = userInput.charAt(x);
//get location of current character in alphabet
alphaPosition = alpha.indexOf(current);
//encryptionMap.charAt(alphaPosition)
tmp.append(map.charAt(alphaPosition));
}
encrypt = tmp.toString();
return(encrypt);
}
static void getMap(){
//get a mapping string and validate from the user
map = getInput();
//validate code
if (map.length() != 40){
valid = false;
}
else{
for (int x=0; x<40; x++){
if (map.indexOf(alpha.charAt(x)) == -1){
valid = false;
}
}
}
if (valid == true){
for (int x=0; x<40; x++){
int a = (int)(alpha.charAt(x));
int y = (int)( map.charAt(x));
//create encryption map
encryptionMap[x]=(a-y);
}
}
}
static String getInput(){
//get input(this repeats)
String input = inputString.nextLine();
input = input.toUpperCase();
if ("QUIT".equals(input) || "END".equals(input) || "NO".equals(input) || "N".equals(input)){
StringBuffer tmp = new StringBuffer();
tmp.append('Q');
input = tmp.toString();
}
return(input);
}
}
You will (probably) not get your original string back if you apply that substitution again. I say probably because you can construct such inputs (they all do things like if A->B then B->A). But most inputs won't do that. You would have to construct the reverse map to decrypt.
However, there is a trick you can do if you're only allowed to go forward. Keep applying the mapping and you'll eventually return to your original input. The number of times you'll have to do that depends on your input. To figure out how many times, compute the orbit of each character, and take the least common multiple of all the orbit sizes. For your input the orbits are size 1 (T->T, W->W), 2 (B->9->B H->3->H U->R->U P->O->P), 4 (C->8->N->,->C), 9 (A->...->Y->A), and 17 (E->...->V->E). The LCM of all those is 612, so 611 forward mappings applied to the ciphertext will return you to the plaintext.
Well, you can get your string back this way only if you do reverse mapping. One to one mapping means that a single letter of your default alphabet maps to only one letter of your new alphabet and vice versa. I.e. you can't map ABCD to ABBA. It doesn't imply that you can get your initial string by doing a second round of encryption.
The thing you have described can be achieved if you use a finite alphabet and a displacement to encode your string. You can choose the displacement in such a way that after a number of rounds of encryption totalDisplacement mod alphabetSize == 0 Than you will get your string back going only forward.

Having trouble implementing a linked list in c++

I am trying to implement a simple singly linked list of integers which are to be sorted upon insertion in Visual Studio c++ 2010 express.
The problem is that when I create a new node and call the .getValue() function on it, the correct number is returned, however somehow that is being lost when I try calling getValue() on a node already in the list. The node might not be inserted into the list correctly, however I can't find why that would be the case. Some other value which looks like a reference value or something is displayed instead of the correct value.
I added current to the watch window when debugging but was still unable to see any of my variables other than the give value to be inserted. I am new to visual studio so I'm not sure if I'm missing something there. Here is my code:
#include "Node.h";
#include <iostream>
//namespace Linked{
//The first two constructors would be the first in the linked list.
Node::Node(void){
value = 0;
next = 0;
}
Node::Node(int setValue){
value = setValue;
next = 0;
}
Node::Node(int setValue,Node *nextNode){
value = setValue;
next = nextNode;
}
Node * Node::getNext(){
return next;
}
void Node::setNext(Node newNext){
next = &newNext;
}
int Node::getValue(){
return value;
}
bool Node::isEqual(Node check){
return value==check.getValue()&&next == check.getNext();
}
/*
int main(){
int firstInt, secondInt;
std::cin>>firstInt;
Node first = Node(firstInt);
std::cout<<"Enter second int: ";
std::cin>>secondInt;
Node second = Node(secondInt, &first);
std::cout<<"Second: "<<second.getValue()<<"\nFirst: "<<(*second.getNext()).getValue();
system("pause");
}*/
Here is the linked list:
//LinkedList.cpp
LinkedList::LinkedList(void)
{
head = 0;
size = 0;
}
LinkedList::LinkedList(int value)
{
head = &Node(value);
size = 1;
}
void LinkedList::insert(int value){
if(head == 0){
Node newNode = Node(value);
head = &newNode;
std::cout<<"Adding "<<(*head).getValue()<<" as head.\n";
}else{
std::cout<<"Adding ";
Node current = *head;
int numChecked = 0;
while(size<=numChecked && (((*current.getNext()).getValue())<value)){
current = (*(current.getNext()));
numChecked++;
}
if(current.isEqual(*head)&&current.getValue()<value){
Node newNode = Node(value, &current);
std::cout<<newNode.getValue()<<" before the head: "<<current.getValue()<<"\n";
}else{
Node newNode = Node(value,current.getNext());
current.setNext(newNode);
std::cout<<newNode.getValue()<<" after "<<current.getValue()<<"\n";
}
}
size++;
}
void LinkedList::remove(int){
}
void LinkedList::print(){
Node current = *head;
std::cout<<current.getValue()<<" is the head";
int numPrinted = 0;
while(numPrinted<(size-1)){
std::cout<<(current.getValue())<<", ";
current = (*(current.getNext()));
numPrinted++;
}
}
int main(){
int a[5] = {30,20,25,13,2};
LinkedList myList = LinkedList();
int i;
for(i = 0 ; i<5 ; i++){
myList.insert(a[i]);
}
myList.print();
system("pause");
}
Any guidance would be greatly appreciated!
When you create nodes in insert, you're allocating them off the stack, which means that they'll be lost after the function returns.
Get them off the heap with:
Node * newNode=new Node(value);
When you use:
Node newNode=Node(value);
You're allocating that object on the stack, which means that pointers:
&newNode
to it are only valid until that function returns. If you use heap memory this is no longer an issue, but it does mean that you have to implement a destructor for your list which goes through and deletes each node.

Resources