percentage statistcal dilema - percentage

Let's say I have 12 values. For this case, let each value be a month in a year. Now write each month on its own separate piece of paper and place that on a table.
So we have 12 pieces of paper in a row along the surface of a table, each with a month of the year written on it.
Each month is assigned a certain percentage to be chosen. For example, January = 15%, February = 9%, December = 5%, etc.
Now, let's randomly pick a number between 1 and 100. We can use two 10-sided die, use a computer random number generator, or whatever you want.
Okay, let's look at the piece of paper that says "January". We now generate a random number between 1 and 100, and it rolls 43. Well, we move onto February now because we were looking for a 15 or lower. Looking at February we generate a new random number between 1 and 100 and roll an 87. Again, we were looking for a 9 or below to choose February, so we move onto March. So on and so forth.... UNTIL we get to July where the random number generated is a 3! Okay, July is picked and we STOP THE WHOLE PROCESS. July is the winner.
My question is: Does each month really have it's percentage value chance of being chosen? Because we stop processing the remaining months if one is picked, I think not. If we were to process each month regardless of one being picked, then yes, each month would have it's face percentage value chance of being picked.
If we must absolutely stop once a month is chosen (which we do have to), how can I make it so that each month has its true percentage chance of being picked?
I think one step in the process is to make sure that each month has a value that if all added together will equal 100, which I have done. But does this really ensure anything?
Code wise (c++), here's what it would look like:
// 15% January
// 9% February
// 9% March
// 8% April
// 8% May
// 8% June
// 8% July
// 8% August
// 8% September
// 8% October
// 6% November
// 5% December
int month = 0;
bool monthFound = false;
if (!monthFound && random(1, 100) <= 15)
{
monthFound = true;
month = 1;
}
if (!monthFound && random(1, 100) <= 9)
{
monthFound = true;
month = 2;
}
if (!monthFound && random(1, 100) <= 9)
{
monthFound = true;
month = 3;
}
if (!monthFound && random(1, 100) <= 8)
{
monthFound = true;
month = 4;
}
if (!monthFound && random(1, 100) <= 8)
{
monthFound = true;
month = 5;
}
if (!monthFound && random(1, 100) <= 8)
{
monthFound = true;
month = 6;
}
if (!monthFound && random(1, 100) <= 8)
{
monthFound = true;
month = 7;
}
if (!monthFound && random(1, 100) <= 8)
{
monthFound = true;
month = 8;
}
if (!monthFound && random(1, 100) <= 8)
{
monthFound = true;
month = 9;
}
if (!monthFound && random(1, 100) <= 8)
{
monthFound = true;
month = 10;
}
if (!monthFound && random(1, 100) <= 6)
{
monthFound = true;
month = 11;
}
if (!monthFound && random(1, 100) <= 5)
{
monthFound = true;
month = 12;
}
if (month)
printf("The month that was picked is: %d", month);
else
printf("No month was picked.");
Here's another way too:
int monthNum = 0;
std::vector<int> chance_;
std::vector<int> month_;
month_.push_back(1); chance_.push_back(15);
month_.push_back(2); chance_.push_back(9);
month_.push_back(3); chance_.push_back(9);
month_.push_back(4); chance_.push_back(8);
month_.push_back(5); chance_.push_back(8);
month_.push_back(6); chance_.push_back(8);
month_.push_back(7); chance_.push_back(8);
month_.push_back(8); chance_.push_back(8);
month_.push_back(9); chance_.push_back(8);
month_.push_back(10); chance_.push_back(8);
month_.push_back(11); chance_.push_back(6);
month_.push_back(12); chance_.push_back(5);
for (std::vector<std::string>::size_type z = 0; z < month_.size(); z++)
{
// Check the chance of the month being picked.
if (RANDOM(1, 100) <= chance_[z])
{
monthNum = month_[z];
break;
}
}
if (monthNum)
printf("The month that was picked is: %d", monthNum);
else
printf("No month was picked.");

You haven't tagged C++, and I use python, so this is Kris's suggestion as python:
import random
number = random.randint(1,100)
if number >= 95:
print ('December')
elif number >= 89:
print ('November')
elif number >= 81:
print ('October')
elif number >= 73:
print ('September')
elif number >= 65:
print ('August')
elif number >= 57:
print ('July')
elif number >= 49:
print ('June')
elif number >= 41:
print ('May')
elif number >= 33:
print ('April')
elif number >= 27:
print ('March')
elif number >= 16:
print ('Febuary')
elif number >= 1:
print ('January')

