Output var not calculating - function

This is a change counter program. The change is counting correctly, but the remainder is not (remChange()). After watching a few videos, and w3schools tutorials, I'm still coming up blank as to why this is. I've added a returnChange at the bottom of each function and was able to get that last 2 functions rounded (from the float). Did I do the floating point wrong in the println? Are my return tags in the wrong place? I'm just trying to get it to work by counting the coins and giving me back the change.
Here is my code: let me know, ill be researching in the meantime.
fun main(args: Array<String>) {
var change = 10.88
getDollars(change)
getQuarters(change)
getDimes(change)
getNickles(change)
}
fun getDollars(change: Double): Double{
val numofdolla = change/(1.00).toFloat();
println(numofdolla.toInt());
val remChange = change - numofdolla * 1.00;
println(remChange)
return change
}
fun getQuarters(change: Double): Double{
val numofqtr = change/(0.25).toFloat();
println(numofqtr.toInt());
val remChange = change - numofqtr * 0.25;
println(remChange)
return change
}
fun getDimes(change: Double): Double{
val numofdime = change/(0.10).toFloat();
println(numofdime.toInt());
val remChange = change - numofdime * 0.10;
println("%.2f".format(remChange))
return change
}
fun getNickles(change: Double): Double{
val numofnick = change/(0.05).toFloat();
println(numofnick.toInt());
val remChange = change - numofnick * 0.05;
println("%.2f".format(remChange))
return change
}
I'm not looking for anyone to write my code, as an explanation would be just perfect.

I'm not sure what you're expecting to happen here, but the title of your question seems to suggest that you expect the change variable to change when calling those helper functions.
You cannot mutate a function argument within a function in Kotlin, but you can indeed return a new value from the function. It seems you tried to do that, but here your main function is not using the return values of the getXxxx functions. So your change variable is never updated.
You can update the change variable based on the result of those functions:
fun main(args: Array<String>) {
var change = 10.88
change = getDollars(change)
change = getQuarters(change)
change = getDimes(change)
change = getNickles(change)
}
That said, those functions currently return the original change variable (which is unchanged), so if you want the value to change, you probably want to return remChange instead.

Related

is there a way to declare a variable with the value of a function which takes this declaring variable as a parameter?

i am wondering is there some syntax in Kotlin for declaring a variable which will be equal to a function which takes several parameters 1 of which is said variable?
class Player(var deck: MutableList<String> = Deck().deck) {
var playerHand = Deck().deal(deck, playerHand, 6)
}
class Deck {
var deck = mutableListOf<String>()
fun deal( from: MutableList<String>, to: MutableList<String>, num: Int ){
var temp = from.slice(0 .. num).toMutableList()
to.addAll(temp)
from.removeAll(temp)
}
}
So i basically want to transfer N amount of cards from a deck inside a Deck class to a variable playerHand in Player class. I know there are numerous other ways of doing it, i just wanted to know is there a way to create a var and assign a value to it using a function that takes that var as a parameter..
I stared at your code for a while and finally realized what you're asking, I think: You want playerHand to be a MutableList whose initial values come from calling Deck().deal(). Like #broot says in the comment, the standard way to do this is to use also. I'm also assuming it's some kind of typo that you are instantiating a new Deck instance to deal from, when you already have a deck property in your class. However, that property should probably be a Deck instance directly so you still have access to the Deck functionality that goes with it.
You might consider making your Deck class implement MutableList using a delegate to simplify how it is referenced and used. Now you can directly use existing MutableList functions like shuffle() directly on your Deck instance. And I would use LinkedList specifically as the delegate because it is more efficient than the default returned by mutableListOf at removing values from the top.
I would also make the deal function simply a dealTo function because it should be assumed a Deck is only going to deal from itself.
Putting that all together:
class Player(var deck: Deck = Deck()) {
val playerHand = mutableListOf<String>().also {
deck.dealTo(it, 6)
}
}
class Deck: MutableList<String> by LinkedList<String>() {
fun dealTo(to: MutableList<String>, num: Int) {
repeat(num) {
to += removeFirst()
}
}
}

How to utilize PropertyName in Geotools for a user-defined function?

