xor rax, rax
:inc rax
jne @B
Originally Posted by Kuntz ![]() I know, but he said just to increment it, I assume because he thinks someone will run it and not realize it would probably take 200 years to execute. |
Originally Posted by metala ![]() The ultimate challenge! Increment a 64bit variable from 0 to maximum of the unsigned type. In GNU C, 64bit variable is declared unsigned long long. |
#include "stdafx.h"
#include <process.h>
#include <limits.h>
union CounterType {
unsigned long long Counter;
unsigned char CounterBytes[sizeof(unsigned long long)];
};
CounterType TheCounter = {0};
HANDLE thread[sizeof(unsigned long long)] = {0};
unsigned __stdcall IncremtntThreadProc(void* ptr)
{
const int index = (int)ptr;
while (TheCounter.CounterBytes[index] != UCHAR_MAX)
++TheCounter.CounterBytes[index];
return 0;
}
void StartThreads()
{
for (int i = 0; i < sizeof(thread)/sizeof(thread[0]); i++)
{
unsigned id;
thread[i] = (HANDLE)_beginthreadex(0, 0, IncremtntThreadProc, (void*)i, 0, &id);
}
}
void WaitForThreadsToFinish()
{
WaitForMultipleObjectsEx(sizeof(thread)/sizeof(thread[0]), thread, TRUE, INFINITE, TRUE);
for (int i = 0; i < sizeof(thread)/sizeof(thread[0]); i++)
CloseHandle(thread[i]);
}
int _tmain(int argc, _TCHAR* argv[])
{
CounterType* pCounter = &TheCounter;
StartThreads();
WaitForThreadsToFinish();
bool success = pCounter->Counter == _UI64_MAX;
return 0;
}
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
//
// Create a program that calculates the number of Sundays
// that were the 1st of a month in the 20th century.
//
namespace OCN
{
/*
* Interfaces...
*/
public interface IMonth
{
DayOfWeek FirstDayOfMonth { get; }
}
/*
* Concrete classes...
*/
public class Month : IMonth
{
private DateTime _begin;
public Month(DateTime begin) { _begin = begin; }
public DayOfWeek FirstDayOfMonth { get { return _begin.DayOfWeek; } }
}
public class TwentiethCentury
{
private DateTime _begin;
public TwentiethCentury() { _begin = new DateTime(1900, 1, 1); }
public TwentiethCentury(DateTime begin) { _begin = begin; }
public IEnumerator<IMonth> GetEnumerator()
{
DateTime d = _begin;
while (d.Year != 2000)
{
yield return new Month(d); // Very cool language feature
if (d.Month < 12)
d = new DateTime(d.Year, d.Month + 1, 1);
else
d = new DateTime(d.Year + 1, 1, 1);
}
}
}
/*
* Tests...
*/
[TestFixture]
public class TwentiethCenturyOfSundaysTests
{
[Test]
public void EnumerateEntireTwentiethCentury()
{
int count = 0;
TwentiethCentury century = new TwentiethCentury();
foreach (IMonth month in century)
++count;
Assert.IsTrue(count == 12 * 100);
}
[Test]
public void MumberOfSundaysThatWereThe1stOfAMonthInThe20thCentury()
{
int count = 0;
TwentiethCentury century = new TwentiethCentury();
foreach (IMonth month in century)
{
if (month.FirstDayOfMonth == DayOfWeek.Sunday)
++count;
}
Assert.IsTrue(count == 172);
}
}
}