Related

Game Of Life ends quickly (Java)

I've created a basic version of the Game Of Life: each turn, the board is simulated by a 2D array of 1's and 0's, after which another class creates a drawing of it for me using the 2d array
I've read all the other questions here regarding this game, but no answer seems to work out for me....sorry if I'm beating a dead horse here.
I think I have a problem with my algorithm, thus maybe the board gets filled with the wrong amount of dead and alive cells and thus ends rather quickly (5-10 turns).
I've found an algorithm here to scan all the neighbors and even added a count = -1 in case it a cell in the grid scans itself as it's own neighbor, but I think I'm missing something here.
public static void repaint(board game, int size,int[][] alive, int[][] newGeneration)
{
int MIN_X = 0, MIN_Y = 0, MAX_X =9, MAX_Y =9, count;
for ( int i = 0; i < size; i++ )
{
for (int j = 0; j < size; j++) //here we check for each matrix cell's neighbors to see if they are alive or dead
{
count = 0;
if (alive[i][j] == 1)
count = -1;
int startPosX = (i - 1 < MIN_X) ? i : i - 1;
int startPosY = (j - 1 < MIN_Y) ? j : j - 1;
int endPosX = (i + 1 > MAX_X) ? i : i + 1;
int endPosY = (j + 1 > MAX_Y) ? j : j + 1;
for (int rowNum = startPosX; rowNum <= endPosX; rowNum++)
{
for (int colNum = startPosY; colNum <= endPosY; colNum++)
{
if (alive[rowNum][colNum] == 1)
count++;
}
}
if (alive[i][j] == 0 && count == 3) //conditions of the game of life
newGeneration[i][j] = 1; //filling the new array for the next life
if (alive[i][j] == 1 && count < 2)
newGeneration[i][j] = 0;
if (alive[i][j] == 1 && count >= 4)
newGeneration[i][j] = 0;
if (alive[i][j] == 1 && count == 3)
newGeneration[i][j] = 1;
}
}
game.setAlive(newGeneration); //we created a new matrix with the new lives, now we set it
SetupGUI(game,size); //re drawing the panel
}
}
What am I doing wrong? thanks for the help.

How to get day of year, week of year from a DateTime Dart object

