structure with data model including array of tuples - swiftui

This is my data model inside a structure. There is an array with 15 up to 30 elements, depending on the situation. It is an array of tuples and that has its disadvantages. What is the cleanest way to rewrite my datamodel? And what are advantages and disadvantages?
import SwiftUI
import Combine
import Foundation
struct Egg: Identifiable {
typealias EggDay = (day: Int, mW: Double, measured: Bool, daily: Double)
let id: Int
let taxonomy: String
let species: String
let layDate: Date
let daysToPip: Int
let daysToHatch: Int
let weightLossMin : Int
let weightLossMax: Int
let temperature: Double
let humidity: Double
let actualWeights : [EggDay]
}
In my app I work with an array of Eggs, mainly to have a List with eggs to be able to select one. And then the selected egg displays all days to edit/add measurements.

The main disadvantage of the tuple in your case is tuples can not conform protocols like Identifiable.
Another one is that you can change struct to class to make your eggs reference type later, but it's hard for doing that for a tuple and needs lots of changes.
Note: Almost all iOS frameworks contains Foundation, don't import it again.

Related

How to use variable to help pick member of struct to utilize

In the program I am writing I have various structs with several members. Saved in several string I have different members of the structs names. How do I use those strings to choose the data from the member I want?
Example:
struct teams
{ double x;
double y;
};
teams cardinals = {1, 2};
teams pirates = {};
teams cubs = {};
team1 = "cardinals";
I want to do the equivalent of outputting team1.x but I have no idea how. Help?
C++ is a strongly typed language, so you really can't achieve this. There are languages like ruby which give you the feature of converting a symbol to a string and vice-versa.
As I understand your questions, What you probably are asking is to associate names for selecting structures. Based on this understanding, you could create enum, declare vector or array of structs and then use them
enum {CARDINALS=0, PIRATES, CUBS, MAX_SIZE};
struct teams
{ double x;
double y;
};
struct teams allTeams[MAX_SIZE+1];
teams[CARDINALS] = {1,2};
Hope it helps!

Dynamic Structs in C++

