complete newbie here. I need help making two functions abs1 and abs2, in order to calculate the absolute value of the numbers -2 and -7, and print them out so it displays 27. However i don't want to change the existing loop i made, i want to add the functions separately. This is being coded on an Arduino.
This is the code i have written so far:
void setup() {
Serial.begin(9600)
}
void loop() {
int number1 = -2;
int number2 = -7;
number1 = abs1(number1);
abs2(&number2);
Serial.print(number1);
Serial.print(number2);
}
I have tried to use int abs1=abs(number1), but it only gives the error messages"number1 was not declared" or "abs1 was not declared" or " Failed to compile for Arduino Genuino Mega 2560" depending on where I place the line.
Why do you think you need two functions? Why not use the regular old abs function?
void loop() {
int number1 = -2;
int number2 = -7;
number1 = abs(number1);
number2 = abs(number2);
Serial.print(number1);
Serial.print(number2);
}
If you just need to print the absolute values just use the abs function at serial print.
void loop() {
int number1 = -2;
int number2 = -7;
Serial.print(abs(number1));
Serial.print(abs(number2));
}
Related
using System;
using static System.Console;
using System.Globalization;
class MoveEstimator
{
static void Main()
{
string entry;
int base;
base = 200;
int rph = 150;
int rpm = 2;
int input;
int hours;
int miles;
int total;
WriteLine ("Enter number of hours for job >>");
entry = ReadLine ();
WriteLine ("Enter number of miles for job >>");
string entryii = ReadLine ();
hours = Convert.ToInt32(entry);
miles = Convert.ToInt32(entryii);
total = (base + rph*hours + rpm*miles);
WriteLine ("For a move taking{0} hours and going {1}miles the estimate is {2}",hours,miles,total.ToString("C", CultureInfo.GetCultureInfo("en-US")));
}
}
I keep getting a error saying that my integer variable "base" is a unexpected symbol. all i did is say int base;. how its that wrong. I am also getting a error for every time I reference it.
First of all, welcome to the Stack Overflow!
base is a reserved keyword in C#, so you should give this variable any other name, for example initialDistance))
Take a recursive function, say:
public static long rekurs(long n) {
if (n == 0) {
return 1;
} else if (n == 1) {
return 1;
} else {
return rekurs(n - 1)*(rekurs(n - 2)+4;
}
}
When n=20, the function has to find all the values S(n) for n=2,...,19 first.
When I let n go from 20 to 21, it does the same thing again (plus finding S(20)).
Now I want to create an array, in which the found values S(n) for n=2,...,19 are filled into, so that the function for n=21 does not have to do the same thing again, but how do I get those elements?
This is the solution I figured out, it's a little bit different from the lecture example.
The keyword that helped me is "dynamic programming".
import java.util.Arrays;
public class Bsp13 {
public static final int N = 0;
public static final int Ende = 20;
public static long[] schroe = new long[N + Ende + 1];
public static void main(String[] args) {
schroe[0] = 1;
schroe[1] = 1;
for (int n = 2; n <= Ende + N; n++) {
schroe[n] = ((6 * n - 3) * (schroe[n-1]) - (n - 2) * (schroe[n-2])) / (n + 1);
}
System.out.println(schroe[N]);
System.out.println(Arrays.toString(schroe));
System.out.println(schroe[N+Ende]);
}
}
What you are trying to do is called dynamic programming. Basically it is bookkeeping in order to not compute subsolutions more than once.
So basically, you need a mapping of n values to solution values. I would suggest you use a dictionary-like-datastructure for this task.
When a value for n needs to be computed, you first check whether the solution is in the dictionary, if yes you return the result. If not, you compute the result and put it into the dictionary.
Think about how you would initialize this dictionary and how you would pass it down to the recursive function calls.
Here's a lecture video on dynamic programming where the computation of Fibonnaci-numbers using dynamic programming is explained, which is very similar to what you are trying to do:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/lecture-videos/lecture-19-dynamic-programming-i-fibonacci-shortest-paths/
I am developing a game in cocos2d-x.While trying to update the score it is displaying 11 , I want the score should be keep on increasing. below i pasted my code please help.
schedule(schedule_selector(HudLayer::updateScore));
void HudLayer::updateScore(int score)
{
score=1;
do {
score=score+10;
const int labelLength = 100;
char scoreLabelText[labelLength];
snprintf(scoreLabelText, labelLength, "Score: %d", score);
scoreLabel->setString(scoreLabelText);
} while (score<0);
The reason why your score is stuck at 11 is that at the first line of your function you set it to 1. It seems that you wanted to pass current score as an argument to this function, but it won't work like this with your schedule.
Example code for adding 10 points with every call of updateScore :
void HudLayer::updateScore() // no argument needed
{
//score=1; <- this would override current score, bug/not needed
do { // unnecessary
score=score+10;
const int labelLength = 100;
char scoreLabelText[labelLength];
snprintf(scoreLabelText, labelLength, "Score: %d", score);
scoreLabel->setString(scoreLabelText);
} while (score<0); //unnecessary
}
// in your *.h file
class HudLayer : <your inheritance> {
int score;
//your code
}
Of course you should initialize the score to some value, but do it only once, for example in the constructor or init() method.
Let me know if anything is not clear.
I'm trying to create my own functions for ReadProcessMemory and WriteProcessMemory in VisualC++ so I don't have to keep inputting all the info for every time I create a new function call. This project is Windows Form. Here's the problem
void Read(DWORD Add, int Value);
private: System::Void btnP1Money_Click_1(System::Object^ sender, System::EventArgs^e)
{
int BigMoney = 100000;
int GetMoneyValue;
DWORD MonAddr = 0x180A6C8;
Read(MonAddr, GetMoneyValue);
}
void Read(DWORD Add, int Value)
{
HWND window = FindWindow(0, _T("Process Window Name"));
DWORD pID = NULL;
DWORD base = dwGetModuleBaseAddress(pID, _T("Game.exe"));
HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pID);
GetWindowThreadProcessId(window, &pID);
ReadProcessMemory(handle, (LPCVOID)(base+Add), &Value, 4, NULL);
}
The value in game is 500, yet the value returned from Read() is 0. Not sure what I'm doing wrong. I just don't want to have to define everything in my Read() function everytime on each button click and checkbox tick ect.
Thanks
You should modify the Read header to
void Read(DWORD Add, int& Value)
I've written small example which works. Make sure that you check the content of the variable, not it's address
void Read(int& Value)
{
Value++;
}
int main(array<System::String ^> ^args)
{
int GetMoneyValue = 5;
Read(GetMoneyValue);
Console::WriteLine(GetMoneyValue);
//6;
return 0;
}
You need to pass by reference, otherwise the function gets its own copy of the int:
void Read(DWORD Add, int& Value);
Alternatively, you could return the value:
int Read(DWORD Add, int Value)
{
....
return Value;
}
How can I find the permutations of k in a given length?
For example:
The word cat has 3 letters: How can I find all the permutations of 2 in the word cat.
Result should be: ac, at, ca, ac, etc...
This is not a homework problem.
Any language could be used but more preferable: C/C++ or C#.
I know how to create the recursion for size LENGTH but not for a custom size.
Here is one in C#, which should work even with repeated characters. For example on "banana" for permutations of length 2 it gives:
ba bn ab aa an nb na nn
The basic idea is to fix the first character, then form all permutations of length k-1, then prepend the character to those k-1 length permutations. To deal with duplicate characters, we keep track of the count left (i.e the ones which can be used for sub-permutations).
Not exemplary code, but should give you the idea. (If you find bugs, let me know and I can edit).
static List<string> Permutations(Dictionary<char, int> input, int length) {
List<string> permutations = new List<string>();
List<char> chars = new List<char>(input.Keys);
// Base case.
if (length == 0) {
permutations.Add(string.Empty);
return permutations;
}
foreach (char c in chars) {
// There are instances of this character left to use.
if (input[c] > 0) {
// Use one instance up.
input[c]--;
// Find sub-permutations of length length -1.
List<string> subpermutations = Permutations(input, length - 1);
// Give back the instance.
input[c]++;
foreach (string s in subpermutations) {
// Prepend the character to be the first character.
permutations.Add(s.Insert(0,new string(c,1)));
}
}
}
return permutations;
}
And here is the full program I have, to use it:
using System;
using System.Collections.Generic;
namespace StackOverflow {
class Program {
static void Main(string[] args) {
List<string> p = Permutations("abracadabra", 3);
foreach (string s in p) {
Console.WriteLine(s);
}
}
static List<string> Permutations(string s, int length) {
Dictionary<char, int> input = new Dictionary<char, int>();
foreach (char c in s) {
if (input.ContainsKey(c)) {
input[c]++;
} else {
input[c] = 1;
}
}
return Permutations(input, length);
}
static List<string> Permutations(Dictionary<char, int> input,
int length) {
List<string> permutations = new List<string>();
List<char> chars = new List<char>(input.Keys);
if (length == 0) {
permutations.Add(string.Empty);
return permutations;
}
foreach (char c in chars) {
if (input[c] > 0) {
input[c]--;
List<string> subpermutations = Permutations(input,
length - 1);
input[c]++;
foreach (string s in subpermutations) {
permutations.Add(s.Insert(0,new string(c,1)));
}
}
}
return permutations;
}
}
}
What's wrong with the recursive solution and passing an extra parameter (depth) so that the recursive function returns immediately for depth > n.
Not the most efficient, but it works:
public class permutation
{
public static List<string> getPermutations(int n, string word)
{
List<string> tmpPermutation = new List<string>();
if (string.IsNullOrEmpty(word) || n <= 0)
{
tmpPermutation.Add("");
}
else
{
for (int i = 0; i < word.Length; i++)
{
string tmpWord = word.Remove(i, 1);
foreach (var item in getPermutations(n - 1, tmpWord))
{
tmpPermutation.Add(word[i] + item);
}
}
}
return tmpPermutation;
}
}
void Prem (char *str, int k, int length) {
if (k == length-1){
printf("%s\n",str);
return;
} else {
for (int i = k ; i < length; ++i) {
char t = str[k];
str[k] = str[i];
str[i] = t;
Prem(str,k+1,length);
t = str[k];
str[k] = str[i];
str[i] = t;
}
}
}
If I'm not mistaken, this problem can be solved by combinadics too, as on http://en.wikipedia.org/wiki/Combinadic/, there are reference implementations there too.
I have used the Java solution (http://docs.google.com/Doc?id=ddd8c4hm_5fkdr3b/) myself for generating all possible triples from a sequence of numbers, this should be no different.
I lack the wherewithal to explain the math behind it, but as I understand this is the least complex way to iterate over all possible nCr (i.e. 3C2 for your cat example) choices within a collection.
First find the possible subsets of your array. You can do this in
a recursive way it was discussed in Iterating over subsets of any size
Second calculate the permutations of every subset with the STL-Algorithm
next_permutation
I haven't implemented it but i think it should work.