I am attempting to use the geotools.org library (Version 24) to write a user-defined function to style my GIS map according to an external data source. The documentation for the GeoTools library includes this tantalizing paragraph in the section on Functions:
When a function is used as part of a Style users often want to calculate a value based on the attributes of the Feature being drawn. The Expression PropertyName is used in this fashion to extract values out of a Feature and pass them into the function for evaluation.
This is exactly what I want to do. However, the documentation includes no actual example of how to do this.
I have spent several days trying various permutations of the Function definition, and I get the same result every time: My user-defined function only receives the geometry attribute, not the extra attributes I have specified.
I have verified that everything else works:
The features are read correctly from the shapefile
The function is actually called
The Feature geometry is passed into the function
Upon completion, the map is drawn
But I cannot get the Geotools library to pass in the additional Feature properties from the shapefile. Has anyone gotten this working, or can you even point me to an example of where this is used?
My current function definition:
package org.geotools.tutorial.function;
import mycode.data.dao.MyTableDao;
import mycode.data.model.MyTable;
import org.geotools.filter.FunctionExpressionImpl;
import org.geotools.filter.capability.FunctionNameImpl;
import org.opengis.feature.Feature;
import org.opengis.filter.capability.FunctionName;
import org.opengis.filter.expression.PropertyName;
import org.opengis.filter.expression.VolatileFunction;
import org.springframework.beans.factory.annotation.Autowired;
import java.awt.*;
import java.beans.Expression;
import java.util.Random;
public class DataFunction extends FunctionExpressionImpl {
#Autowired
MyTableDao myTableDao;
public static FunctionName NAME =
new FunctionNameImpl(
"DataFunction",
Color.class,
FunctionNameImpl.parameter("featureData1", PropertyName.class),
FunctionNameImpl.parameter("featureData2", PropertyName.class));
public DataFunction() {
super("DataFunction");
}
public int getArgCount() {
return 2;
}
#Override
public Object evaluate(Object feature) {
Feature f = (Feature) feature;
// fallback definition
float pct = 0.5F;
if (f.getProperty("featureData1") != null) {
MyTable temp = myTableDao.read(
f.getProperty("featureData1").getValue().toString(),
f.getProperty("featureData2").getValue().toString());
pct = temp.getColumnValue();
}
Color color = new Color(pct, pct, pct);
return color;
}
}
EDIT: I am invoking the function programmatically through a Style that is created in code. This Style is then added to the Layer which is added to the Map during the drawing process.
private Style createMagicStyle(File file, FeatureSource featureSource) {
FeatureType schema = (FeatureType) featureSource.getSchema();
// create a partially opaque outline stroke
Stroke stroke =
styleFactory.createStroke(
filterFactory.literal(Color.BLUE),
filterFactory.literal(1),
filterFactory.literal(0.5));
// create a partial opaque fill
Fill fill =
styleFactory.createFill(
filterFactory.function("DataFunction",
new AttributeExpressionImpl("featureData1"),
new AttributeExpressionImpl("featureData2")));
/*
* Setting the geometryPropertyName arg to null signals that we want to
* draw the default geomettry of features
*/
PolygonSymbolizer sym = styleFactory.createPolygonSymbolizer(stroke, fill, null);
Rule rule = styleFactory.createRule();
rule.symbolizers().add(sym);
FeatureTypeStyle fts = styleFactory.createFeatureTypeStyle(new Rule[] {rule});
Style style = styleFactory.createStyle();
style.featureTypeStyles().add(fts);
return style;
}
I think you want to set up your function to take a pair of Strings or Doubles (or whatever those attributes are) so something like:
public static FunctionName NAME =
new FunctionNameImpl(
"DataFunction",
Color.class,
FunctionNameImpl.parameter("featureData1", Double.class),
FunctionNameImpl.parameter("featureData2", Double.class));
public DataFunction(List<Expression> params, Literal fallback) {
this.params = params;
this.fallback = fallback;
}
then your evaluate method becomes:
#Override
public Object evaluate(Object feature) {
Feature f = (Feature) feature;
// fallback definition
float pct = 0.5F;
Expression exp1 = params.get(0);
Expression exp2 = params.get(1);
if (f.getProperty("featureData1") != null) {
MyTable temp = myTableDao.read(
exp1.evaluate(f, Double.class),
exp2.evaluate(f, Double.class));
pct = temp.getColumnValue();
}
Color color = new Color(pct, pct, pct);
return color;
}
and you would use it in the style using something like:
Fill fill =
styleFactory.createFill(
filterFactory.function("DataFunction",
filterFactory.propertyName("featureData1"),
filterFactory.propertyName("featureData2")));

