Converting Values to Switch Statement Cases - c++

For a programming class, I have to convert a range of values to a switch statement without using if/else ifs. Here are the values that I need to convert to cases:
0 to 149 ............. $10.00
150 to 299 .........$15.00
300 to 449 .........$25.00
550 to 749..........$40.00
750 to 1199........$65.00
2000 and above.....$85.00
I am having difficulty finding a way to separate the values since they are so close in number (like 149 to 150).
I have used plenty of algorithms such as dividing the input by 2000, and then multiplying that by 10 to get a whole number, but they are too close to each other to create a new case for.

The first thing to do is to figure out your granularity. It looks like in your case you do not deal with increments less than 50.
Next, convert each range to a range of integers resulting from dividing the number by the increment (i.e. 50). In your case, this would mean
0, 1, 2 --> 10
3, 4, 5 --> 15
6, 7, 8 --> 25
... // And so on
This maps to a very straightforward switch statement.
Note: This also maps to an array of values, like this:
10, 10, 10, 15, 15, 15, 25, 25, 25, ...
Now you can get the result by doing array[n/50].

Related

Minesweeper algorithm in C++[KOI 2020]

I'm preparing KOI 2022, so, I'm solving KOI 2021, 2020 problems. KOI 2020 contest 1 1st period problem 5(See problem 5 in here)
I want to make <vector<vector<int>> minesweeper(vector<vector<int>> &v) function that works on 5*5 minesweeper.
argument
vector<vector<int>> &v
Numbers in minesweeper that converted to vector. -1 if it is blank.
e.g. {{0, 0, 1, -1, 1}, {-1, 3, 3, -1, 1}, {-1, -1, -1, -1, 0}, {2, 5, -1, 3, -1}, {-1, -1, -1, -1, -1}}
return value
A vector. Size is same with argument. Mine is 1, default is 0.
English translation of KOI 2020 contest 1 1st period problem 5
There is a 5*5 minesweeper puzzle.
There are 11 numbers, and the others are blank.
0
0
1
가
1
나
3
3
1
다
0
2
5
3
라
마
Where is the mine?
A. 가
B. 나
C. 다
D. 라
E. 마
How can I make minesweeper function? I want algorithm description, too.
There two some simple rules to solving Minesweeper:
If a field sees all it's mines then all blank fields don't have mines and can be uncovered.
If a field has as many blank fields as it is missing mines then they all contain mines.
Keep applying those rules over and over till nothing changes.
Now it gets complex because you have to look at combinations of fields. Instead of figuring out lots of special cases for 2, 3, 4 known fields I suggest going straight to a brute force algorithm:
For every blank field next to a know field:
create copies of the map with a mine present and not present
go back to the top to solve each map
if one of the maps results in any known field to not see enough mines then the other case must be the actual solution, apply it and go back to the start
If no progress was made then you have to guess. The above loop can give you probabilities for where mines are and if you know the number of mines total you have a probability for other blank fields. Pick one least likely to have a mine.

how to sort out values in a certain time period in R?

I´ve got a time series of temperature data with some wrong values, I want to sort out. The problem is, I want to sort out only the points in a certain period of time.
If I sort out the wrong points by their temperature value, ALL of the points of this temperature value are sorted out (through the wohle measuring period)
This is a very easy version of my code (in reality, there are many more values)
laketemperature <- c(15, 14, 14, 12, 11, 9, 9, 8, 6, 4, 15, 14, 3) #only want to sort out the last 14 and 15
out <- c(15, 14)
laketemperature_clean <- laketemperature [- out] # the 15 and 14s at the beginning are sorted out, too :(
I want to have the whole laketemperature-series in the end, only without the second 15.
I already tried with ifelse, but it didn´t work out.

Django Window annotation using combined with distinct clause

