Error by double to string and back in bukit 1.13 - minecraft

i want to let the player in bukkit minecraft 1.13 solve a equation for x,
i wrote a generator and its working fine. But there are fractions possible as answers so i thought i could get the players answer, check if its a fraction, convert it to a double, back to a string and see if the fraction in decimal equals the solution:
if(cmd.getName().equalsIgnoreCase("math")) {
Player p = (Player) sender;
if(mathPlayer.contains(p.getName())) {
String eing = args[0];
String eing2 = "";
String eingf = "";
double vergl = 0.0;
if(eing.contains("/")) {
eing2 = eing.replace(",", ".");
vergl = Double.parseDouble(eing2);
eingf = Double.toString(vergl).replace(".", ",");
} else {
eingf = eing;
}
int in = mathPlayer.indexOf(p.getName());
String ergeb = mathAnswer.get(in);
if(ergeb.contains(eingf)) {
World w = p.getWorld();
w.playSound(p.getLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 10, 1);
p.sendMessage("§8[§cMATH§8] §aCongratulations!");
} else {
p.sendMessage("§8[§cMATH§8] §7Wrong: Solution: " + ergeb);
}
mathPlayer.remove(in);
mathAnswer.remove(in);
} else {
String equation = genequation(p);
sender.sendMessage("§8[§cMATH§8] §7Solve for x: §a" + equation);
p.sendMessage("§8[§cMATH§8] §7Enter answer with /math <answer>!");
}
return false;
Thanks in advance

Looking through your code i believe that you have asked the user to enter a fraction and not a decimal. However, a fraction needs to be converted to decimal before you can check it.
Easiest way to do this I believe would be like so:
double partA = Double.parseDouble(args[0].substring(0, args[0].indexOf("/")));
double partB = Double.parseDouble(args[0].substring(args[0].indexOf("/") + 1))
double answer = partA / partB
This is approximate and typed on an ipad but them you would compare it to the answer of the question.
Also, but confused as why you return false at the end instead of true.
Edit:
Use ChatColor.COLOR_CHAR for the color symbol as that could cause issues later down the line

Related

How do we round only if the number is with .0 in decimal

Ex 10.0 = 10
10.3 = 10.3
10.7 = 10. 7
Looking for a convenient way from Kotlin Standard library
You can use the following function:
fun removeTrailingZeros(num: String): String {
if(!num.contains('.')) // Return the original number if it doesn't contain decimal
return num
return num
.dropLastWhile { it == '0' } // Remove trailing zero
.dropLastWhile { it == '.' } // Remove decimal in case it's the last character in the resultant string
}
You can verify the code here
You can try this:
double number = 23.471;
if (number % 1 != 0)
{
//round off here
System.out.print ("Decimal");
}
else
{
System.out.print ("Integer");
}
If you want to get a string, the easiest way is to work with a string like num.toString().replace(".0",""). For numbers conversion does not make sense since the resulting type is different for different inputs.

Game Maker Studio 2 Array taking wrong values

Hey guys I'm new to Game Maker Studio and new to the language. I'm making a game and have been working on the dialogue system.
This chunk of code was designed for characters respond to a set of choices, the dialogue starts by printing out the first element of the line_array, which it does, then give the player the choice of two responses from the response_array, which it insteads prints out the second element of the line_array and I don't understand why.
Does an argument only hold one element of an array? I'm initializing two arrays in an object oCivilian2 and pushing them through code DialogueCode which is linked to another object oRespond that supposed to allow me to sift through dialogue in game. Anything helps thanks
It's initialized here in create of oCivilian2
line_array = [3];
line_array[0] = "Ethan it's good to see you! \n I thought after the incident well.... \n well I thought we had lost you";
line_array[1] = "I've said too much";
line_array[2] = "You hit your head trying to saver her\n It was horrible";
response_array = [2];
response_array[0] = "What happened?";
response_array[1] = "I don't recall alot. How bad was it?";
counter = 0;
x1 = RESOLUTION_W / 2;
y1 = RESOLUTION_H -70;
x2 = RESOLUTION_W/2;
y2 = RESOLUTION_H;
_print = "";
responseSelected = 0;
Then the step which links it to DialogueCode when spacebar is pressed
keyActivate = keyboard_check_pressed(vk_space);
if (keyActivate)
{
var inst = collision_rectangle(oPlayer.x+3,oPlayer.y+3,oPlayer.x-3,oPlayer.y-3, oCivilian2, false, false);
if (inst != noone)
{
ScriptExecuteArray(DialogueCode, line_array);
ScriptExecuteArray(DialogueCode, response_array);
}
}
Then through to step in the object oRespond
lerpProgress += (1 - lerpProgress) / 50;
textProgress += global.textSpeed;
x1 = lerp(x1, x1Target,lerpProgress);
x2 = lerp(x2, x2Target,lerpProgress);
keyUp = (keyboard_check_pressed(vk_up)) || (keyboard_check_pressed(ord("W")))
keyDown = keyboard_check_pressed(vk_down) || keyboard_check_pressed(ord("S"));
responseSelected += (keyDown - keyUp);
var _max = 2;
var _min = 0;
if (responseSelected > _max) responseSelected = _min;
if (responseSelected < _min) responseSelected = _max;
for (var i = 0; i < 2; i++)
{
var _marker = string_pos(",", response);
if (string_pos(",",response))
{
responseScript[i] = string_copy(response,0,_marker);
string_delete(response,0,_marker);
var _marker = string_pos(",", response);
}
else
{
responseScript[i] = string_copy(response,0, string_length(response));
}
}
if (keyboard_check_pressed(vk_space))
{
counter++;
}
Then to print in oRespond
/// text
//response
NineSliceBoxStretched(sTextBox, x1,y1,x2,y2, 0);
draw_set_font(fText);
draw_set_halign(fa_center);
draw_set_valign(fa_top);
draw_set_color(c_black);
if (counter % 2 == 0)
{
var _i = 0;
var _print = string_copy(text,1,textProgress);
draw_text((x1+x2) / 2, y1 + 8, _print);
draw_set_color(c_white);
draw_text((x1+x2) / 2, y1 + 7, _print);
_i++;
}
else
{
if (array_length_1d(responseScript) > 0)
{
var _print = "";
for (var t = 0; t < array_length_1d(responseScript); t++)
{
_print += "\n";
if (t == responseSelected) _print += "--> "
_print += responseScript[t];
show_debug_message(responseScript[t]);
if (t == responseSelected) _print += " <-- "
}
draw_text((x1+x2) / 2, y1 + 8, _print);
draw_set_color(c_white);
draw_text((x1+x2) / 2, y1 + 7, _print);
}
}
Alright, i think to see many problems with your code.
First of all, since arrays in GM are dynamic declare them like
line_array[3]
is a bad practice (in my point of view)
I've never declared an array this way in GM so that could be the problem here.
Second, i don't really understand the logic of your code, always create objects, at least in the GM environment, that corresponds to "physical" entities, i would make an object for the Civilian but not for the "respond".
I've red your code a lot of times and since no one answered you in 3 months i can assume it's because no one can really understand your way of coding, and this way of coding will probably give you a lot of problems in future. The thing that you're trying to doing could be super-easy if done with a good hierarchy.
I would like to help u with this code, but i find it very chaotic.
If you've not resolved this problems, write a comment :)
I advice you to fully re-implement it even if resolved anyway.

Round outcome Fraction Apache Math Common

Is it possible to round the fraction, e.g., 3/2 becomes 1+1/2 and 11/2 becomes 5+1/2 that is produced using Apache Common Math?
Attempt
Fraction f = new Fraction(3, 2);
System.out.println(f.abs());
FractionFormat format = new FractionFormat();
String s = format.format(f);
System.out.println(s);
results in:
3 / 2
3 / 2
It looks like what you are looking for is a Mixed Number.
Since I don't think Apache Fractions has this built in, you can use the following custom formatter:
public static String formatAsMixedNumber(Fraction frac) {
int sign = Integer.signum(frac.getNumerator())
* Integer.signum(frac.getDenominator());
frac = frac.abs();
int wholePart = frac.intValue();
Fraction fracPart = frac.subtract(new Fraction(wholePart));
return (sign == -1 ? "-" : "")
+ wholePart
+ (fracPart.equals(Fraction.ZERO) ? ("") : ("+" + fracPart));
}

Convert numbers in Chinese characters to arabic numbers

I am a newbie in programming and i start with Objective C as my first language.
I am messing around with some books and tutorials, at last programing a calculator...
Everything fine and i am getting into (programming makes really fun)
Now i am asking myself how I could translate arabic numbers to chinese numbers
(e.g. arabic 4 is in chinese 四 and 8 is 八 which means 四 + 四 = 八
The chinese number system is kind of different than arabic they have signs for 100, 1000, 10000 and ja kind of twisted, which screws up my brain ... anyway do anybody have some advice, hints, tips or solutions how i can tell the computer how to work with this numbers, or even how to calculate with them?
I think everything is possible so i wont ask "If its even possible?"
Considering the Chinese numerical system (Mandarin) as described by wikipedia http://en.wikipedia.org/wiki/Chinese_numerals, where for instance:
45 is interpreted as [4] [10] [5] and written 四十五
114 is interpreted as [1] [100] [1] [10] [4] and written 一百一十四
So the trick is to decompose a number as powers of 10:
x = c(k)*10^k + ... + c(1)*10 + c(0)
where k is the largest power of 10 that divides x such that the quotient is at least 1. In the 2nd example above, 114 = 1*10^2 + 1*10 + 4.
This x = c(k)*10^k + ... + c(1)*10 + c(0) becomes [c(k)][10^k]...[c(1)][10][c(0)]. In the 2nd example again, 114 = [1] [100] [1] [10] [4].
Then map each number within bracket to the corresponding sinogram:
0 = 〇
1 = 一
2 = 二
3 = 三
4 = 四
5 = 五
6 = 六
7 = 七
8 = 八
9 = 九
10 = 十
100 = 百
1000 = 千
10000 = 万
As long as you keep track of the [c(k)][10^k]...[c(1)][10][c(0)] form, it's easy to convert to an integer that the computer can handle or to the corresponding Chinese numeral. So it's this [c(k)][10^k]...[c(1)][10][c(0)] form that I'd store in an integer array of size k+2.
I'm not familiar with Objective-C, thus I can't help you with a solution for iOS.
Nonetheless, following is the Java code for Android...
I assumed it might help you, as well as it helped me.
double text2double(String text) {
String[] units = new String[] { "〇", "一", "二", "三", "四",
"五", "六", "七", "八", "九"};
String[] scales = new String[] { "十", "百", "千", "万",
"亿" };
HashMap<String, ScaleIncrementPair> numWord = new HashMap<String, ScaleIncrementPair>();
for (int i = 0; i < units.length; i++) {
numWord.put(units[i], new ScaleIncrementPair(1, i));
}
numWord.put("零", new ScaleIncrementPair(1, 0));
numWord.put("两", new ScaleIncrementPair(1, 2));
for (int i = 0; i < scales.length; i++) {
numWord.put(scales[i], new ScaleIncrementPair(Math.pow(10, (i + 1)), 0));
}
double current = 0;
double result = 0;
for (char character : text.toCharArray()) {
ScaleIncrementPair scaleIncrement = numWord.get(String.valueOf(character));
current = current * scaleIncrement.scale + scaleIncrement.increment;
if (scaleIncrement.scale > 10) {
result += current;
current = 0;
}
}
return result + current;
}
class ScaleIncrementPair {
public double scale;
public int increment;
public ScaleIncrementPair(double s, int i) {
scale = s;
increment = i;
}
}
You can make use of NSNumberFormatter.
Like below code, firstly get NSNumber from chinese characters, then combine them.
func getNumber(fromText text: String) -> NSNumber? {
let locale = Locale(identifier: "zh_Hans_CN")
let numberFormatter = NumberFormatter()
numberFormatter.locale = locale
numberFormatter.numberStyle = .spellOut
guard let number = numberFormatter.number(from: text) else { return nil }
print(number)
return number
}

Solving math equations from a text field

I am trying to increase the performance of the update(); function below. The numbers inside the mathNumber variable will come from an NSString created from a text field. Even though I'm using five numbers I would like it to be able to run any amount that the user inserts into a text field. What are some ways I could speed up the code in update(); with C and/or Objective-C? I also would like it to work on the Mac and iPhone.
typedef struct {
float *left;
float *right;
float *equals;
int operation;
} MathVariable;
#define MULTIPLY 1
#define DIVIDE 2
#define ADD 3
#define SUBTRACT 4
MathVariable *mathVariable;
float *mathPointer;
float newNumber;
void init();
void update();
float solution(float *left, float *right, int *operation);
void init()
{
float *mathNumber = (float *) malloc(sizeof(float) * 9);
mathNumber[0] =-1.0;
mathNumber[1] =-2.0;
mathNumber[2] = 3.0;
mathNumber[3] = 4.0;
mathNumber[4] = 5.0;
mathNumber[5] = 0.0;
mathNumber[6] = 0.0;
mathNumber[7] = 0.0;
mathNumber[8] = 0.0;
mathVariable = (MathVariable *) malloc(sizeof(MathVariable) * 4);
mathVariable[0].equals = &mathPointer[5];
mathVariable[0].left = &mathPointer[2];
mathVariable[0].operation = MULTIPLY;
mathVariable[0].right = &mathPointer[3];
mathVariable[1].equals = &mathPointer[6];
mathVariable[1].left = &mathPointer[1];
mathVariable[1].operation = SUBTRACT;
mathVariable[1].right = &mathPointer[5];
mathVariable[2].equals = &mathPointer[7];
mathVariable[2].left = &mathPointer[0];
mathVariable[2].operation = ADD;
mathVariable[2].right = &mathPointer[6];
mathVariable[3].equals = &mathPointer[8];
mathVariable[3].left = &mathPointer[7];
mathVariable[3].operation = MULTIPLY;
mathVariable[3].right = &mathPointer[4];
return self;
}
// This is updated with a timer
void update()
{
int i;
for (i = 0; i < 4; i++)
{
*mathVariable[i].equals = solution(mathVariable[i].left, mathVariable[i].right, &mathVariable[i].operation);
}
// Below is the equivalent of: newNumber = (-1.0 + (-2.0 - 3.0 * 4.0)) * 5.0;
// newNumber should equal -75
newNumber = mathPointer[8];
}
float solution(float *left, float *right, int *operation)
{
if ((*operation) == MULTIPLY)
{
return (*left) * (*right);
}
else if ((*operation) == DIVIDE)
{
return (*left) / (*right);
}
else if ((*operation) == ADD)
{
return (*left) + (*right);
}
else if ((*operation) == SUBTRACT)
{
return (*left) - (*right);
}
else
{
return 0.0;
}
}
EDIT:
I first must say thank you for all of your kind posts. This is the first forum I've gotten people that don't tell me I'm a complete idiot. Sorry about the return self; I didn't realize this was an objective-C forum too (thus why I hastily used C). I have my own parser which is slow but I'm not concerned with its speed. All I want is to speed up the update() function since it slows everything down and 90% of the objects use it. Also, I'm try to get it to work faster with iOS devices since I can't compile anything in the text boxes. If you have any other advice on making update() faster I thank you.
Thanks again,
Jonathan
EDIT 2:
Well I got it to run faster by changing it from:
int i;
for (i = 0; i < 4; i++)
{
*mathVariable[i].equals = solution(*mathVariable[i].left, *mathVariable[i].right, mathVariable[i].operation);
}
To:
*mathVariable[0].equals = solution(*mathVariable[0].left, *mathVariable[0].right, mathVariable[0].operation);
*mathVariable[1].equals = solution(*mathVariable[1].left, *mathVariable[1].right, mathVariable[1].operation);
*mathVariable[2].equals = solution(*mathVariable[2].left, *mathVariable[2].right, mathVariable[2].operation);
*mathVariable[3].equals = solution(*mathVariable[3].left, *mathVariable[3].right, mathVariable[3].operation);
Is there any other way to increment it as fast as the preloaded numbers in the array like above?
Your code is a mix of styles, and contains some unwarranted uses of pointers (e.g. when passing operation to solution). It is unclear why you are passing the floats by reference, but maybe you intend that these change be changed and the expression reevaluated?
Below are some changes both to tidy and incidentally speed it up - the cost of any of this is not high and you may be guilt of premature optimization. As #Dave commented there are libraries to do parsing for you, but if you're targeting simple math expressions an operator precedence stack-based parser/evaluator is easy enough to code.
Suggestion 1: use enum - cleaner:
typedef enum { MULTIPLY, DIVIDE, ADD, SUBTRACT } BinaryOp;
typedef struct
{
float *left;
float *right;
float *equals;
BinaryOp operation;
} MathVariable;
Suggestion 2: use switch - cleaner and probably faster as well:
float solution(float left, float right, int operation)
{
switch(operation)
{
case MULTIPLY:
return left * right;
case DIVIDE:
return left / right;
case ADD:
return left + right;
case SUBTRACT:
return left - right;
default:
return 0.0;
}
}
Note I also removed passing pointers, the call is now:
*mathVariable[i].equals = solution(*mathVariable[i].left,
*mathVariable[i].right,
mathVariable[i].operation);
Now an OO person will probably object (:-)) to the switch (or the if/else) and argue each node (your MathVariable) should be an instance which knows how to perform its own operation. A C person might suggest you use function pointers in the node so they can perform their own operation. All this is design and you'll have to figure that out yourself.