Convert numbers in Chinese characters to arabic numbers - objective-c

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
}

Related

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.

Error by double to string and back in bukit 1.13

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

Cyclomatic Complexity edges

So I'm trying to figure out if that blue line is in the right place, I know that I should have 9 edges but not sure if it's correct.
The code
public int getResult(int p1, int p2) {
int result = 0; // 1
if (p1 == 0) { // 2
result += 1; //3
} else {
result += 2; //4
}
if (p2 == 0) { //5
result += 3; //6
} else {
result += 4; //7
}
return result; //8 exit node
}
so 8 nodes and it should have 9 edges, right? Did I do the right thing?
Yes, the blue line is placed correctly because after the 3rd line, your program is going to jump to the 5th line.
The easiest way to compute cyclomatic complexity without drawing any flow diagram is as follows:
Count all the loops in the program for, while, do-while, if. Assign a value of 1 to each loop. Else should not be counted here.
Assign a value of 1 to each switch case. Default case should not be counted here.
Cyclomatic complexity = Total number of loops + 1
In your program, there are 2 if loops, so the cyclomatic complexity would be 3(2+1)
You can cross-check it with the standard formulae available as well which are as below:
C = E-N+2 (9-8+2=3)
OR
C = Number of closed regions + 1 (2+1=3)
According to wikipedia:
M = E − N + 2P,
where
E = the number of edges of the graph.
N = the number of nodes of the graph.
P = the number of connected components.
so:
9 - 8 + 2*1 = 3

Palindrome of a number - No console log

So I tried to write a code that finds the largest palindromic number from two (3 spaces long) multiplied numbers. Does my code work fine or are there no palindromes for this?
function checkPalindrom(str) {
return str === str.split('').reverse().join('');
}; //Declares the funciton to check if a string is a palindrome
var x = 999;
var y = 999;
var z = 0;
var n = z.toString(); //Declares that n is the string of z
for (i=0; i<899; i++) { //For loop: counts from 0 to 899
x*y===z; //Is this correct? z is set equal to x*y
if(checkPalindrom(n) === true) { //If n is a palindrome,
console.log(n); //Write out the palindrome
} else {
x-=1; //subtract 1 from x and run again
}
};
Also, what is the best way to check for all combinations of 3 digit numbers? Because right now I am just checking for any number from 100 to 999, but I actually need to check for all combinations...
Your post has a few problems, as well as multiple questions in it. I'll try to hone in on the major stuff but, as this is a fairly standard type of Programming 101 homework question, I'm not going to give you an exact answer right out.
First off, there are three different 'equals' in javascript, =, ==, and ===. A single = is an assignment operator and it always works from right to left. Thus,
var x = 2;
assigns the value of 2 to the variable x. In your code,
x*y === z;
has a couple of problems. First off, it is backwards. Secondly, it uses === but should be using =.
z = x*y;
That is what you were trying to put here.
In javascript, == and === are both comparitives. The triple === adds type comparison and is stronger but generally unnecessary. In almost all cases, == is sufficient. But, what it does is compare the values like inside an if statement:
if(x == 2)
This just checks if the value of x is equal to the value of 2, but the values themselves do not change.
Ok, for your other question: "number from 100 to 999, but I actually need to check for all combinations..."
The best way to handle this is a double loop:
var z;
for(var x = 100; x < 1000; x++)
for(var y = x; y < 1000; y++)
z = x*y;
This will first let x = 100, then check 100 * every number from 100 to 999. Then you let x = 101 and check 101* every number from 101 to 999.
function checkPalindrom(str) {
return str === str.split('').reverse().join('');
}; //Declares the funciton to check if a string is a palindrome
var x;
var y;
var z;
var n;
var max = 0;
for (x=999; x >= 100; x--) {
for (y=999; y >= 100; y--) {
z = x*y;
n = z.toString();
if(checkPalindrom(n) === true && max < z) {
console.log(n);
max = z;
}
}
}

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));
}