I have a Django model stored in a Postgres DB comprised of values of counts at irregular intervals:
WidgetCount
- Time
- Count
I'm trying to use a window function with Lag to give me a previous row's values as an annotation. My problem is when I try to combine it with some distinct date truncation the window function uses the source rows rather than the distinctly grouped ones.
For example if I have the following rows:
time count
2020-01-20 05:00 15
2020-01-20 06:00 20
2020-01-20 09:00 30
2020-01-21 06:00 35
2020-01-21 07:00 40
2020-01-22 04:00 50
2020-01-22 06:00 54
2020-01-22 09:00 58
And I want to return a queryset showing the first reading per day, I can use:
from django.db.models.functions import Trunc
WidgetCount.objects.distinct("date").annotate(date=Trunc("time", "day"))
Which gives me:
date count
01/01/20 15
01/01/21 35
01/01/22 50
I would like to add an annotation which gives me yesterday's value (so I can show the change per day).
date count yesterday_count
01/01/20 15
01/01/21 35 15
01/01/22 50 35
If I do:
from django.db.models.functions import Trunc, Lag
from django.db.models import Window
WidgetCount.objects.distinct("date").annotate(date=Trunc("time", "day"), yesterday_count=Window(expression=Lag("count")))
The second row return gives me 30 for yesterday_count - ie, its showing me the previous row before applying the distinct clause.
If I add a partiion clause like this:
WidgetCount.objects.distinct("date").annotate(date=Trunc("time", "day"), yesterday_count=Window(expression=Lag("count"), partition_by=F("date")))
Then yesterday_count is None for all rows.
I can do this calculation in Python if I need to but it's driving me a bit mad and I'd like to find out if what I'm trying to do is possible.
Thanks!
I think the main problem is that you're mixing operations that used in annotation generates a grouped query set such as sum with a operation that simples create a new field for each record in the given query set such as yesterday_count=Window(expression=Lag("count")).
So Ordering really matters here. So when you try:
WidgetCount.objects.distinct("date").annotate(date=Trunc("time", "day"), yesterday_count=Window(expression=Lag("count")))
The result queryset is simply the WidgetCount.objects.distinct("date") annotated, no grouping is perfomed.
I would suggest decoupling your operations so it becomes easier to understand what is happening, and notice you're iterating over the python object so don't need to make any new queries!
Note in using SUM operation as example because I am getting an unexpected error with the FirstValue operator. So I'm posting with Sum to demonstrate the idea which remains the same. The idea should be the same for first value just by changing acc_count=Sum("count") to first_count=FirstValue("count")
for truncDate_groups in Row.objects.annotate(trunc_date=Trunc('time','day')).values("trunc_date")\
.annotate(acc_count=Sum("count")).values("acc_count","trunc_date")\
.order_by('trunc_date')\
.annotate(y_count=Window(Lag("acc_count")))\
.values("trunc_date","acc_count","y_count"):
print(truncDate_groups)
OUTPUT:
{'trunc_date': datetime.datetime(2020, 1, 20, 0, 0, tzinfo=<UTC>), 'acc_count': 65, 'y_count': None}
{'trunc_date': datetime.datetime(2020, 1, 21, 0, 0, tzinfo=<UTC>), 'acc_count': 75, 'y_count': 162}
{'trunc_date': datetime.datetime(2020, 1, 22, 0, 0, tzinfo=<UTC>), 'acc_count': 162, 'y_count': 65}
It turns out FirstValue operator requires to use a Windows function so you can't nest FirtValue and then calculate Lag, so in this scenario I'm not exactly sure if you can do it. The question becomes how to access the First_Value column without nesting windows.
I haven't tested it out locally but I think you want to GROUP BY instead of using DISTINCT here.
WidgetCount.objects.values(
date=Trunc('time', 'day'),
).order_by('date').annotate(
date_count=Sum('count'), # Will trigger a GROUP BY date
).annotate(
yesterday_count=Window(Lag('date_count')),
)

Plot non present numbers with pandas

I have a large pandas Series, which contains unique numbers from 0 to 1,000,000. The series is not complete, but lacks some numbers in this range. I want to get a rough idea of what numbers are missing, so I'm thinking I should plot the data as a line with gaps showing the missing data.
How would I accomplish that? This does not work:
nums = pd.Series(myNumbers)
nums.plot()
The following provides a list of the missing numbers in Series nums. You can then plot them as needed. For your purposes adjust the max to 1E6.
max = 10 # highest number to look for in the Series
import pandas as pd
nums = pd.Series([1, 2, 3, 4, 5, 6, 9])
missing = [n for n in xrange(int(max + 1)) if n not in nums.values]
print missing
# prints: [0, 7, 8, 10]
I think there are two concerns with the plotting function you wrote. First, there are one million numbers. Second, the x-axis for the plot will be indexes in the series (start at 0, going sequentially); the y-axis will be numbers that you care about (nums.values in the code here). Therefore, you are looking for missing y-axis values.
I think it depends on what you mean by missing. If those are nans, then you can do something like
len(nums[nums.apply(numpy.isnan)])
if you are looking for numbers that are not present between 0-1M in the series, then do something like
a= set([i for i in xrange(int(1e6))])
b= set(nums.values)
print len(a-b) # or plot it as scatter.

How should roulette wheel selection be organized for non-sorted population in genetic algorithm?

My question is linked with this one:
Roulette-wheel selection in Genetic algorithm. Population needs to be sorted first?
If we don't sort the population what is the way of organizing roulette wheel selection for it?
Surely, we have to search in linear way now. Have you got any code snippets in C++ or Java for this case?
The population does not need to be sorted at all - the key to roulette selection is that the probability of a given individual being selected for reproduction is proportional to its fitness.
Say you have an unsorted population, with fitnesses as follows:
[12, 45, 76, 32, 54, 21]
To perform roulette selection, you need only pick a random number in the range 0 to 240 (the sum of the population's fitness). Then, starting at the first element in the list, subtract each individual's fitness until the random number is less than or equal to zero. So, in the above case, if we randomly pick 112, we do the following:
Step 1: 112 - 12 = 100. This is > 0, so continue.
Step 2: 100 - 45 = 55. This is > 0, so continue.
Step 3: 55 - 76 = -21. This is <= 0, so stop.
Therefore, we select individual #3 for reproduction. Note how this doesn't require the population to be sorted at all.
So, in pseudocode, it boils down to:
let s = sum of population fitness
let r = random number in range [0, s].
let i = 0.
while r > 0 do:
r = r - fitness of individual #i
increment i
select individual #i - 1 for reproduction.
Note that the - 1 in the final line is to counteract the increment i that's done within the last iteration of the loop (because even though we've found the individual we want, it increments regardless).