Math Is Fun Forum

  Discussion about math, puzzles, games and fun.   Useful symbols: ÷ × ½ √ ∞ ≠ ≤ ≥ ≈ ⇒ ± ∈ Δ θ ∴ ∑ ∫ • π ƒ -¹ ² ³ °

You are not logged in.

#1 2008-06-19 04:13:00

Ricky
Moderator
Registered: 2005-12-04
Posts: 3,791

Code snippets

Ever come across a little function that you found to be extremely useful in general?  If you do, post it here.

Displaying any vector:

template <class T>
ostream& operator << (ostream& out, const vector<T> &v) {
	out << "{";
	typename vector<T>::const_iterator itr;
	for (itr = v.begin(); itr != v.end()-1; itr++) {
		out << *itr << ",";
	}
	out << *itr << "}";
	return out;
}

Remember that this requires the item within the vector to overload <<.  That's why it can't be in any standard library, it's requirement is way to strong.  But useful when you have vectors of floats, ints, and short strings.


"In the real world, this would be a problem.  But in mathematics, we can just define a place where this problem doesn't exist.  So we'll go ahead and do that now..."

Offline

#2 2008-06-19 04:33:16

luca-deltodesco
Member
Registered: 2006-05-05
Posts: 1,470

Re: Code snippets

a question, wouldn't it be better for the argument to be a const reference so that the vector need not be copied in the function?


The Beginning Of All Things To End.
The End Of All Things To Come.

Offline

#3 2008-06-19 06:28:52

Ricky
Moderator
Registered: 2005-12-04
Posts: 3,791

Re: Code snippets

Huh, I could have sworn I did that.  Guess not. Thanks luca.


"In the real world, this would be a problem.  But in mathematics, we can just define a place where this problem doesn't exist.  So we'll go ahead and do that now..."

Offline

#4 2008-06-19 13:25:51

Ricky
Moderator
Registered: 2005-12-04
Posts: 3,791

Re: Code snippets

Here is one which is useful for any combinatorics programming.  Given an array of size n, and an integer 0 <= k < n!, this function permutes the elements:

template <typename T>
vector<T> permute(int k, vector<T> v) {
  T t;
  vector<T> result(v.size()-1, t);
  int i;
  for (i = v.size()-1; i > 0; i--) {
    int m = factorial(i);
    result[result.size() - i] = v[k / m];
    v.erase(v.begin() + k / m);
    k -= k / m * m; //note the flooring making this not just equal to k
  }
  result.push_back(v[0]); //append the very last element (as there is now only one in v) to the end

  return result;
}

Thus, the following for loop:

for (i = 0; i < factorial(v.size()); i++) {
  vector<T> newArray = permute(i, v);
}

Gives all possible arrangements of v.  I haven't used this code in about 2 years.. but I'm pretty sure it works.  I also just "templated" it, so there may be some small compile time errors.  I personally find it really cool because it uses "base n factorial", or at least that's what I call it.


"In the real world, this would be a problem.  But in mathematics, we can just define a place where this problem doesn't exist.  So we'll go ahead and do that now..."

Offline

#5 2008-06-24 14:16:36

mikau
Member
Registered: 2005-08-22
Posts: 1,504

Re: Code snippets

Here is a function i've used in pretty much every game program I've written.  PolarAngle, it calculates the directed angle from (from_x, from_y) to (to_x, to_y) in degrees.

//remember to include math.h
float polarAngle(float from_x, float from_y, float to_x, float to_y)
{

  float h, v, r;
 
  v = to_y - from_y;   
  h = to_x - from_x;    

  if ((h == 0) && (v < 0)) { return 270;}     // avoid division by zero
  if ((h == 0) && (v > 0)) { return 90; }     // avoid division by zero
  if ((h == 0) && (v == 0)) { return 0; }     // points overlap, no angle

  r = atan(v/h) * 180/M_PI;                // convert radians to degree's

  if (h < 0)
  r+= 180;

  return r;

}

note the function sometimes produces negative angles, so you might like to add
if (r < 0) r+= 360;  before the return statement.

Last edited by mikau (2008-06-24 14:19:40)


A logarithm is just a misspelled algorithm.

Offline

#6 2008-06-29 01:52:11

Laterally Speaking
Real Member
Registered: 2007-05-21
Posts: 356

Re: Code snippets

There's always the method for loading an ini file by calling the Win32 APIs, but that's not exactly short... and, depending on applications, it changes quite a bit. I will work on writing up a simplified and general version, and keep the (numerous) variables named in a self-explanatory way.