For a project in C++ (I'm relatively new to this language) I want to create a structure which stores a given word and a count for multiple classes. E.g.:
struct Word
{
string word;
int usaCount = 0;
int canadaCount = 0;
int germanyCount = 0;
int ukCount = 0;
}
In this example I used 4 classes of countries. In fact there are hundreds of country classes.
My questions regarding this are the following:
Is there any way to generate this list of countries dynamically? (E.g. there is a file of countries which is read and on that basis this struct is generated)
Fitting for this struct should be a function which increments the count if the class is seen. Is there also a way to make this "dynamic" by which I mean that I want to avoid one function per class (e.G.: incUsa(), incCanada(), incGermany() etc.)
Since I'm not really used to C++: Is this even the ideomatic approach to it? Perhaps there's a better data structructure or an alternative (and more fitting) way to result the problem.
Thanks in advance.
In C++ class and struct definitions are statically created at compile time, so you can't, for example, add a new member to a struct at runtime.
For a dynamic data structure, you can use an associative container like std::map:
std::map<std::string, int> count_map;
count_map["usa"] = 1;
count_map["uk"] = 2;
etc...
You can include count_map as a member in the definition of your struct Word:
struct Word
{
std::string word;
std::map<std::string, int> count_map;
};
Consider std::map. You could create a map of countries to a map of words to counts. Or a map words to a map of countries to counts. Whether you use an enum or strings for your country codes is up to you.

Concise initialization syntax for nested variants?

I'm working a small C++ JSON library to help sharpen my rusty C++ skills, and I'm having trouble understanding some behavior with initialization lists.
The core of the library is a variant class (named "var") that stores any of the various JSON datatypes (null, boolean, number, string, object, array).
The goal is for var to work as closely as possible to a JavaScript variable, so there's lots of operator overloading going on. The primitive datatypes are easy to take care of...
var fee = "something";
var fie = 123.45;
var foe = false;
The problem is with objects (maps) and arrays (vectors).
To get something close to a JavaScript object and array literal syntax, I'm using initialization lists. It looks like this:
// in my headers
typedef var object[][2];
typedef var array[];
// in user code
var foo = (array){ 1, "b", true };
var bar = (object){ { "name", "Bob" }, { "age", 42 } };
This works out pretty nicely. The problem comes in with nested lists.
var foo = (array){ 1, "b", (array){ 3.1, 3.2 } };
For some reason my variant class interprets the nested "array" as a boolean, giving:
[1, "b", true]
Instead of:
[1, "b", [3.1, 3.2]]
If I explicitly cast the inner list to a var, it works:
var foo = (array){ 1, "b", (var)(array){ 3.1, 3.2 } };
Why do I have to explicitly cast the inner list to a var after I cast it to an array, and how can I get around this extra cast? As far as I can tell it should be implicitly converting the array to my var class anyway, since it's using the constructor for an array of vars:
template <size_t length>
var(const var(&start)[length]) {
// internal stuff
init();
setFromArray(vector<var>(start, start + length));
}
It seems that without the explicit cast to var, the initialization list somehow gets cast to something else on its way from being cast from an array to a var. I'm trying to understand why this happens, and how to avoid it.
Here's a gist with the complete source. Let me know if I should add anything relevant to the question.
Update
Apparently (foo){1, "two"} does not actually cast an initialiation list; it's a complete expression called a compound literal. It seems that it's only available in C, although g++ doesn't complain unless you give it -pedantic.
It looks like my options are:
Find another concise initialization syntax that is officially supported.
Use compound literals and hope they work in other compilers.
Drop support for C++ < 11 and use initializer_list.
Don't offer a concise initialization syntax.
Any help with the first option would be the sort of answer I'm looking for at this point.
Macros are another sort of last-ditch option, and I've written some that do the job, but I'd like to not have to use them.
You need to use the facilities already provided to you by Boost.
typedef boost::optional<boost::make_recursive_variant<
float, int, bool, //.. etc
std::unordered_map<std::string, boost::optional<boost::recursive_variant_>>,
std::vector<boost::recursive_variant_>
> JSONType;
They can easily define recursive variant types.

C++ Classes: Christian Holiday Calculator

Basically, I'm trying to complete this exam-style question for exam practice. I know how to do everything but the last question, to do with classes. I kinda get them, but don't know how to apply it to the question. Could anybody give me some starting points or tips (or even possible answers) to how I would go about creating a C++ class? Any help is much appreciated. The question is below. Apologies about how long it is.
In 1800 the mathematician Carl Friedrich Gauss presented an algorithm for calculating the
date of the Easter holiday in the new Gregorian calendar (introduced in the British Empire in
the year 1752). For this a number of expressions need to be evaluated:
Two terms M and N, which for a given year y hold the values:
year M N
1700-1799 23 3
1800-1899 23 4
1900-2099 24 5
2100-2199 24 6
The expressions are:
a = y mod 19
b = y mod 4
c = y mod 7
d = (19a + M) mod 30
e = (2b + 4c + 6d + N) mod 7
If 22+d+e is smaller than 32 than this sum is the day of the Easter holiday in March.
Otherwise d+e-9 is the day of Easter in April unless:
- the result is the 26th April, in which case Easter is on the 19th April instead
- the result is the 25th April, in which case Easter is on the 18th of April if d is 28 and
a is greater than 10
a) Implement a C/C++ function that given a year as parameter will
print out the date for the Easter holiday. (10 marks)
Other Christian holidays can be calculated from the date of Easter:
Good Friday is the Friday before Easter Sunday.
Palm Sunday is the Sunday before Easter Sunday.
Whit Sunday is 7 weeks after Easter Sunday.
Ascension day is 10 days before Whit Sunday.
Note: April and June are 30 days long, whereas March and May are 31 days long.
b) Design/describe algorithms for identifying the date for the Christian
holidays "Good Friday", "Palm Sunday", "Ascension" and "Whit
Sunday". (no source code is required for this answer) (15 Marks)
The terms M and N in the Easter calculation algorithm described by Gauss can also
be calculated using the following expressions:
k = floor(y/100)
p = floor((13 + 8k)/25)
q = floor(k/4)
M = (15 − p + k − q) mod 30
N = (4 + k − q) mod 7
The floor function rounds down a value – in the maths library math.h this is
available as a C function with the prototype double floor(double);
c) Produce a C++ class to implement a Christian Holiday calculator. It
should have private attributes (member variables) representing the
day, month and year of the date and a private method for
calculating the terms M and N. The default constructor should set
all attributes to 0. It should be possible to change the year using a
set() method and to retrieve day and month using get() methods.
The class should also contain compute methods for the different
holidays – example: computeEaster().
...how I would go about creating a C++ class?
Creating a class is simple:
class foobar
{
public:
private:
};
There! you now have a class foobar. That class can be whatever you want it to be. Fill in the public and private sections as appropriate.
Could anybody give me some starting points or tips...
As for how to use classes on how to solve a given problem, here are the general steps in roughly sequential order:
Identify the requirements of the problem. What needs solving?
Reform those requirements as a list of responsibilities. What does your program have to do to fulfill those requirements?
Group those responsibilities together to form a cohesive class object. How does this class object contribute to the overall solution of the problem? How will this object actually be used?
Express and capture that usage in a unit test for each of those objects. While doing this, you can pretend that that class is already implemented and whatever member functions you need from it is available.
Finally, implement that class so the unit test passes.
One last note, as David's comment already pointed out, copying and pasting the original problem verbatim into your question is a bad idea. People will be (substantially) less inclined to read it through. You can increase the likelihood for a response if you clarified exactly what trouble you're having and cutting out all the irrelevant parts.
So, you are stuck on creating a class. Either you don't know how to create a class at all, or you don't know how to create this specific class.
To create a class at all, use the class keyword: class { int i; };. If you have not yet created any classes in C++, then you may need to retake this or another C++ programming class.
If your problem, instead, is that you don't understand how to translate your professor's class design into C++ code, then you are not nearly as alone as you feel. Translating from ambiguous English design statements to concrete C++ programs is difficult, and is the reason we get paid the big bucks.
Let's go through it step by step.
Produce a C++ class to implement a Christian Holiday calculator.
That sounds easy enough, doesn't it?
class ChristianHolidayCalculator {
};
There, that step is done!.
It should have private attributes (member variables) representing the day, month and year of the date
Do you know what attributes or member variables are? Do you need to check the index of your textbook? Go ahead, I'll wait. ... Oh, you're back! You must have seen that member variables are a collection of variables which are scoped by the class declaration and which spring into existence (as a group) everytime an object of that class is created.
class ChristianHolidayCalculator {
double width;
double height;
double depth;
};
Oh, you thought I would name them "year", "month", and "day"? No, that's your homework, not mine. Since you told us that you know how to do the math, I'll leave the specifics to you.
and a private method for calculating the terms M and N.
There are two more vocabulary words: method and private. Go review your course material for those.
You surely found that a method is a function inside the class scope. Methods are special in that they are invoked only in relation to objects of the class at hand.
As for "private", well, I'll leave that to you. Surely you learned something about classes this year?
class ChristianHolidayCalculator {
double width;
double height;
double depth;
void GuitarTune() {
// Code to tighten strings goes here.
}
};
Since this method has to compute M and N, you'll need someplace to store the results. Hmm, maybe you need more member variables?
Finally, your teacher mentioned set(), get() and compute() methods. This is his shorthand way of telling you which public methods to create. He probably doesn't mean literally int get() { ... }. He probably means that you need to create a group of methods, all similar in name and in design:
class ChristianHolidayCalculator {
double width;
double height;
double depth;
void GuitarTune() {
// Code to tighten strings goes here.
}
int getRed() { /* return red value */ }
int getGreen() { /* return green value */ }
int getBlue() { /* return blue value */ }
void setRed(int newRed) { /* assign red value */ }
void setGreen(int newGreen) { /* guess */ }
... calculateEaster() ... { ... }
};
There is how you start to create the class. I hope this gives the push you need to get started. Good luck on your exams.