Word randomization in Actionscript

In Actionscript, I'm trying to find a way to produce strings and string variables which spit out different text each time they're brought up. To purely visualize:
var text:String "Red||Blue"; //Whenever the variable is called, it's either Red or Blue
textoutput("You spot a grey||black cat."); //A function equivalent of the same issue
I can produce a function which does this effect, but it seems a variable cannot be a function, as far as I can tell.
I've considered array variables, but I have no idea how to use an array to spit out a single entry when the variable is called, and I don't know how to make this work for a string that isn't a variable -- assuming I can get away with a single system that works for both situations.
Edit
To expand upon the issue expressed in Batman's answer, using his result on a variable produces a result that 'sticks' to whichever it randomly chooses. Example:
var shoes:String = grabRandomItem("Red shoes||Crimson shoes");
trace("You have " + shoes + ".") //Whichever result is chosen it stays that way.
Moreover, I may want to change this variable to something else that is entirely not-random:
var secondshoes:String = "Blue shoes";
function newshoes():
{
shoes = secondshoes;
}
You want a random value from a list of possible values. Rather than call the variable, you can reference it dynamically...
function random(low:Number=0, high:Number=1):Number {
/* Returns a random number between the low and high values given. */
return Math.floor(Math.random() * (1+high-low)) + low;
}
var options:Array = ["red", "blue", "grey", "black"];
trace("You spot a " + options[random(0, options.length-1)] + " cat.")
//You spot a black cat.
Alternatively, you can use a function in place of a variable to remove the inline logic...
function catColor():String { return options[random(0, options.length-1)]; }
trace("You found a " + catColor() + " key.")
// You found a red key.
Or generalize it to a generic function with arguments.
var options:Object = {
"cat":["grey", "black"],
"key":["gold", "silver"],
"door":["blue", "red", "green"]
}
function get(item:String):String {
return options[item][random(0, options[item].length-1)];
}
trace("You found a " + get("door") + " door.")
// You found a green door.
There are a ton of ways to do this, but to align with the way you'd like to do it, here is the simplest way to accomplish this:
//populate your string: (remove the word private if using timeline code)
private var text_:String = "Red||Blue||Green||Yellow";
//create a getter to use a function like a property
function get text():String {
//create an array by splitting the text on instances of ||
var arr:Array = text_.split("||");
//return a random element of the array you just made
return arr[Math.floor(Math.random() * arr.length)];
}
trace(text);
Even better, create a common function to parse your string:
function grabRandomItem(str:String):String {
var arr:Array = str.split("||");
return arr[Math.floor(Math.random() * arr.length)];
}
//make a getter variable that regenerates everytime it's called.
function get label():String {
return "You spot a " + grabRandomItem("grey||black||blue||red||purple") + " cat";
}
trace(label); //anytime you access the label var, it will re-generate the randomized string
trace(label);
trace(label);
trace(label);
// ^^ should have different results
Of course, this way I think only works best if the text comes from user input. If you are hard coding the text into the app, you might as well just create it in an array directly as show in another answer you have as there's less overhead involved that way.

How do I get this Scala count down function to work?

Basically what I want this code to do is define a function, timeCount, and each time it is called I want 1 to be subtracted from 21, have the result be printed out, and have the result equal timeNum. So, I want 1 to be subtracted from 21, resulting in 20, printing out 20, then making timeNum equal to 20. Then the next time the function is called, it would be equal to 19, 18, etc, etc, ...
However, this code does not work. How can I get what I want to happen?
def timeCount() = {
var timeNum = 21
var timeLeft = timeNum-1
println(timeLeft)
var timeNum = timeLeft
}
}
class TimeCount(initial: Int) extends Function0[Int] {
var count = initial
def apply = {
count = count - 1
count
}
}
Use it like this:
scala> val f = new TimeCount(21)
f: TimeCount = <function0>
scala> f()
res0: Int = 20
scala> f()
res1: Int = 19
scala> f()
res2: Int = 18
I made two changes from what you were asking for, I made the number to start with a parameter to the constructor of the function, and I returned the count instead of printing it, because these seem more useful If you really just want to print it, change Function0[Int] to Function0[Unit] and change count to println(count.toString)
This is, of course, not threadsafe.
As the compiler error below states, you defined the same var twice.
console>:11: error: timeNum is already defined as variable timeNum
var timeNum = timeLeft
^
Keep in mind, one can modify the value of a var, but not to define it again.
Additionally, you declare and initialize the timeNum var in the function call. The result being that once it does compile you will print the same value (20) repeatedly.
Also, the timeLeft var is superfluous.

