Button generating a cross sum - function

I'm looking for a tip for a AS3 script, have no idea how to start there
Button, if clicked the function is executed, which outputs a predefined value as the cross sum of a number string.
Example:
Cross sum should be 10
By clicking on the button, the function generates the number 55 or 82 or 37 or 523, ie numbers with the cross sum 10

An alternative way using % (modulo) instead of a string. You could write that into one line like this:
while (sum != 0) { qsum += sum % 10; sum /= 10; }
The trick is that modulo will give us only the last digit of the longer number, then we divide by 10 to trim off that last number (from longer) and we re-read a newer ending digit of the long number.
Example:
Long num = 1234, so each trim gives, 4 then 3 then 2 then 1 and we'll sum them up each time.
usage:
myInt = cross_sum(50); //makes myInt hold answer result of function (where ExpectedValue input is 50).
and the supporting function...
function cross_sum( ExpectedValue: int ) : int
{
var rand :int = Math.floor(Math.random() * 100000000000)
var sum :int = Math.abs( rand );
var qsum :int = 0;
while (sum != 0)
{
qsum += sum % 10; //get last digit of sum...
sum /= 10; //trim down sum by 1 digit...
}
if ( qsum == ExpectedValue ) { return rand; } //# stop here and give back "rand" as answer result.
else { cross_sum( expectedValue ); } //# else if wrong, try again...
}

Got it now.....
the function calculates a number, with the crosssum 50
function berechnen() {
var rand = Math.floor(Math.random() * 100000000000)
var sum = String(rand)
var qsum = 0;
for (var i = 0; i < sum.length; i++) {
qsum += Number(sum.charAt(i));
}
if (qsum == 50) {
summe.text = String(sum);
} else {
berechnen()
}
}

Related

Random generate three integer values and check if they are unique