I need to get day of year (day1 is 1rst of january), week of year, and month of year from a dart DateTime object.
I did not find any available library for this. Any idea ?
[ORIGINAL ANSWER - Please scroll below to the updated answer, which has an updated calculation]
Week of year:
/// Calculates week number from a date as per https://en.wikipedia.org/wiki/ISO_week_date#Calculation
int weekNumber(DateTime date) {
int dayOfYear = int.parse(DateFormat("D").format(date));
return ((dayOfYear - date.weekday + 10) / 7).floor();
}
The rest is available through DateFormat (part of the intl package).
[UPDATED ANSWER]
As pointed out by Henrik Kirk in a comment, the original answer did not include the necessary correction for certain dates. Here is a full implementation of the ISO week date calculation.
/// Calculates number of weeks for a given year as per https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year
int numOfWeeks(int year) {
DateTime dec28 = DateTime(year, 12, 28);
int dayOfDec28 = int.parse(DateFormat("D").format(dec28));
return ((dayOfDec28 - dec28.weekday + 10) / 7).floor();
}
/// Calculates week number from a date as per https://en.wikipedia.org/wiki/ISO_week_date#Calculation
int weekNumber(DateTime date) {
int dayOfYear = int.parse(DateFormat("D").format(date));
int woy = ((dayOfYear - date.weekday + 10) / 7).floor();
if (woy < 1) {
woy = numOfWeeks(date.year - 1);
} else if (woy > numOfWeeks(date.year)) {
woy = 1;
}
return woy;
}
Day of year
final date = someDate;
final diff = now.difference(new DateTime(date.year, 1, 1, 0, 0));
final diffInDays = diff.inDays;
Week of year
final date = someDate;
final startOfYear = new DateTime(date.year, 1, 1, 0, 0);
final firstMonday = startOfYear.weekday;
final daysInFirstWeek = 8 - firstMonday;
final diff = date.difference(startOfYear);
var weeks = ((diff.inDays - daysInFirstWeek) / 7).ceil();
// It might differ how you want to treat the first week
if(daysInFirstWeek > 3) {
weeks += 1;
}
Month of year
final monthOfYear = new DateTime.now().month;
Caution: That's not battle-tested code.
Try this really simple dart package, Jiffy. The code below will help
To get date day of year
// This will return the day of year from now
Jiffy().dayOfYear; // 295
// You can also pass in a dateTime object
Jiffy(DateTime(2019, 1, 3)).dayOfYear; // 3
To get week of year
Jiffy().week; // 43
// You can also pass in an Array or Map
Jiffy([2019, 1, 3]).week; // 1
To get month of year
Jiffy().month; // 10
Jiffy({
"year": 2019,
"month": 1,
"day": 3
}).month; // 1
Hope this answer helps
This is my implementation of ISO 8601 Week of Year in Dart:
int getWeekOfYear(DateTime date) {
final weekYearStartDate = getWeekYearStartDateForDate(date);
final dayDiff = date.difference(weekYearStartDate).inDays;
return ((dayDiff + 1) / 7).ceil();
}
DateTime getWeekYearStartDateForDate(DateTime date) {
int weekYear = getWeekYear(date);
return getWeekYearStartDate(weekYear);
}
int getWeekYear(DateTime date) {
assert(date.isUtc);
final weekYearStartDate = getWeekYearStartDate(date.year);
// in previous week year?
if(weekYearStartDate.isAfter(date)) {
return date.year - 1;
}
// in next week year?
final nextWeekYearStartDate = getWeekYearStartDate(date.year + 1);
if(isBeforeOrEqual(nextWeekYearStartDate, date)) {
return date.year + 1;
}
return date.year;
}
DateTime getWeekYearStartDate(int year) {
final firstDayOfYear = DateTime.utc(year, 1, 1);
final dayOfWeek = firstDayOfYear.weekday;
if(dayOfWeek <= DateTime.thursday) {
return addDays(firstDayOfYear, 1 - dayOfWeek);
}
else {
return addDays(firstDayOfYear, 8 - dayOfWeek);
}
}
Note that the "week year" is not always the calendar year, it could also be the one before or after:
void printWeekOfYear(DateTime date) {
print('week ${getWeekOfYear(date)} in year ${getWeekYear(date)}');
}
printWeekOfYear(DateTime.utc(2017, 1, 1));
// --> week 52 in year 2016
printWeekOfYear(DateTime.utc(2019, 12, 31));
// --> week 1 in year 2020
Number Week according to ISO 8601
int isoWeekNumber(DateTime date) {
int daysToAdd = DateTime.thursday - date.weekday;
DateTime thursdayDate = daysToAdd > 0 ? date.add(Duration(days: daysToAdd)) : date.subtract(Duration(days: daysToAdd.abs()));
int dayOfYearThursday = dayOfYear(thursdayDate);
return 1 + ((dayOfYearThursday - 1) / 7).floor();
}
int dayOfYear(DateTime date) {
return date.difference(DateTime(date.year, 1, 1)).inDays;
}
Dart SDK2.8.4 and later:
day of the year , with no packages:
void main(){
final now = new DateTime.now();
final todayInDays = now.difference(new DateTime(now.year,1,1,0,0)).inDays; //return 157
}
reference (official)> inDays, from Dart Official documentation
I wrote another solution based on your answers, it seem to work fine, but please feel free to give me feedback if you see a problem:
class DateUtils {
static int currentWeek() {
return weekOfYear(DateTime.now());
}
static int weekOfYear(DateTime date) {
DateTime monday = weekStart(date);
DateTime first = weekYearStartDate(monday.year);
int week = 1 + (monday.difference(first).inDays / 7).floor();
if (week == 53 && DateTime(monday.year, 12, 31).weekday < 4)
week = 1;
return week;
}
static DateTime weekStart(DateTime date) {
// This is ugly, but to avoid problems with daylight saving
DateTime monday = DateTime.utc(date.year, date.month, date.day);
monday = monday.subtract(Duration(days: monday.weekday - 1));
return monday;
}
static DateTime weekEnd(DateTime date) {
// This is ugly, but to avoid problems with daylight saving
// Set the last microsecond to really be the end of the week
DateTime sunday = DateTime.utc(date.year, date.month, date.day, 23, 59, 59, 999, 999999);
sunday = sunday.add(Duration(days: 7 - sunday.weekday));
return sunday;
}
static DateTime weekYearStartDate(int year) {
final firstDayOfYear = DateTime.utc(year, 1, 1);
final dayOfWeek = firstDayOfYear.weekday;
return firstDayOfYear.add(Duration(days: (dayOfWeek <= DateTime.thursday ? 1 : 8) - dayOfWeek));
}
}
getWeekOfYear(){
DateTime _kita=DateTime.now();
int d=DateTime.parse("${_kita.year}-01-01").millisecondsSinceEpoch;
int t= _kita.millisecondsSinceEpoch;
double daydiff= (t- d)/(1000 * (3600 * 24));
double week= daydiff/7;
return(week.ceil());
}
Tested and working you do not need any package
This calculation works for me.
int dayOfWeek({DateTime date}) {
if (date == null)
date = DateTime.now();
int w = ((dayOfYear(date) - date.weekday + 10) / 7).floor();
if (w == 0) {
w = getYearsWeekCount(date.year-1);
} else if (w == 53) {
DateTime lastDay = DateTime(date.year, DateTime.december, 31);
if (lastDay.weekday < DateTime.thursday) {
w = 1;
}
}
return w;
}
int getYearsWeekCount(int year) {
DateTime lastDay = DateTime(year, DateTime.december, 31);
int count = dayOfWeek(date: lastDay);
if (count == 1)
count = dayOfWeek(date: lastDay.subtract(Duration(days: 7)));
return count;
}
int dayOfYear(DateTime date) {
int total = 0;
for (int i = 1; i < date.month; i++) {
total += getDayOfMonth(date.year, i);
}
total+=date.day;
return total;
}
int getDayOfMonth(int year, int month) {
final List<int> days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (year % 4 == 0) days[DateTime.february]++;
return days[month];
}
the previous most voted solution is not working, if the year changes. for example has December 2020 a 53. week and if i change to January 2021 the previous solution computed 0 and not 53.
so i wrote a DateTime extension to cover year change.
int get weekNumber {
if (weekday > DateTime.thursday) {
int toSubstract = weekday - DateTime.thursday;
DateTime thursday = subtract(Duration(days: toSubstract));
if (thursday.year != year) {
return thursday.weekNumber;
}
}
int dayOfYear = int.parse(format('D'));
return ((dayOfYear - weekday + 10) / 7).floor();
}
The correct answer of #András Szepesházi but as DateTime extension
extension DateTimeExt on DateTime {
/// Calculates week number from a date as per https://en.wikipedia.org/wiki/ISO_week_date#Calculation
int get weekNumber {
int dayOfYear = int.parse(DateFormat("D").format(this));
int woy = ((dayOfYear - weekday + 10) / 7).floor();
if (woy < 1) {
woy = _numOfWeeks(year - 1);
} else if (woy > _numOfWeeks(year)) {
woy = 1;
}
return woy;
}
/// Calculates number of weeks for a given year as per https://en.wikipedia.org/wiki/ISO_week_date#Weeks_per_year
int _numOfWeeks(int year) {
DateTime dec28 = DateTime(year, 12, 28);
int dayOfDec28 = int.parse(DateFormat("D").format(dec28));
return ((dayOfDec28 - dec28.weekday + 10) / 7).floor();
}
}
static int getWeekNumber(DateTime datetime) {
var day1 = DateTime(datetime.year);
DateTime firstMonday;
switch (day1.weekday) {
case 1: // mon
firstMonday = day1;
break;
case 2: // tue
firstMonday = day1.add(const Duration(days: 6));
break;
case 3: // wed
firstMonday = day1.add(const Duration(days: 5));
break;
case 4: // thir
firstMonday = day1.add(const Duration(days: 4));
break;
case 5: // fri
firstMonday = day1.add(const Duration(days: 3));
break;
case 6: // sat
firstMonday = day1.add(const Duration(days: 2));
break;
case 7: // sun
firstMonday = day1.add(const Duration(days: 1));
break;
default:
firstMonday = day1;
}
Duration sinceStartOfYear = datetime.diff(firstMonday);
double weekNo = (sinceStartOfYear.inDays / 7);
var no = weekNo.floor();
return no + 1;
}
My full tested method.