Questions on Scala from a C++ programmer (structs and stl)

I am having problems translating C++ data structures to Scala. Scala is really different from C++, but I like a lot of it.
I have the following Code fragment in C++:
struct Output
{
double point;
double solution[6];
};
struct Coeff
{
double rcont1[6];
double rcont2[6];
double rcont3[6];
double rcont4[6];
double rcont5[6];
double rcont6[6];
};
std::list<Output> output;
std::list<Coeff> coeff;
I now fill the list in a while loop with data
while(n<nmax) {
if step successfull
Output out;
out.point = some values;
out.solution[0] = some value;
output.push_back(out);
}
I tried creating a simple class in Scala to hold the data.
class Output
{
var point: Double
var solution: Array[Double] = new Array(6)
}
But this doens't work since point is not initialized. Is there a way around this? I just want to define the variable but not initialize it.
Another quick thing. I am looking for an equivalent to stl::lower_bound.
Is finds the right position to insert an element in an sorted container to maintain the order.
Thanks for helping a Scala beginner
Why don't you want to initialize it? For efficiency? I'm afraid that the JVM doesn't let you get away with having random junk in your variables based on whatever was there originally. So since you have to initialize it anyway, why not specify what your "uninitialized" value is?
class Output {
var point = 0.0
var solution = new Array[Double](6)
}
(You could use Double.NaN and check for point.isNaN if you later need to see whether the value has been initialized or not.)
You could use _ as the default initialization, but unless you use it in generic code:
class Holder[T] {
var held: T = _
}
then you're just obscuring what the value really will be set to. (Or you are announcing "I really don't care what goes here, it could be anything"--which could be useful.)
I just found the answer to the intialistion:
class Output
{
var point: Double = _
var solution: Array[Double] = Array(6)
}
Puh Scala has a lot of syntx to get used to :-)
Anyone have a solution for the lower_bound equivalent ?
It's hard to translate effectively, as you've left a lot of unknowns hidden behind pseudo code, but I'd advocate something along these lines:
// type alias
type Coeff = Seq[Seq[Double]]
// parameters passed to a case class become member fields
case class Output (point: Double, solution: Seq[Double])
val outputs = (0 to nmax) map { n =>
Output(generatePoint(n), generateSolution(n))
}
If you can flesh out your sample code a bit more fully, I'll be able to give a better translation.