First, I am generating random integer values to get some values to check.
var A1, B2, C3:int;
A1 = Math.random() * 100 + 1;
B2 = Math.random() * 100 + 1;
C3 = Math.random() * 100 + 1;
Then I want to check if all the variables are unique from each other.
if (!(A1 == B2 || A1 == C3 || B2 == C3)){
unique = true;
}else{ // Not unique
}
If the variables are not unique to each other, I want to keep only the value for A1, and then change the two other variables B2 and C3 and then again check if they are unique.
}else{ // Not unique
if (unique = false){
do{
B2 = Math.random() * A1 + 1;
C3 = Math.random() * A1 + 1;
if (!(A1 == B2 || A1 == C3 || B2 == C3)){
unique = true;
}while (unique = true)
}
trace("Not unique");
}
My problem is that I cannot get three unique values, and any help on how I can solve this is highly appreciated.
This is a case where instead of asking to resolve the problem at hand you should probably have started by explaining what you are trying to do and what's the best way to achieve it. Since you have been posting a few times already my guess is that you are trying to extract 3 unique int from a range of 0 to 100. If that's the case then you are trying to create a complex and inefficient way to do it which is interesting by itself but is far from the point. The solution is to simply generate an array of int from 0 to 100 and then extract 3 of them randomly. In that case they will always be unique and always from 0 to 100.
var intRange:Array = [];
for(var i:int = 0; i < 100; i++)
{
intRange.push(i);
}
var index:int = Math.flor(Math.random() * intRange.length);
var a:int = intRange[index];
intRange.splice(index, 1);
index = Math.flor(Math.random() * intRange.length);
var b:int = intRange[index];
intRange.splice(index, 1);
index = Math.flor(Math.random() * intRange.length);
var c:int = intRange[index];
intRange.splice(index, 1);
//3 unique int from 0 to 100 range
Your problem is the wrong code here:
if (unique = false) { // must be: if (unique == false)
do {
...
} while (unique = true) // must be: while(unique == false)
}
also it can be reduced to
while(!unique) {
...
}
Also, there you are taking random from A1, not 100. Just too many errors. The proper code should be:
var a:int, b:int, c:int; // also, why would you call variables A1, B2, C3???
a = Math.random() * 100 + 1;
do {
b = Math.random() * 100 + 1;
while(b == a);
do {
c = Math.random() * 100 + 1;
} while(c == a || c == b);
// here you have unique
Now, the answer given by BotMaster is correct and robust but it involves filling an array and splicing it which is not always ok, especially if random range is significantly more than 100 and we need only three values from it.

AS3-Flash cs6 How to make numbers have a comma?

I am making a game that when you click on the Monster your score gets +1. But when your score goes over 1000 I would like it like this 1,000 rather than 1000. I am not sure how to do this as I have not learnt much action script. I have embed number and punctuation into the font. Here is my code so far:
var score:Number = 0;
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
Monster.addEventListener(TouchEvent.TOUCH_TAP, fl_TapHandler);
function fl_TapHandler(event:TouchEvent):void
{
score = score + 1;
Taps_txt.text = (score).toString();
}
Help will greatly appreciated.
You can do like that:
function affScore(n:Number, d:int):String {
return n.toFixed(d).replace(/(\d)(?=(\d{3})+\b)/g,'$1,');
}
trace(affScore(12345678, 0)); // 12,345,678
This may not be the most elegant approach, but I wrote a function that will return the string formatted with commas;
public function formatNum(str:String):String {
var strArray:Array = str.split("");
if (strArray.length >= 4) {
var count:uint = 0;
for (var i:uint = strArray.length; i > 0; i--) {
if (count == 3) {
strArray.splice(i, 0, ",");
count = 0;
}
count++;
}
return strArray.join("");
}
else {
return str;
}
}
I tested it on some pretty large numbers, and it seems to work just fine. There's no upper limit on the size of the number, so;
trace (formatNum("10000000000000000000"));
Will output:
10,000,000,000,000,000,000
So in your example, you could use it thusly;
Taps_txt.text = formatNum(String(score));
(This is casting the type implicitly rather than explicitly using toString();, but either method is fine. Casting just looks a little neater in function calls)
Use the NumberFormatter class:
import flash.globalization.NumberFormatter;
var nf:NumberFormatter = new NumberFormatter("en_US");
var numberString:String = nf.formatNumber(1234567.89);
trace("Formatted Number:" + numberString);
// Formatted Number:1,234,567.89
To show the score with comma, you can do like this : ( comments are inside the code )
var score:Number = 0;
var score_str:String;
var score_str_len:int;
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
Monster.addEventListener(TouchEvent.TOUCH_TAP, fl_TapHandler);
function fl_TapHandler(event:TouchEvent):void
{
score = score + 1;
score_str = score.toString();
score_str_len = score_str.length;
// here you can use score > 999 instead of score_str_len > 3
Taps_txt.text =
score_str_len > 3
// example : 1780
// score_str_len = 4
// score_str.substr(0, 4 - 3) = 1 : get thousands
// score_str.substr(4 - 3) = 780 : get the rest of our number : hundreds, tens and units
// => 1 + ',' + 780 = 1,780 : concatenate thousands + comma + (hundreds, tens and units)
? score_str.substr(0, score_str_len-3) + ',' + score_str.substr(score_str_len-3)
: score_str
;
// gives :
// score == 300 => 300
// score == 1285 => 1,285
// score == 87903 => 87,903
}
EDIT :
To support numbers greater than 999.999, you can do like this :
function fl_TapHandler(event:MouseEvent):void
{
score = score + 1;
score_str = score.toString();
Taps_txt.text = add_commas(score_str);
}
function add_commas(nb_str:String):String {
var tmp_str:String = '';
nb_str = nb_str.split('').reverse().join('');
for(var i = 0; i < nb_str.length; i++){
if(i > 0 && i % 3 == 0) tmp_str += ',';
tmp_str += nb_str.charAt(i);
}
return tmp_str.split('').reverse().join('');
/*
gives :
1234 => 1,234
12345 => 12,345
123456 => 123,456
1234567 => 1,234,567
12345678 => 12,345,678
123456789 => 123,456,789
1234567890 => 1,234,567,890
*/
}
Hope that can help you.

GML Storing User Input

So I have been working on a program that ask the user to input a values and when the user exits the code by entering -99 its suppose to return the total Value of all the numbers and the average but I'm stumped My values keep getting overided by the previous one... here is my code
{
var user_Input;<br>
var output_msg;<br>
var count;<br>
var highest;<br>
var value;<br>
var total;<br>
count = 0;
do
{
user_Input = get_integer("Enter a number To add To the List(Enter -99 to leave)",-99);
if (user_Input == (-99)){
continue}
count += 1;
value = 0;
value = value + user_Input;
average = value/count;
}
until(user_Input == (-99)){
count -=1;
user_Input = user_Input + 99;
output_msg=("#Numbers Entered: " + string(count) + "##Total value of numbers: " + string(highest) + "## Average:" + string(average));`
}
show_message(output_msg);
}
How Do I make it so it doesn't override the previous one?
This is because you are setting value equal to 0 every time the while loop is executed. Try setting
value = 0;
before you start the do until loop. Perhaps right after
count = 0;
like this:
count = 0;
value = 0;
do{
user_Input = get_integer("Enter a number To add To the List(Enter -99 to leave)",-99);
if (user_Input == (-99)){continue}
count += 1;
value = value + user_Input;
average = value/count;
}

Game: nine heads and tails. I am having trouble with binary stuff

You may not understand what I wrote clearly because English is not my first language.
Anyway, here is what I wrote.
public class Exercises7point11 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
int[][] binaryNumber = {{0,0,0},{0,0,0},{0,0,0}};
System.out.print("Enter a number between 0 and 511: ");
int decimalNumber = input.nextInt();
int subtractNumber = 256, number = decimalNumber;
for (int row = 0 ; row < 3; row++){
for (int column = 0 ; column < 3; column++) {
if(number >= subtractNumber) {
binaryNumber[row][column] = 1;
number = number - subtractNumber;
}
else {
subtractNumber = subtractNumber / 2;
binaryNumber[row][column] = 0;
}
}
}
// print
for (int row = 0; row < binaryNumber.length; row++){
for (int column = 0; column < binaryNumber[row].length; column++){
if (binaryNumber[row][column] == 1)
System.out.print("T ");
else if (binaryNumber[row][column] == 0)
System.out.print("H ");
if (column == 2)
System.out.print("\n");
}
}
}
Here is the details. Nine coins are placed in a 3-by-3 matrix with some face up and some face down. You can represent the state of the coins using a 3-by-3 matrix with values 0 (heads) and 1 (tails).
Such as,
1 0 0
0 1 0
1 1 0.
There are a total of 512 possibilities, so I can use decimal numbers 0, 1, 2, 3,..., 511 to represent all states of the matrix. Write a program that prompts the user to enter a number between 0 and 511 and displays the corresponding matrix with the characters H and T.
My problem is "subtractNumber = subtractNumber / 2; binaryNumber[row][column] = 0;" in the 18 and 19 lines. Even though 'number is greater than or equal to subtractNumber, 18 and 19 lines are read.
I don't know how I can fix it.
Thank you so much!!
The output is a 3x3 matrix, but that doesn't mean you need to use a 2d array.
Here's a simpler approach. We're turning the user's input into a binary string using the toBinaryString method, then translating the binary string into H/T.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number between 0 and 511: ");
int input = sc.nextInt();
// Turn input to binary string
String binary = Integer.toBinaryString(input);
// Add enough zeros in front so that the string has 9 characters
binary = binary.format("%09d", Integer.parseInt(binary));
// Iterate through binary string one char at a time
for (int i = 1; i < 10; i++) {
if ('0' == binary.charAt(i - 1)) {
System.out.print("H ");
} else {
System.out.print("T ");
}
// New line after 3 letters
if (i % 3 == 0) {
System.out.println();
}
}
}
Example output
12 in binary is 000001100
Enter a number between 0 and 511: 12
H H H
H H T
T H H

increase chances of even number

If I am getting a random number, how do I increase my chances of making that random number to be even. I am not looking to make it even every time. I am just looking to generate a random number say... %70 of the time or %90 of the time.
private function randNum (high, low) {
return Math.floor(Math.random() * (1+high-low)) + low;
}
Would I pass in a greater range of numbers to this function? Or would I have to scrap this function altogether?
Thank you
private function randNum (high : Number, low : Number) : int
{
var even : Boolean = Math.random() < 0.7; //set probability of even number here
var rand : int = Math.floor(Math.random() * (1+high-low)) + low;
if (even)
while (rand % 2 != 0)
rand = Math.floor(Math.random() * (1+high-low)) + low;
else
while (rand % 2 != 1)
rand = Math.floor(Math.random() * (1+high-low)) + low;
return rand;
}
Test:
var even : int = 0;
var odd : int = 0;
for (var i : int = 0; i < 100000; i++)
{
var a : int = randNum(1, 20);
if (a % 2 == 0)
even++;
else
odd++;
}
trace(even, odd);
Output:
[trace] 69869 30131
A little too late ;) but another one with no loop and using bit masking operation :
ret & -2 will make your number even, then depending on the result of (Math.random() >= evenProbability) you set the lower bit to be 1 to give an odd number
function randomRange(low:int, high:int, evenProbability:Number = 0.5):int{
var ret:int = int( Math.random() * ( 1 + high - low ) ) + low
return ( ret & -2 ) | int( Math.random() >= evenProbability )
}
Here a live test with wonderfl : http://wonderfl.net/c/9IHx