How to add surcharge

I have this process, the user selects 2 dates. The system will then check if there are weekends. Weekends are:
Friday
Saturday
Sunday
Every time there are weekends, there would be additional charge + $10 PER DAY OF THE WEEKEND.
I have this code below, what I want is the process to add the surcharge.
http://jsfiddle.net/xtD5V/71/
function isWeekend(date1, date2) {
var d1 = new Date(date1),
d2 = new Date(date2),
isWeekend = false;
while (d1 < d2) {
var day = d1.getDay();
isWeekend = (day == 6) || (day == 0);
if (isWeekend) { return true; }
d1.setDate(d1.getDate() + 1);
}
return false;
}
alert(isWeekend(date1, date2));
You can opt to try this option.
Loop through all the dates and check for weekends like you did.
Store it in a variable
Option 1:
function noOfWeekends(date1, date2) {
//record number of weekends
var no_of_weekends = 0;
var d1 = new Date(date1),
d2 = new Date(date2),
isWeekend = false;
while (d1 < d2) {
var day = d1.getDay();
isWeekend = (day == 6) || (day == 0);
if (isWeekend) { no_of_weekends++; }
d1.setDate(d1.getDate() + 1);
}
return no_of_weekends;
}
//noOfWeekends now returns the number of weekends. You can do more stuff with it
alert(noOfWeekends(date1, date2) > 0);
alert("surcharge: " + noOfWeekends * 10);
*P/s: You can opt to write a formula to calculate the number of weekends without a loop since we can derive the information from your current day and number of days left. Do give it a try.

