It says there is no suitable entry point for the program as well as invalid expression of int when attempting to use the printMenu method. My instructions specify that I need to initialize the array and menu in the main and utilize the 5 methods in a switch statement but I am tripping over the Main method. I am unable to understand how to reference an (int[] args) with a string. I was able to do it just fine with a switch statement but since moving onto methods I have struggled understanding how to reference properly and would appreciate any tops or fixes on how to adjust.
public static void Main(string[] args)
{
int[] initArray = new int[10];
Console.Write("Would you like to: \n1) Enter a number\n2)Print the array \n3)find the sum of the array\n4)Reset the array\n5)Quit\n");
int input = Convert.ToInt32(Console.ReadLine());
printMenu(int[input]);
}
public void printMenu(int[] args)
{
Console.Write("Would you like to: \n1) Enter a number\n2)Print the array \n3)find the sum of the array\n4)Reset the array\n5)Quit\n");
int input = Convert.ToInt32(Console.ReadLine());
do
{
switch (input)
{
case 1:
enterNum(args);
break;
}
} while (input < 5);
}
You can call the printMenu method like this:
printMenu(new int[]{ input });
If you have a second input you would do:
printMenu(new int[]{ input, input2 });
Using an array of integers is only logical when you want to pass in multiple integers. When you are never going to pass in more than 1 ints I suggest changing the signature of printMenu to ask for just one integer: printMenu(int arg) and just pass in the one input.
printMenu(input);
Related
I would like to know the best/correct way to get back to the initial values of an object without playing with delete and new (everything must stay on the stack)
With this 2 classes:
static const int defaultValue{15};
class Foo
{
private:
int val1{defaultValue};
short val2{4};
}
class LongStandingObject
{
public:
void resetFoo(int index);
private:
Foo foos[100];
}
If I need to reset some foos to their default values, what is the best way?
Create reset method in Foo
void Foo::reset()
{
val1 = defaultValue;
val2 = 4;
}
I don't really like the idea to have the values coming from 2 differents places and I do like to have the defaults values in the header next to the variable declaration.
Replace by a locally created Foo
void LongStandingObject::resetFoo(int index)
{
foos[index] = Foo();
}
Am I heading to trouble when the local variable is destroyed?
Use memcpy
void LongStandingObject::resetFoo(int index)
{
Foo foo;
memcpy(foos[index], &foo, sizeof(Foo));
}
Maybe less readable...
Any other method?
Your #2 is just fine, and probably the most legible.
void LongStandingObject::resetFoo(int index)
{
foos[index] = Foo();
}
There are no object lifetime issues here: the assignment operator is called on foos[index] to change its values to match the temporary object materialized from Foo(). That is, the code is exactly equivalent to
{
Foo tmp;
foos[index].val1 = tmp.val1;
foos[index].val2 = tmp.val2;
}
And if optimizations are enabled, almost any compiler will be able to just modify foos[index] directly without actually creating the temporary Foo.
If you do want a Foo::reset() function as well, you can use the same idea for it:
void Foo::reset()
{
*this = Foo();
}
I would avoid using memcpy, since the program would become incorrect if you ever make changes to Foo that make it no longer trivially copyable.
What you can do is to use std::pair on each variable. Initialized with with variable.first = variable.second = value. After, every time you want to update the variable you set: variable.second = new_value. When you want to restore to the original, you set: variable.second = variable.first. You can improve it by writing a macro RestoreDefault(var) to make the code more readable.
For example:
#define RestoreDefault(var) ((var).second = (var).first)
// int val1{180}; // Instead of this line
std::pair<int,int> val1{ 180,180}; // <- this line
val1.second = 456;
RestoreDefault(val1);
If you want to hardcoded block any possibility to re-set later the default value, write:
std::pair<const int,int> val1{ 180,180}; // <- this line
-
Addition: Same principle for array:
class Foo
{
public:
int x = 100;
int y = 200;
};
#define RestoreArrDefault(var) ((var).second.fill((var).first))
// Use:
std::pair<Foo, std::array<Foo, 100>> FooAr, FooAr2;
// You can define different arrays with different defaults:
FooAr.first = { 180,360 }; // <- Customize FooAr defaults
// In that point FooAr default is 180,360 and FooAr2 default is 100,200
FooAr.second[3] = { 2,10 }; // <- Edit FooAr index-3 item
RestoreArrDefault(FooAr); // <- Restore Default
I have several functions which receive the following type:
function<double(int,int,array2D<vector<double *>>*)>
Where array2D is a custom type. Further, I have a function which takes the following as arguments:
double ising_step_distribution(double temp,int i,int j,array2D<vector<double *>>* model)
Right now, in order to bind the first value, temp, and return a functor which has the correct signature, I am writing:
double temp = some_value;
function<double(int,int,array2D<vector<double *>>*)> step_func =
[temp](int i, int j, array2D<vector<double *>>* model){
return ising_step_distribution(temp,i,j,model);
}
}
And this works. However, the following breaks:
auto step_func =
[temp](int i, int j, array2D<vector<double *>>* model){
return ising_step_distribution(temp,i,j,model);
}
}
With the following error:
candidate template ignored:
could not match
'function<double (int, int, array2D<vector<type-parameter-0-0 *, allocator<type-parameter-0-0 *> > > *)>'
against
'(lambda at /Users/cdonlan/home/mcmc/main.cpp:200:25)'
void mix_2D_model(function<double(int,int,array2D<vector<T*>>*)> step_distribution_func,...
And so, the code clump is ugly, obfuscative and repetitive (because I am making many of these).
I have been reading the documentation, and I understand that I should be able to write:
function<double(int,int,array2D<vector<double *>>*)> step_func =
bind(ising_step_distribution,temp,_1,_2,_3);
However, the only examples I have seen are for functions of type function<void()>. This one fails with an error:
// cannot cast a bind of type
// double(&)(double,int,int,array2D<vector<double *>>*)
// as function<double(int,int,...)
How do I get a visually clean bind and cast?
How do I get a visually clean bind and cast?
One way is:
using F = function<double(int,int,array2D<vector<double *>>*)>;
auto step_func =
[temp](int i, int j, array2D<vector<double *>>* model){
return ising_step_distribution(temp,i,j,model);
}
}
And then:
auto step_func_2 = F(step_func);
mix_2D_model(step_func_2, ...);
Or:
mix_2D_model(F(step_func), ...);
I was wonder how you would go about exiting a method early. If this was a void type, I would just do "return", however since this is an int type, it wants me to return an integer. How do I return to main without returning any integers. Thanks.
public static int binarysearch(String[] myArray, String target, int first, int last)
{
int index;
if (first > last)
{
index = -1;
System.out.println("That is not in the array");
// Return to main here
}
You can't return from a method without a return value, in the traditional sense.
You can either return -1; and declare in your documentation that -1 represents a failed search, or you can throw an exception. If you throw an exception, though, you'll need to catch it. You can read more about that in the linked article.
A couple of options....
1. break;
2. return a value that you know would not be returned from a valid result. Eg 99999999 or -34
Those would be simple choices....
Edit
Of course break would only exit the loop. So youd still need to return a known value.
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.
Using this question as the base is there an alogrithm or coding example to change some text to Pascal or Camel casing.
For example:
mynameisfred
becomes
Camel: myNameIsFred
Pascal: MyNameIsFred
I found a thread with a bunch of Perl guys arguing the toss on this question over at http://www.perlmonks.org/?node_id=336331.
I hope this isn't too much of a non-answer to the question, but I would say you have a bit of a problem in that it would be a very open-ended algorithm which could have a lot of 'misses' as well as hits. For example, say you inputted:-
camelCase("hithisisatest");
The output could be:-
"hiThisIsATest"
Or:-
"hitHisIsATest"
There's no way the algorithm would know which to prefer. You could add some extra code to specify that you'd prefer more common words, but again misses would occur (Peter Norvig wrote a very small spelling corrector over at http://norvig.com/spell-correct.html which might help algorithm-wise, I wrote a C# implementation if C#'s your language).
I'd agree with Mark and say you'd be better off having an algorithm that takes a delimited input, i.e. this_is_a_test and converts that. That'd be simple to implement, i.e. in pseudocode:-
SetPhraseCase(phrase, CamelOrPascal):
if no delimiters
if camelCase
return lowerFirstLetter(phrase)
else
return capitaliseFirstLetter(phrase)
words = splitOnDelimiter(phrase)
if camelCase
ret = lowerFirstLetter(first word)
else
ret = capitaliseFirstLetter(first word)
for i in 2 to len(words): ret += capitaliseFirstLetter(words[i])
return ret
capitaliseFirstLetter(word):
if len(word) <= 1 return upper(word)
return upper(word[0]) + word[1..len(word)]
lowerFirstLetter(word):
if len(word) <= 1 return lower(word)
return lower(word[0]) + word[1..len(word)]
You could also replace my capitaliseFirstLetter() function with a proper case algorithm if you so wished.
A C# implementation of the above described algorithm is as follows (complete console program with test harness):-
using System;
class Program {
static void Main(string[] args) {
var caseAlgorithm = new CaseAlgorithm('_');
while (true) {
string input = Console.ReadLine();
if (string.IsNullOrEmpty(input)) return;
Console.WriteLine("Input '{0}' in camel case: '{1}', pascal case: '{2}'",
input,
caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.CamelCase),
caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.PascalCase));
}
}
}
public class CaseAlgorithm {
public enum CaseMode { PascalCase, CamelCase }
private char delimiterChar;
public CaseAlgorithm(char inDelimiterChar) {
delimiterChar = inDelimiterChar;
}
public string SetPhraseCase(string phrase, CaseMode caseMode) {
// You might want to do some sanity checks here like making sure
// there's no invalid characters, etc.
if (string.IsNullOrEmpty(phrase)) return phrase;
// .Split() will simply return a string[] of size 1 if no delimiter present so
// no need to explicitly check this.
var words = phrase.Split(delimiterChar);
// Set first word accordingly.
string ret = setWordCase(words[0], caseMode);
// If there are other words, set them all to pascal case.
if (words.Length > 1) {
for (int i = 1; i < words.Length; ++i)
ret += setWordCase(words[i], CaseMode.PascalCase);
}
return ret;
}
private string setWordCase(string word, CaseMode caseMode) {
switch (caseMode) {
case CaseMode.CamelCase:
return lowerFirstLetter(word);
case CaseMode.PascalCase:
return capitaliseFirstLetter(word);
default:
throw new NotImplementedException(
string.Format("Case mode '{0}' is not recognised.", caseMode.ToString()));
}
}
private string lowerFirstLetter(string word) {
return char.ToLower(word[0]) + word.Substring(1);
}
private string capitaliseFirstLetter(string word) {
return char.ToUpper(word[0]) + word.Substring(1);
}
}
The only way to do that would be to run each section of the word through a dictionary.
"mynameisfred" is just an array of characters, splitting it up into my Name Is Fred means understanding what the joining of each of those characters means.
You could do it easily if your input was separated in some way, e.g. "my name is fred" or "my_name_is_fred".