Create a Non-Database-Driven Lookup

Lots of references for creating lookups out there, but all seem to draw their values from a query.
I want to add a lookup to a field that will add items from a list of values that do not come from a table, query, or any other data source.
Such as from a string: "Bananas, Apples, Oranges"
..or a container ["Bananas", "Apples", "Oranges"]
Assume the string/container is a dynamic object. Drawing from an static enum is not a choice.
Is there a way to create lookups on the fly from something other than a data source?
Example code would be a great help, but I'll take hints as well.
There is the color picker.
Also in the Global you will find pickXxxx such as pickList.
There are others, pickUser, pickUserGroup etc.
Take a look on the implementation. I guess they build a temporary table then displays that. Tables are great!
Update:
To go on you own follow the rules.
For the advanced user, see also: Lookup form returning more than one value.
public void lookup()
{
SysTableLookup sysTableLookup;
TmpTableFieldLookup tmpTableFieldLookup;
Enumerator en;
List entitylist = new list(types::String);
entitylist.addend("Banana");
entitylist.addend("Apple");
en = entityList.getEnumerator();
while (en.moveNext())
{
tmpTableFieldLookup.TableName = en.current();
tmpTableFieldLookup.insert();
}
sysTableLookup = SysTableLookup::newParameters(tableNum(tmpTableFieldLookup), this);
sysTableLookup.addLookupfield(fieldNum(TmpTableFieldLookup, TableName));
//BP Deviation documented
sysTableLookup.parmTmpBuffer(tmpTableFieldLookup);
sysTableLookup.performFormLookup();
}
The above code helps in displaying strings as lookup.
I'm also guessing there's no way to perform a lookup without a table. I say that because a lookup is simply a form with one or more datasources that is displayed in a different way.
I've also blogged about this, so you can get some info on how to perform a lookup, even with a temporary table, here:
http://devexpp.blogspot.com.br/2012/02/dynamics-ax-custom-lookup.html
Example from global::PickEnumValue:
static int pickEnumValue(EnumId _enumId, boolean _omitZero = false)
{
Object formRun;
container names;
container values;
int i,value = -1,valueIndex;
str name;
#ResAppl
DictEnum dictEnum = new DictEnum(_enumId);
;
if (!dictEnum)
return -1;
for (i=1;i<=dictEnum.values();i++)
{
value = dictEnum.index2Value(i);
if (!(_omitZero && (value == 0)))
{
names += dictEnum.index2Label(i);
values += value;
}
}
formRun = classfactory.createPicklist();
formRun.init();
formRun.choices(names, #ImageClass);
formRun.caption(dictEnum.label());
formRun.run();
formRun.wait();
name = formRun.choice();
value = formRun.choiceInt();
if (value>=0) // the picklist form returns -1 if a choice has not been made
{
valueIndex = -1;
for (i=1;i<=conLen(names);i++)
{
if (name == conPeek(names,i))
{
valueIndex = i;
break;
}
}
if (valueIndex>=0)
return conPeek(values,valueIndex);
}
return value;
}
It isn't the most graceful solution, but this does work, and it doesn't override or modify any native AX 2012 objects:
Copy the sysLookup form from AX2009 (rename it) and import it into AX 2012.
We'll call mine myLookupFormCopy.
I did a find/replace of "sysLookup" in the XPO file to rename it.
Create this class method:
public static client void lookupList(FormStringControl _formStringControl, List _valueList, str _columnLabel = '')
{
Args args;
FormRun formRun;
;
if (_formStringControl && _valueList && _valueList.typeId() == Types::String)
{
args = new Args(formstr(myLookupFormCopy));
args.parmObject(_valueList);
args.parm(_columnLabel);
formRun = classFactory.formRunClass(args);
_formStringControl.performFormLookup(formRun);
}
}
In the lookup method for your string control, use:
public void lookup()
{
List valueList = new List(Types::String);
;
...build your valueList here...
MyClass::lookupList(this, valueList, "List Title");
super();
}