Determine position of number in a grid of numbers centered around 0 and increasing in spiral

I've got the following grid of numbers centered around 0 and increasing in spiral. I need an algorithm which would receive number in spiral and return x; y - numbers of moves how to get to that number from 0. For example for number 9 it would return -2; -1. For 4 it would be 1; 1.
25|26|... etc.
24| 9|10|11|12
23| 8| 1| 2|13
22| 7| 0| 3|14
21| 6| 5| 4|15
20|19|18|17|16
This spiral can be slightly changed if it would help the algorithm to be better.
Use whatever language you like. I would really appreciate mathematical explanation.
Thank you.
First we need to determine which cycle (distance from center) and sector (north, east, south or west) we are in. Then we can determine the exact position of the number.
The first numbers in each cycle is as follows: 1, 9, 25
This is a quadratic sequence: first(n) = (2n-1)^2 = 4n^2 - 4n + 1
The inverse of this is the cycle-number: cycle(i) = floor((sqrt(i) + 1) / 2)
The length of a cycle is: length(n) = first(n+1) - first(n) = 8n
The sector will then be:
sector(i) = floor(4 * (i - first(cycle(i))) / length(cycle(i)))
Finally, to get the position, we need to extrapolate from the position of the first number in the cycle and sector.
To put it all together:
def first(cycle):
x = 2 * cycle - 1
return x * x
def cycle(index):
return (isqrt(index) + 1)//2
def length(cycle):
return 8 * cycle
def sector(index):
c = cycle(index)
offset = index - first(c)
n = length(c)
return 4 * offset / n
def position(index):
c = cycle(index)
s = sector(index)
offset = index - first(c) - s * length(c) // 4
if s == 0: #north
return -c, -c + offset + 1
if s == 1: #east
return -c + offset + 1, c
if s == 2: #south
return c, c - offset - 1
# else, west
return c - offset - 1, -c
def isqrt(x):
"""Calculates the integer square root of a number"""
if x < 0:
raise ValueError('square root not defined for negative numbers')
n = int(x)
if n == 0:
return 0
a, b = divmod(n.bit_length(), 2)
x = 2**(a+b)
while True:
y = (x + n//x)//2
if y >= x:
return x
x = y
Example:
>>> position(9)
(-2, -1)
>>> position(4)
(1, 1)
>>> position(123456)
(-176, 80)
Do you mean something like this? I did not implement any algorithm and the code can be written better but it works - that's always a start :) Just change the threshold value for whatever you wish and you'll get the result.
static int threshold=14, x=0, y=0;
public static void main(String[] args) {
int yChange=1, xChange=1, count=0;
while( !end(count) ){
for (int i = 0; i < yChange; i++) {
if( end(count) )return;
count++;
y--;
}
yChange++;
for (int i = 0; i < xChange; i++) {
if( end(count) )return;
count++;
x++;
}
xChange++;
for (int i = 0; i < yChange; i++) {
if( end(count) )return;
count++;
y++;
}
yChange++;
for (int i = 0; i < xChange; i++) {
if( end(count) )return;
count++;
x--;
}
xChange++;
}
}
public static boolean end(int count){
if(count<threshold){
return false;
}else{
System.out.println("count: "+count+", x: "+x+", y: "+y);
return true;
}
}

How do I get browser timezone using Flex/AS3?

How do I get client browser's timezone in Flex/AS3?
Have a look on the following: http://thanksmister.com/2011/10/06/determining-local-timezone-in-actionscript-air-flex-as3/
It may help.
Can you use the timeZoneOffest of the Date object?
Honestly, I believe this just passes back information based on the user's OS settings. I wouldn't have expected a bBrowser to actually have a time zone.
I've been wanting the same thing, but I found nothing on the Internet. I was already using FlexDateUtils (blog post), but it only formats timezones as 'GMT -600'. Luckily, I can safely say that the users of my app will be in the United States, so I modified to 'DateUtils.buildTimeZoneDesignation(date:Date)' as follows. I hope this helps.
private static function buildTimeZoneDesignation( date:Date ):String {
if ( !date ) {
return "";
}
var timezoneOffsetHours:Number = date.getTimezoneOffset() / 60;
// custom timezone handlers (assumes major U.S. zones with daylight savings time dates as of 2011)
if (3 < timezoneOffsetHours && timezoneOffsetHours < 12)
{
var usDST:Boolean = false;
// the date of the Sunday before today unless today is Sunday
var sundayBeforeToday:Number = date.date - date.day;
if (2007 <= date.fullYear) {
// test for since-2007 extended daylight savings time
if (2 < date.month && date.month < 10) {
// daylight savings time (April through October)
usDST = true;
}
else if (date.month == 2) {
// DST starts second Sunday in March
usDST = (7 < sundayBeforeToday);
}
else if (date.month == 10) {
// DST ends first Sunday in November
usDST = (0 < sundayBeforeToday);
}
}
else {
// test for pre-2007 daylight savings time
if (3 < date.month && date.month < 9) {
// daylight savings time (May through September)
usDST = true;
}
else if (date.month == 3) {
// DST starts first Sunday in April
usDST = (0 < sundayBeforeToday);
}
else if (date.month == 9) {
// DST ends last Sunday in October
usDST = (sundayBeforeToday + 7 <= 31);
}
}
// return custom timezone strings for US timezones
switch (timezoneOffsetHours) {
case 4:
// Eastern or Atlantic
return usDST ? "EDT" : "AST";
case 5:
// Central or Eastern
return usDST ? "CDT" : "EST";
case 6:
// Mountain or Central
return usDST ? "MDT" : "CST";
case 7:
// Pacific or Mountain
return usDST ? "PDT" : "MST";
case 8:
// Alaska or Pacific
return usDST ? "AKDT" : "PST";
case 9:
// Hawaii or Alaska
return usDST ? "HADT" : "AKST";
case 10:
// Samoa or Hawaii
return usDST ? "SDT" : "HAST";
case 11:
if (!usDST)
// Samoa
return "SST";
break;
}
}
// else just generate a GMT string
var timeZoneAsString:String = "GMT ";
// timezoneoffset is the number that needs to be added to the local time to get to GMT, so
// a positive number would actually be GMT -X hours
if ( 0 < timezoneOffsetHours && timezoneOffsetHours < 10 ) {
timeZoneAsString += "-0" + ( timezoneOffsetHours ).toString();
} else if ( date.getTimezoneOffset() < 0 && timezoneOffsetHours > -10 ) {
timeZoneAsString += "0" + ( -1 * timezoneOffsetHours ).toString();
}
// add zeros to match standard format
timeZoneAsString += "00";
return timeZoneAsString;
}

Resources