Here is a modified module from one of my projects; it has been reduced to the bare minimum, I believe.

Option Explicit

' api declarations for ini services
Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long
Declare Function GetFileAttributes Lib "kernel32" Alias "GetFileAttributesA" (ByVal lpFileName As String) As Long
Declare Function GetFileSize Lib "kernel32" (ByVal hFile As Long, lpFileSizeHigh As Long) As Long
Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpString As Any, ByVal lpFileName As String) As Long

Global inipath As String

Global Output As String

Global SearchedHeader As String
Global SearchedValue As String

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Function fullpath(ByVal dirpath As String, ByVal fileName As String) As String
'
' Purpose: Returns full path
'
' Inputs: dirpath and filename strings
'
' Outputs: string representing the full path including the filename
'
' Globals:
'
' Modifications:
'
' Comments:

If (Right$(dirpath, 1) = "") Then
fullpath = dirpath & fileName
Else
fullpath = dirpath & "" & fileName
End If

End Function

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Function getprivateprofile(ByVal section As String, ByVal KeyName As String, ByVal default As String) As String
'
' Purpose: Low level driver interface to obtain .ini info
'
' Inputs: section,keyname and default strings
'
' Outputs: String representing requested .ini item
'
' Globals:None
'
' Modifications:
'
' Comments:


Dim buffer As String
Dim i As Integer

buffer = String$(512, 0)

If (Len(KeyName) = 0) Then
i = GetPrivateProfileString(section, ByVal 0&, default, buffer, 512, inipath)
Else
i = GetPrivateProfileString(section, ByVal KeyName, default, buffer, 512, inipath)
End If
getprivateprofile = Left$(buffer, i)

End Function

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Sub OnStartup()
'
' Purpose: Loads data from ini file
'
' Inputs: None
'
' Outputs:None
'
' Globals:
'
' Modifications:
'
' Comments:

Dim dummy As String
Dim errmsg As String
Dim tempport As String
Dim tempsettings As String
Dim inierrormsg As String

'frmmain.txtinstructions

inipath = fullpath("C:\Documents and Settings\new user\My Documents", "Document") & ".txt"

SearchedHeader = "Names"
SearchedValue = "Name1"
dummy = (getprivateprofile(SearchedHeader, SearchedValue, ""))
Output(cycler) = dummy

Exit Sub

fferr:

MsgBox errmsg
'SetFail

End Sub

Sub OnExit()
'
' Purpose: Close comm ports and exit loops
'
' Inputs: None
'
' Outputs: None
'
' Globals:
'
' Modifications:
'
' Comments:


' update ini file
UPdateIni

End Sub

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Function WriteProfileStuff(KeyName As String, KeyValue As String, Optional AppName As String = "?", Optional IniLoc As String = "?") As Boolean
'
' Purpose: Low level ini file write function
'
' Inputs: keyname = ini entry definition, KeyValue = value to be written, AppName = ini file section name
'
' Outputs: flag = pass/fail
'
' Globals:
'
' Modifications:
'
' Comments:

Dim retval As Long
Dim ibuf As Long
Dim DefValue As String
Dim Results As String

On Error GoTo WriteprofileStuff_Error

' Inilialize varables
ibuf = 255                   'Set buffer length for API code

If IniLoc = "?" Then IniLoc = "C:\Documents and Settings\new user\My Documents\Document.txt"


retval = WritePrivateProfileString(AppName, KeyName, KeyValue, IniLoc)

' Return back to calling procedure with INI file infomation/
If retval = 1 Then
    WriteProfileStuff = True
Else
    WriteProfileStuff = False
End If

Exit Function

   ' Return back to calling procedure with Error measage
WriteprofileStuff_Error:
    MsgBox "System error attempting to write ini file data " & Err.Description, vbCritical
    WriteProfileStuff = False
End Function

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Function UPdateIni() As Boolean
'
' Purpose: Updates ini entries
'
' Inputs: None
'
' Outputs: None
'
' Globals:
'
' Modifications:
'
' Comments:

Dim retval As Boolean
Dim msg As String

retval = WriteProfileStuff(WriteValue, msg, WriteGroup)
If retval = False Then GoTo errr

UPdateIni = True

Exit Function

errr:

UPdateIni = False

End Function

Note that this was written in VB 5.0

Last edited by Laterally Speaking (2008-06-29 02:07:25)


"Knowledge is directly proportional to the amount of equipment ruined."
"This woman painted a picture of me; she was clearly a psychopath"

Offline

Board footer

Powered by FluxBB