<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Programming &amp; Software Q&amp;A | CollectiveSolver - Recent questions and answers</title>
<link>https://collectivesolver.com/qa</link>
<description>Powered by Question2Answer</description>
<item>
<title>Answered: How to remove extra whitespace from a string in Python</title>
<link>https://collectivesolver.com/100456/how-to-remove-extra-whitespace-from-a-string-in-python?show=100457#a100457</link>
<description>&lt;pre class=&quot;brush:python;&quot;&gt;def remove_extra_whitespace(text: str) -&amp;gt; str:
    &quot;&quot;&quot;
    Removes leading/trailing whitespace and collapses multiple
    consecutive whitespace characters into a single space.

    Python's split() without arguments:
    - Splits on any run of whitespace (spaces, tabs, newlines)
    - Automatically trims leading/trailing whitespace
    - Produces a list of clean words
    &quot;&quot;&quot;
    words = text.split()   # Efficient O(N) whitespace normalization
    return &quot; &quot;.join(words) # Reassemble with single spaces


def main() -&amp;gt; None:
    # Input string containing arbitrary whitespace, tabs, and padding
    s = &quot;   This   is   a   test   string   with         extra   spaces.   &quot;

    # Clean the string using standard string methods
    cleaned_string = remove_extra_whitespace(s)

    print(cleaned_string)


if __name__ == &quot;__main__&quot;:
    main()


&quot;&quot;&quot;
run:

This is a test string with extra spaces.

&quot;&quot;&quot;
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100456/how-to-remove-extra-whitespace-from-a-string-in-python?show=100457#a100457</guid>
<pubDate>Fri, 07 Aug 2026 16:59:57 +0000</pubDate>
</item>
<item>
<title>Answered: How to remove extra whitespace from a string in PHP</title>
<link>https://collectivesolver.com/100454/how-to-remove-extra-whitespace-from-a-string-in-php?show=100455#a100455</link>
<description>&lt;pre class=&quot;brush:php;&quot;&gt;/**
 * Normalizes a string by trimming leading and trailing whitespace
 * and collapsing multiple consecutive spaces into a single space.
 *
 * @param string $input
 * @return string
 */
function removeExtraWhitespace(string $input): string
{
    // Step 1: Use regular expression \s+ to match one or more contiguous whitespace characters
    // (spaces, tabs, newlines) and replace each group with a single space.
    $collapsed = preg_replace('/\s+/', ' ', $input);

    // Step 2: Strip any leading or trailing whitespace left at the boundaries of the string.
    return trim($collapsed);
}

// Input string containing variable padding and extra internal spaces
$s = &quot;   This   is   a   test   string   with         extra   spaces.   &quot;;

// Clean and normalize the string
$cleanedString = removeExtraWhitespace($s);

echo $cleanedString . PHP_EOL;


/*
run:

This is a test string with extra spaces.

*/&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100454/how-to-remove-extra-whitespace-from-a-string-in-php?show=100455#a100455</guid>
<pubDate>Fri, 07 Aug 2026 14:36:54 +0000</pubDate>
</item>
<item>
<title>Answered: How to remove extra whitespace from a string in C#</title>
<link>https://collectivesolver.com/100452/how-to-remove-extra-whitespace-from-a-string-in-c%23?show=100453#a100453</link>
<description>&lt;pre class=&quot;brush:csharp;&quot;&gt;using System;

class Program
{
    /// &amp;lt;summary&amp;gt;
    /// Removes leading and trailing whitespace and collapses multiple 
    /// consecutive whitespace characters into a single space.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&quot;input&quot;&amp;gt;The string to clean.&amp;lt;/param&amp;gt;
    /// &amp;lt;returns&amp;gt;A normalized string with single spaces between words.&amp;lt;/returns&amp;gt;
    static string RemoveExtraWhitespace(string input)
    {
        if (string.IsNullOrWhiteSpace(input)) {
            return string.Empty;
        }

        // Split the string by any whitespace characters, automatically removing 
        // empty entries created by consecutive spaces or surrounding padding.
        string[] words = input.Split(
            (char[])null!, 
            StringSplitOptions.RemoveEmptyEntries
        );

        // Join the individual words back together separated by a single space.
        return string.Join(&quot; &quot;, words);
    }

    static void Main()
    {
        // Input string containing arbitrary whitespace, tabs, and padding
        string s = &quot;   This   is   a   test   string   with         extra   spaces.   &quot;;

        // Clean the string using standard string methods
        string cleanedString = RemoveExtraWhitespace(s);

        Console.WriteLine(cleanedString);
    }
}


/*
run:

This is a test string with extra spaces.

*/&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100452/how-to-remove-extra-whitespace-from-a-string-in-c%23?show=100453#a100453</guid>
<pubDate>Fri, 07 Aug 2026 14:34:04 +0000</pubDate>
</item>
<item>
<title>Answered: How to remove extra whitespace from a string in VB.NET</title>
<link>https://collectivesolver.com/100450/how-to-remove-extra-whitespace-from-a-string-in-vb-net?show=100451#a100451</link>
<description>&lt;pre class=&quot;brush:vb;&quot;&gt;Imports System

Module Program

    ''' &amp;lt;summary&amp;gt;
    ''' Removes leading and trailing whitespace and collapses multiple 
    ''' consecutive whitespace characters into a single space.
    ''' &amp;lt;/summary&amp;gt;
    ''' &amp;lt;param name=&quot;input&quot;&amp;gt;The original string containing extra spaces.&amp;lt;/param&amp;gt;
    ''' &amp;lt;returns&amp;gt;A normalized string with single spaces between words.&amp;lt;/returns&amp;gt;
    Function RemoveExtraWhitespace(ByVal input As String) As String
        If String.IsNullOrWhiteSpace(input) Then
            Return String.Empty
        End If

        ' Split the string on whitespace characters, automatically stripping out empty entries
        ' created by consecutive spaces or leading/trailing padding.
        Dim words() As String = input.Split(
            CType(Nothing, Char()), 
            StringSplitOptions.RemoveEmptyEntries
        )

        ' Rejoin the extracted words using a single space separator.
        Return String.Join(&quot; &quot;, words)
    End Function

    Sub Main()
        ' Input string containing arbitrary whitespace, tabs, and padding
        Dim s As String = &quot;   This   is   a   test   string   with         extra   spaces.   &quot;

        ' Clean the string using standard framework methods
        Dim cleanedString As String = RemoveExtraWhitespace(s)

        Console.WriteLine(cleanedString)
    End Sub

End Module


' run:
'
' This is a test string with extra spaces.
'
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100450/how-to-remove-extra-whitespace-from-a-string-in-vb-net?show=100451#a100451</guid>
<pubDate>Fri, 07 Aug 2026 14:32:04 +0000</pubDate>
</item>
<item>
<title>Answered: How to remove extra whitespace from a string in Java</title>
<link>https://collectivesolver.com/100448/how-to-remove-extra-whitespace-from-a-string-in-java?show=100449#a100449</link>
<description>&lt;pre class=&quot;brush:java;&quot;&gt;import java.util.Objects;

public class Main {

    /**
     * Removes leading and trailing whitespace and collapses multiple 
     * consecutive whitespace characters into a single space.
     *
     * @param input The original string containing extra spaces.
     * @return A normalized string with single space separation.
     */
    public static String removeExtraWhitespace(String input) {
        if (input == null || input.isBlank()) {
            return &quot;&quot;;
        }

        // Step 1: strip() removes leading and trailing whitespace (Unicode-aware).
        // Step 2: replaceAll(&quot;\\s+&quot;, &quot; &quot;) matches any sequence of 1 or more 
        // whitespace characters and collapses them down to a single space.
        return input.strip().replaceAll(&quot;\\s+&quot;, &quot; &quot;);
    }

    public static void main(String[] args) {
        // Input string containing arbitrary whitespace, tabs, and padding
        String s = &quot;   This   is   a   test   string   with         extra   spaces.   &quot;;

        // Clean the string using standard String class methods
        String cleanedString = removeExtraWhitespace(s);

        System.out.println(cleanedString);
    }
}


/*
run:

This is a test string with extra spaces.

*/&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100448/how-to-remove-extra-whitespace-from-a-string-in-java?show=100449#a100449</guid>
<pubDate>Fri, 07 Aug 2026 14:29:03 +0000</pubDate>
</item>
<item>
<title>Answered: How to remove extra whitespace from a string in Pascal</title>
<link>https://collectivesolver.com/100446/how-to-remove-extra-whitespace-from-a-string-in-pascal?show=100447#a100447</link>
<description>&lt;pre class=&quot;brush:delphi;&quot;&gt;program NormalizeWhitespace;

{$mode objfpc}{$H+}

uses
  SysUtils; // CharInSet

{ ------------------------------------------------------------
  NormalizeWhitespace
  ------------------------------------------------------------
  Removes extra whitespace from a string:

  - Trim leading whitespace
  - Trim trailing whitespace
  - Collapse multiple internal whitespace into a single space

  The algorithm performs a single linear scan and writes into
  a result string. This avoids repeated allocations and keeps
  the logic simple and efficient.
  ------------------------------------------------------------ }
function NormalizeWhitespace(const S: string): string;
var
  i, j: Integer;
  InWS, Started: Boolean;
  Ch: Char;
begin
  SetLength(Result, Length(S));  { Preallocate for efficiency }
  j := 0;
  InWS := False;
  Started := False;

  for i := 1 to Length(S) do
  begin
    Ch := S[i];

    if CharInSet(Ch, [' ', #9, #10, #13]) then
    begin
      { Skip leading whitespace }
      if not Started then
        Continue;

      { Skip repeated whitespace }
      if InWS then
        Continue;

      { First whitespace after a word → write a single space }
      Inc(j);
      Result[j] := ' ';
      InWS := True;
    end
    else
    begin
      { Non-whitespace character }
      Inc(j);
      Result[j] := Ch;
      InWS := False;
      Started := True;
    end;
  end;

  { Remove trailing space if present }
  if (j &amp;gt; 0) and (Result[j] = ' ') then
    Dec(j);

  SetLength(Result, j);
end;

{ ------------------------------------------------------------
  Main program
  ------------------------------------------------------------ }
var
  S, Cleaned: string;
begin
  S := '   This   is   a   test   string   with         extra   spaces.   ';

  Cleaned := NormalizeWhitespace(S);

  WriteLn('Original: [', S, ']');
  WriteLn('Cleaned:  [', Cleaned, ']');
end.



(*
run:

Original: [   This   is   a   test   string   with         extra   spaces.   ]
Cleaned:  [This is a test string with extra spaces.]

*)
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100446/how-to-remove-extra-whitespace-from-a-string-in-pascal?show=100447#a100447</guid>
<pubDate>Fri, 07 Aug 2026 14:25:13 +0000</pubDate>
</item>
<item>
<title>Answered: How to remove extra whitespace from a string in C</title>
<link>https://collectivesolver.com/100443/how-to-remove-extra-whitespace-from-a-string-in-c?show=100444#a100444</link>
<description>&lt;pre class=&quot;brush:cpp;&quot;&gt;#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;ctype.h&amp;gt;
#include &amp;lt;string.h&amp;gt;

/* ------------------------------------------------------------
   normalize_whitespace
   ------------------------------------------------------------
   Removes extra whitespace from a string:

   - Trim leading whitespace
   - Trim trailing whitespace
   - Collapse multiple internal whitespace into a single space

   The algorithm performs a single linear scan and writes into
   an output buffer provided by the caller.
   ------------------------------------------------------------ */
void normalize_whitespace(const char *input, char *output) {

    int in_ws = 0;      /* Tracks whether we are inside a whitespace run */
    int started = 0;    /* Tracks whether we've copied the first non-space */
    size_t j = 0;       /* Write index for output */

    for (size_t i = 0; input[i] != '\0'; i++) {

        if (isspace((unsigned char)input[i])) {

            /* Skip leading whitespace */
            if (!started) {
                continue;
            }

            /* If already in a whitespace run, skip extra whitespace */
            if (in_ws) {
                continue;
            }

            /* First whitespace after a word → write a single space */
            output[j++] = ' ';
            in_ws = 1;

        } else {
            /* Non-whitespace character */
            output[j++] = input[i];
            in_ws = 0;
            started = 1;
        }
    }

    /* Remove trailing space if present */
    if (j &amp;gt; 0 &amp;amp;&amp;amp; output[j - 1] == ' ') {
        j--;
    }

    output[j] = '\0';
}

int main(void) {

    const char *s = &quot;   This   is   a   test   string   with         extra   spaces.   &quot;;
    char cleaned[256] = &quot;&quot;;  /* Output buffer */

    normalize_whitespace(s, cleaned);

    printf(&quot;Original: [%s]\n&quot;, s);
    printf(&quot;Cleaned:  [%s]\n&quot;, cleaned);

    return 0;
}



/*
run:

Original: [   This   is   a   test   string   with         extra   spaces.   ]
Cleaned:  [This is a test string with extra spaces.]

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100443/how-to-remove-extra-whitespace-from-a-string-in-c?show=100444#a100444</guid>
<pubDate>Fri, 07 Aug 2026 09:55:46 +0000</pubDate>
</item>
<item>
<title>Answered: How to remove extra whitespace from a string in C++</title>
<link>https://collectivesolver.com/100440/how-to-remove-extra-whitespace-from-a-string-in-c?show=100442#a100442</link>
<description>&lt;pre class=&quot;brush:cpp;&quot;&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;string&amp;gt;
#include &amp;lt;algorithm&amp;gt;

// Function to normalize whitespace: collapses consecutive spaces and trims edges
std::string removeExtraWhitespace(std::string str) {
    // Step 1: Normalize all whitespace characters (tabs, newlines, etc.) to standard spaces
    std::transform(str.begin(), str.end(), str.begin(), [](unsigned char ch) {
        return std::isspace(ch) ? ' ' : ch;
    });

    // Step 2: Collapse consecutive spaces into a single space in-place using std::unique
    // std::unique moves duplicate adjacent elements to the end and returns an iterator 
    // to the new boundary
    auto new_end = std::unique(str.begin(), str.end(), [](char lhs, char rhs) {
        return lhs == ' ' &amp;amp;&amp;amp; rhs == ' ';
    });

    // Erase the leftover duplicate elements beyond the new boundary
    str.erase(new_end, str.end());

    // Step 3: Trim leading space if present
    if (!str.empty() &amp;amp;&amp;amp; str.front() == ' ') {
        str.erase(str.begin());
    }

    // Step 4: Trim trailing space if present
    if (!str.empty() &amp;amp;&amp;amp; str.back() == ' ') {
        str.pop_back();
    }

    return str;
}

int main() {
    std::string s = &quot;   This   is   a   test   string   with         extra   spaces.   &quot;;

    // Clean the string
    std::string cleaned = removeExtraWhitespace(s);

    std::cout &amp;lt;&amp;lt; cleaned &amp;lt;&amp;lt; std::endl;
}


/*
run:

This is a test string with extra spaces.

*/&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100440/how-to-remove-extra-whitespace-from-a-string-in-c?show=100442#a100442</guid>
<pubDate>Fri, 07 Aug 2026 09:42:16 +0000</pubDate>
</item>
<item>
<title>Answered: How to calculate the distance between two latitude-longitude points in Swift</title>
<link>https://collectivesolver.com/100438/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-swift?show=100439#a100439</link>
<description>&lt;pre class=&quot;brush:jscript;&quot;&gt;import Foundation

// ------------------------------------------------------------
// Convert degrees to radians
// ------------------------------------------------------------
func degToRad(_ deg: Double) -&amp;gt; Double {
    return deg * Double.pi / 180.0
}

// ------------------------------------------------------------
// Compute the great-circle distance between two points on Earth
// using the Haversine formula.
// lat1, lon1, lat2, lon2 are in degrees.
// The result is returned in kilometers.
// ------------------------------------------------------------
func haversine(lat1: Double, lon1: Double,
               lat2: Double, lon2: Double) -&amp;gt; Double {

    // Earth's mean radius in kilometers
    let R: Double = 6371.0

    // Convert all angles to radians
    let rlat1 = degToRad(lat1)
    let rlon1 = degToRad(lon1)
    let rlat2 = degToRad(lat2)
    let rlon2 = degToRad(lon2)

    // Differences
    let dlat = rlat2 - rlat1
    let dlon = rlon2 - rlon1

    // Haversine formula
    // a is the Haversine of the central angle between the two points.
    let a =
        pow(sin(dlat / 2), 2) +
        cos(rlat1) * cos(rlat2) *
        pow(sin(dlon / 2), 2)

    // Central angle
    // c is the central angle between the two points on the Earth’s surface.
    let c = 2 * asin(sqrt(a))

    // Final distance
    return R * c
}

// ------------------------------------------------------------
// Main 
// ------------------------------------------------------------

// Example coordinates:
// Austin, Texas
let lat1: Double = 30.2672
let lon1: Double = -97.7431

// Houston, Texas
let lat2: Double = 29.7604
let lon2: Double = -95.3698

let distanceKm: Double = haversine(lat1: lat1, lon1: lon1,
                                   lat2: lat2, lon2: lon2)

// Convert kilometers to miles
let distanceMiles: Double = distanceKm * 0.621371

print(String(format: &quot;Distance: %.3f km&quot;, distanceKm))
print(String(format: &quot;Distance: %.3f miles&quot;, distanceMiles))



/*
run:

Distance: 235.352 km
Distance: 146.241 miles

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100438/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-swift?show=100439#a100439</guid>
<pubDate>Fri, 07 Aug 2026 08:50:23 +0000</pubDate>
</item>
<item>
<title>Answered: How to calculate the distance between two latitude-longitude points in Kotlin</title>
<link>https://collectivesolver.com/100436/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-kotlin?show=100437#a100437</link>
<description>&lt;pre class=&quot;brush:jscript;&quot;&gt;import kotlin.math.*

// ------------------------------------------------------------
// Convert degrees to radians
// ------------------------------------------------------------
fun degToRad(deg: Double): Double {
    return deg * PI / 180.0
}

// ------------------------------------------------------------
// Compute the great-circle distance between two points on Earth
// using the Haversine formula.
// lat1, lon1, lat2, lon2 are in degrees.
// The result is returned in kilometers.
// ------------------------------------------------------------
fun haversine(lat1: Double, lon1: Double,
              lat2: Double, lon2: Double): Double {

    // Earth's mean radius in kilometers
    val R: Double = 6371.0

    // Convert all angles to radians
    val rlat1: Double = degToRad(lat1)
    val rlon1: Double = degToRad(lon1)
    val rlat2: Double = degToRad(lat2)
    val rlon2: Double = degToRad(lon2)

    // Differences
    val dlat: Double = rlat2 - rlat1
    val dlon: Double = rlon2 - rlon1

    // Haversine formula
    // a is the Haversine of the central angle between the two points.
    val a: Double =
        sin(dlat / 2).pow(2) +
        cos(rlat1) * cos(rlat2) *
        sin(dlon / 2).pow(2)

    // Central angle
    // c is the central angle between the two points on the Earth’s surface.
    val c: Double = 2 * asin(sqrt(a))

    // Final distance
    return R * c
}

fun main() {

    // Example coordinates:
    // Austin, Texas
    val lat1: Double = 30.2672
    val lon1: Double = -97.7431

    // Houston, Texas
    val lat2: Double = 29.7604
    val lon2: Double = -95.3698

    val distanceKm: Double = haversine(lat1, lon1, lat2, lon2)

    // Convert kilometers to miles
    val distanceMiles: Double = distanceKm * 0.621371

    println(&quot;Distance: %.3f km&quot;.format(distanceKm))
    println(&quot;Distance: %.3f miles&quot;.format(distanceMiles))
}


/*
run:

Distance: 235.352 km
Distance: 146.241 miles

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100436/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-kotlin?show=100437#a100437</guid>
<pubDate>Fri, 07 Aug 2026 08:47:09 +0000</pubDate>
</item>
<item>
<title>Answered: How to calculate the distance between two latitude-longitude points in Scala</title>
<link>https://collectivesolver.com/100434/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-scala?show=100435#a100435</link>
<description>&lt;pre class=&quot;brush:scala;&quot;&gt;object HaversineDistance {

  // ------------------------------------------------------------
  // Convert degrees to radians
  // ------------------------------------------------------------
  def degToRad(deg: Double): Double =
    deg * math.Pi / 180.0

  // ------------------------------------------------------------
  // Compute the great-circle distance between two points on Earth
  // using the Haversine formula.
  // lat1, lon1, lat2, lon2 are in degrees.
  // The result is returned in kilometers.
  // ------------------------------------------------------------
  def haversine(lat1: Double, lon1: Double,
                lat2: Double, lon2: Double): Double = {

    // Earth's mean radius in kilometers
    val R: Double = 6371.0

    // Convert all angles to radians
    val rlat1 = degToRad(lat1)
    val rlon1 = degToRad(lon1)
    val rlat2 = degToRad(lat2)
    val rlon2 = degToRad(lon2)

    // Differences
    val dlat = rlat2 - rlat1
    val dlon = rlon2 - rlon1

    // Haversine formula
    // a is the Haversine of the central angle between the two points.
    val a =
      math.sin(dlat / 2) * math.sin(dlat / 2) +
      math.cos(rlat1) * math.cos(rlat2) *
      math.sin(dlon / 2) * math.sin(dlon / 2)

    // Central angle
    // c is the central angle between the two points on the Earth’s surface.
    val c = 2 * math.asin(math.sqrt(a))

    // Final distance
    R * c
  }

  def main(args: Array[String]): Unit = {

    // Example coordinates:
    // Austin, Texas
    val lat1: Double = 30.2672
    val lon1: Double = -97.7431

    // Houston, Texas
    val lat2: Double = 29.7604
    val lon2: Double = -95.3698

    val distanceKm: Double = haversine(lat1, lon1, lat2, lon2)

    // Convert kilometers to miles
    val distanceMiles: Double = distanceKm * 0.621371

    println(f&quot;Distance: $distanceKm%.3f km&quot;)
    println(f&quot;Distance: $distanceMiles%.3f miles&quot;)
  }
}


/*
run:

Distance: 235.352 km
Distance: 146.241 miles

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100434/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-scala?show=100435#a100435</guid>
<pubDate>Fri, 07 Aug 2026 08:38:52 +0000</pubDate>
</item>
<item>
<title>Answered: How to calculate the distance between two latitude-longitude points in Ruby</title>
<link>https://collectivesolver.com/100432/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-ruby?show=100433#a100433</link>
<description>&lt;pre class=&quot;brush:ruby;&quot;&gt;# ------------------------------------------------------------
# Convert degrees to radians
# ------------------------------------------------------------
def deg_to_rad(deg)
  deg * Math::PI / 180.0
end

# ------------------------------------------------------------
# Compute the great-circle distance between two points on Earth
# using the Haversine formula.
# lat1, lon1, lat2, lon2 are in degrees.
# The result is returned in kilometers.
# ------------------------------------------------------------
def haversine(lat1, lon1, lat2, lon2)

  # Earth's mean radius in kilometers
  r = 6371.0

  # Convert all angles to radians
  rlat1 = deg_to_rad(lat1)
  rlon1 = deg_to_rad(lon1)
  rlat2 = deg_to_rad(lat2)
  rlon2 = deg_to_rad(lon2)

  # Differences
  dlat = rlat2 - rlat1
  dlon = rlon2 - rlon1

  # Haversine formula
  # a is the Haversine of the central angle between the two points.
  a =
    Math.sin(dlat / 2)**2 +
    Math.cos(rlat1) * Math.cos(rlat2) *
    Math.sin(dlon / 2)**2

  # Central angle
  # c is the central angle between the two points on the Earth’s surface.
  c = 2 * Math.asin(Math.sqrt(a))

  # Final distance
  r * c
end

# ------------------------------------------------------------
# Main 
# ------------------------------------------------------------

# Example coordinates:
# Austin, Texas
lat1 = 30.2672
lon1 = -97.7431

# Houston, Texas
lat2 = 29.7604
lon2 = -95.3698

distance_km = haversine(lat1, lon1, lat2, lon2)

# Convert kilometers to miles
distance_miles = distance_km * 0.621371

puts &quot;Distance: #{format('%.3f', distance_km)} km&quot;
puts &quot;Distance: #{format('%.3f', distance_miles)} miles&quot;



=begin
run:

Distance: 235.352 km
Distance: 146.241 miles

=end
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100432/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-ruby?show=100433#a100433</guid>
<pubDate>Fri, 07 Aug 2026 08:36:08 +0000</pubDate>
</item>
<item>
<title>Answered: How to calculate the distance between two latitude-longitude points in Rust</title>
<link>https://collectivesolver.com/100430/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-rust?show=100431#a100431</link>
<description>&lt;pre class=&quot;brush:cpp;&quot;&gt;use std::f64::consts::PI;

// ------------------------------------------------------------
// Convert degrees to radians
// ------------------------------------------------------------
fn deg_to_rad(deg: f64) -&amp;gt; f64 {
    deg * PI / 180.0
}

// ------------------------------------------------------------
// Compute the great-circle distance between two points on Earth
// using the Haversine formula.
// lat1, lon1, lat2, lon2 are in degrees.
// The result is returned in kilometers.
// ------------------------------------------------------------
fn haversine(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -&amp;gt; f64 {

    // Earth's mean radius in kilometers
    const R: f64 = 6371.0;

    // Convert all angles to radians
    let rlat1 = deg_to_rad(lat1);
    let rlon1 = deg_to_rad(lon1);
    let rlat2 = deg_to_rad(lat2);
    let rlon2 = deg_to_rad(lon2);

    // Differences
    let dlat = rlat2 - rlat1;
    let dlon = rlon2 - rlon1;

    // Haversine formula
    // a is the Haversine of the central angle between the two points.
    let a =
        (f64::sin(dlat / 2.0)).powi(2) +
        f64::cos(rlat1) * f64::cos(rlat2) *
        (f64::sin(dlon / 2.0)).powi(2);

    // Central angle
    // c is the central angle between the two points on the Earth’s surface.
    let c = 2.0 * f64::asin(f64::sqrt(a));

    // Final distance
    R * c
}

fn main() {

    // Example coordinates:
    // Austin, Texas
    let lat1: f64 = 30.2672;
    let lon1: f64 = -97.7431;

    // Houston, Texas
    let lat2: f64 = 29.7604;
    let lon2: f64 = -95.3698;

    let distance_km: f64 = haversine(lat1, lon1, lat2, lon2);

    // Convert kilometers to miles
    let distance_miles: f64 = distance_km * 0.621371;

    println!(&quot;Distance: {:.3} km&quot;, distance_km);
    println!(&quot;Distance: {:.3} miles&quot;, distance_miles);
}



/*
run:

Distance: 235.352 km
Distance: 146.241 miles

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100430/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-rust?show=100431#a100431</guid>
<pubDate>Fri, 07 Aug 2026 08:33:16 +0000</pubDate>
</item>
<item>
<title>Answered: How to calculate the distance between two latitude-longitude points in Go</title>
<link>https://collectivesolver.com/100428/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-go?show=100429#a100429</link>
<description>&lt;pre class=&quot;brush:cpp;&quot;&gt;package main

import (
    &quot;fmt&quot;
    &quot;math&quot;
)

// ------------------------------------------------------------
// Convert degrees to radians
// ------------------------------------------------------------
func degToRad(deg float64) float64 {
    return deg * math.Pi / 180.0
}

// ------------------------------------------------------------
// Compute the great-circle distance between two points on Earth
// using the Haversine formula.
// lat1, lon1, lat2, lon2 are in degrees.
// The result is returned in kilometers.
// ------------------------------------------------------------
func haversine(lat1, lon1, lat2, lon2 float64) float64 {

    // Earth's mean radius in kilometers
    const R float64 = 6371.0

    // Convert all angles to radians
    rlat1 := degToRad(lat1)
    rlon1 := degToRad(lon1)
    rlat2 := degToRad(lat2)
    rlon2 := degToRad(lon2)

    // Differences
    dlat := rlat2 - rlat1
    dlon := rlon2 - rlon1

    // Haversine formula
    // a is the Haversine of the central angle between the two points.
    a := math.Sin(dlat/2)*math.Sin(dlat/2) +
        math.Cos(rlat1)*math.Cos(rlat2)*math.Sin(dlon/2)*math.Sin(dlon/2)

    // Central angle
    // c is the central angle between the two points on the Earth’s surface.
    c := 2 * math.Asin(math.Sqrt(a))

    // Final distance
    return R * c
}

func main() {

    // Example coordinates:
    // Austin, Texas
    lat1 := 30.2672
    lon1 := -97.7431

    // Houston, Texas
    lat2 := 29.7604
    lon2 := -95.3698

    distanceKm := haversine(lat1, lon1, lat2, lon2)

    // Convert kilometers to miles
    distanceMiles := distanceKm * 0.621371

    fmt.Printf(&quot;Distance: %.3f km\n&quot;, distanceKm)
    fmt.Printf(&quot;Distance: %.3f miles\n&quot;, distanceMiles)
}



/*
run:

Distance: 235.352 km
Distance: 146.241 miles

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100428/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-go?show=100429#a100429</guid>
<pubDate>Fri, 07 Aug 2026 08:30:17 +0000</pubDate>
</item>
<item>
<title>Answered: How to calculate the distance between two latitude-longitude points in TypeScript</title>
<link>https://collectivesolver.com/100426/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-typescript?show=100427#a100427</link>
<description>&lt;pre class=&quot;brush:ts;&quot;&gt;// ------------------------------------------------------------
// Convert degrees to radians
// ------------------------------------------------------------
function degToRad(deg: number): number {
    return deg * Math.PI / 180.0;
}

// ------------------------------------------------------------
// Compute the great-circle distance between two points on Earth
// using the Haversine formula.
// lat1, lon1, lat2, lon2 are in degrees.
// The result is returned in kilometers.
// ------------------------------------------------------------
function haversine(lat1: number, lon1: number,
                   lat2: number, lon2: number): number {

    // Earth's mean radius in kilometers
    const R: number = 6371.0;

    // Convert all angles to radians
    const rlat1: number = degToRad(lat1);
    const rlon1: number = degToRad(lon1);
    const rlat2: number = degToRad(lat2);
    const rlon2: number = degToRad(lon2);

    // Differences
    const dlat: number = rlat2 - rlat1;
    const dlon: number = rlon2 - rlon1;

    // Haversine formula
    //  a is the Haversine of the central angle between the two points.
    const a: number =
        Math.sin(dlat / 2) ** 2 +
        Math.cos(rlat1) * Math.cos(rlat2) *
        Math.sin(dlon / 2) ** 2;

    // Central angle
    // c is the central angle between the two points on the Earth’s surface.
    const c: number = 2 * Math.asin(Math.sqrt(a));

    // Final distance
    return R * c;
}

// ------------------------------------------------------------
// Main 
// ------------------------------------------------------------

// Example coordinates:
// Austin, Texas
const lat1: number = 30.2672;
const lon1: number = -97.7431;

// Houston, Texas
const lat2: number = 29.7604;
const lon2: number = -95.3698;

// Calculate distances
const distanceKm: number = haversine(lat1, lon1, lat2, lon2);

// Convert kilometers to miles
const distanceMiles: number = distanceKm * 0.621371;

// Output results
console.log(`Distance: ${distanceKm.toFixed(3)} km`);
console.log(`Distance: ${distanceMiles.toFixed(3)} miles`);



/*
run:

Distance: 235.352 km
Distance: 146.241 miles

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100426/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-typescript?show=100427#a100427</guid>
<pubDate>Fri, 07 Aug 2026 08:27:15 +0000</pubDate>
</item>
<item>
<title>Answered: How to calculate the distance between two latitude-longitude points in JavaScript</title>
<link>https://collectivesolver.com/100424/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-javascript?show=100425#a100425</link>
<description>&lt;pre class=&quot;brush:jscript;&quot;&gt;// ------------------------------------------------------------
// Convert degrees to radians
// ------------------------------------------------------------
function degToRad(deg) {
    return deg * Math.PI / 180.0;
}

// ------------------------------------------------------------
// Compute the great-circle distance between two points on Earth
// using the Haversine formula.
// lat1, lon1, lat2, lon2 are in degrees.
// The result is returned in kilometers.
// ------------------------------------------------------------
function haversine(lat1, lon1, lat2, lon2) {

    // Earth's mean radius in kilometers
    const R = 6371.0;

    // Convert all angles to radians
    const rlat1 = degToRad(lat1);
    const rlon1 = degToRad(lon1);
    const rlat2 = degToRad(lat2);
    const rlon2 = degToRad(lon2);

    // Differences
    const dlat = rlat2 - rlat1;
    const dlon = rlon2 - rlon1;

    // Haversine formula
    // a is the Haversine of the central angle between the two points.
    const a =
        Math.sin(dlat / 2) ** 2 +
        Math.cos(rlat1) * Math.cos(rlat2) *
        Math.sin(dlon / 2) ** 2;

    // c is the central angle between the two points on the Earth’s surface.
    const c = 2 * Math.asin(Math.sqrt(a));

    // Final distance
    return R * c;
}

// ------------------------------------------------------------
// Main 
// ------------------------------------------------------------

// Example coordinates:
// Austin, Texas
const lat1 = 30.2672;
const lon1 = -97.7431;

// Houston, Texas
const lat2 = 29.7604;
const lon2 = -95.3698;

const distanceKm = haversine(lat1, lon1, lat2, lon2);

// Convert kilometers to miles
const distanceMiles = distanceKm * 0.621371;

console.log(`Distance: ${distanceKm.toFixed(3)} km`);
console.log(`Distance: ${distanceMiles.toFixed(3)} miles`);



/*
run:

Distance: 235.352 km
Distance: 146.241 miles

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100424/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-javascript?show=100425#a100425</guid>
<pubDate>Fri, 07 Aug 2026 08:22:26 +0000</pubDate>
</item>
<item>
<title>Answered: How to calculate the distance between two latitude-longitude points in Python</title>
<link>https://collectivesolver.com/100422/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-python?show=100423#a100423</link>
<description>&lt;pre class=&quot;brush:python;&quot;&gt;import math

# ------------------------------------------------------------
# Convert degrees to radians
# ------------------------------------------------------------
def deg_to_rad(deg: float) -&amp;gt; float:
    return deg * math.pi / 180.0

# ------------------------------------------------------------
# Compute the great-circle distance between two points on Earth
# using the Haversine formula.
# lat1, lon1, lat2, lon2 are in degrees.
# The result is returned in kilometers.
# ------------------------------------------------------------
def haversine(lat1: float, lon1: float,
              lat2: float, lon2: float) -&amp;gt; float:

    # Earth's mean radius in kilometers
    R = 6371.0

    # Convert all angles to radians
    rlat1 = deg_to_rad(lat1)
    rlon1 = deg_to_rad(lon1)
    rlat2 = deg_to_rad(lat2)
    rlon2 = deg_to_rad(lon2)

    # Differences
    dlat = rlat2 - rlat1
    dlon = rlon2 - rlon1

    # Haversine formula
    # a is the Haversine of the central angle between the two points.
    a = math.sin(dlat / 2)**2 + \
        math.cos(rlat1) * math.cos(rlat2) * math.sin(dlon / 2)**2

    # c is the central angle between the two points on the Earth’s surface.
    c = 2 * math.asin(math.sqrt(a))

    # Final distance
    return R * c

# ------------------------------------------------------------
# Main 
# ------------------------------------------------------------
if __name__ == &quot;__main__&quot;:

    # Example coordinates:
    # Austin, Texas
    lat1 = 30.2672
    lon1 = -97.7431

    # Houston, Texas
    lat2 = 29.7604
    lon2 = -95.3698

    distance_km = haversine(lat1, lon1, lat2, lon2)

    # Convert kilometers to miles
    distance_miles = distance_km * 0.621371

    print(f&quot;Distance: {distance_km:.3f} km&quot;)
    print(f&quot;Distance: {distance_miles:.3f} miles&quot;)



&quot;&quot;&quot;
run:

Distance: 235.352 km
Distance: 146.241 miles

&quot;&quot;&quot;
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100422/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-python?show=100423#a100423</guid>
<pubDate>Fri, 07 Aug 2026 08:14:54 +0000</pubDate>
</item>
<item>
<title>Answered: How to calculate the distance between two latitude-longitude points in PHP</title>
<link>https://collectivesolver.com/100420/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-php?show=100421#a100421</link>
<description>&lt;pre class=&quot;brush:php;&quot;&gt;// ------------------------------------------------------------
// Convert degrees to radians
// ------------------------------------------------------------
function degToRad(float $deg): float {
    return $deg * M_PI / 180.0;
}

// ------------------------------------------------------------
// Compute the great-circle distance between two points on Earth
// using the Haversine formula.
// lat1, lon1, lat2, lon2 are in degrees.
// The result is returned in kilometers.
// ------------------------------------------------------------
function haversine(float $lat1, float $lon1, float $lat2, float $lon2): float {

    // Earth's mean radius in kilometers
    $R = 6371.0;

    // Convert all angles to radians
    $rlat1 = degToRad($lat1);
    $rlon1 = degToRad($lon1);
    $rlat2 = degToRad($lat2);
    $rlon2 = degToRad($lon2);

    // Differences
    $dlat = $rlat2 - $rlat1;
    $dlon = $rlon2 - $rlon1;

    // Haversine formula
    // a is the Haversine of the central angle between the two points.
    $a = sin($dlat / 2) * sin($dlat / 2) +
         cos($rlat1) * cos($rlat2) *
         sin($dlon / 2) * sin($dlon / 2);

    // c is the central angle between the two points on the Earth’s surface.
    $c = 2 * asin(sqrt($a));

    // Final distance
    return $R * $c;
}

// ------------------------------------------------------------
// Main 
// ------------------------------------------------------------

// Example coordinates:
// Austin, Texas
$lat1 = 30.2672;
$lon1 = -97.7431;

// Houston, Texas
$lat2 = 29.7604;
$lon2 = -95.3698;

$distanceKm = haversine($lat1, $lon1, $lat2, $lon2);

// Convert kilometers to miles
$distanceMiles = $distanceKm * 0.621371;

echo &quot;Distance: &quot; . number_format($distanceKm, 3) . &quot; km\n&quot;;
echo &quot;Distance: &quot; . number_format($distanceMiles, 3) . &quot; miles\n&quot;;



/*
run:

Distance: 235.352 km
Distance: 146.241 miles

*/&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100420/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-php?show=100421#a100421</guid>
<pubDate>Fri, 07 Aug 2026 07:27:38 +0000</pubDate>
</item>
<item>
<title>Answered: How to calculate the distance between two latitude-longitude points in C#</title>
<link>https://collectivesolver.com/100418/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-c%23?show=100419#a100419</link>
<description>&lt;pre class=&quot;brush:csharp;&quot;&gt;using System;

class HaversineDistance
{
    // ------------------------------------------------------------
    // Convert degrees to radians
    // ------------------------------------------------------------
    static double DegToRad(double deg)
    {
        return deg * Math.PI / 180.0;
    }

    // ------------------------------------------------------------
    // Compute the great-circle distance between two points on Earth
    // using the Haversine formula.
    // lat1, lon1, lat2, lon2 are in degrees.
    // The result is returned in kilometers.
    // ------------------------------------------------------------
    static double Haversine(double lat1, double lon1,
                            double lat2, double lon2)
    {
        // Earth's mean radius in kilometers
        const double R = 6371.0;

        // Convert all angles to radians
        double rlat1 = DegToRad(lat1);
        double rlon1 = DegToRad(lon1);
        double rlat2 = DegToRad(lat2);
        double rlon2 = DegToRad(lon2);

        // Differences
        double dlat = rlat2 - rlat1;
        double dlon = rlon2 - rlon1;

        // Haversine formula
        // a is the Haversine of the central angle between the two points.
        double a = Math.Sin(dlat / 2) * Math.Sin(dlat / 2) +
                   Math.Cos(rlat1) * Math.Cos(rlat2) *
                   Math.Sin(dlon / 2) * Math.Sin(dlon / 2);

        // c is the central angle between the two points on the Earth’s surface.
        double c = 2 * Math.Asin(Math.Sqrt(a));

        // Final distance
        return R * c;
    }

    static void Main()
    {
        // Example coordinates:
        // Austin, Texas
        double lat1 = 30.2672;
        double lon1 = -97.7431;

        // Houston, Texas
        double lat2 = 29.7604;
        double lon2 = -95.3698;

        double distanceKm = Haversine(lat1, lon1, lat2, lon2);

        // Convert kilometers to miles
        double distanceMiles = distanceKm * 0.621371;

        Console.WriteLine(&quot;Distance: &quot; + distanceKm.ToString(&quot;0.000&quot;) + &quot; km&quot;);
        Console.WriteLine(&quot;Distance: &quot; + distanceMiles.ToString(&quot;0.000&quot;) + &quot; miles&quot;);
    }
}



/*
run:

Distance: 235.352 km
Distance: 146.241 miles

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100418/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-c%23?show=100419#a100419</guid>
<pubDate>Fri, 07 Aug 2026 06:55:30 +0000</pubDate>
</item>
<item>
<title>Answered: How to calculate the distance between two latitude-longitude points in VB.NET</title>
<link>https://collectivesolver.com/100416/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-vb-net?show=100417#a100417</link>
<description>&lt;pre class=&quot;brush:vb;&quot;&gt;Imports System

Module HaversineDistance

    ' ------------------------------------------------------------
    ' Convert degrees to radians
    ' ------------------------------------------------------------
    Function DegToRad(deg As Double) As Double
        Return deg * Math.PI / 180.0
    End Function

    ' ------------------------------------------------------------
    ' Compute the great-circle distance between two points on Earth
    ' using the Haversine formula.
    ' lat1, lon1, lat2, lon2 are in degrees.
    ' The result is returned in kilometers.
    ' ------------------------------------------------------------
    Function Haversine(lat1 As Double, lon1 As Double,
                       lat2 As Double, lon2 As Double) As Double

        ' Earth's mean radius in kilometers
        Const R As Double = 6371.0

        ' Convert all angles to radians
        Dim rlat1 As Double = DegToRad(lat1)
        Dim rlon1 As Double = DegToRad(lon1)
        Dim rlat2 As Double = DegToRad(lat2)
        Dim rlon2 As Double = DegToRad(lon2)

        ' Differences
        Dim dlat As Double = rlat2 - rlat1
        Dim dlon As Double = rlon2 - rlon1

        ' Haversine formula
        ' a is the Haversine of the central angle between the two points.
        Dim a As Double =
            Math.Sin(dlat / 2) * Math.Sin(dlat / 2) +
            Math.Cos(rlat1) * Math.Cos(rlat2) *
            Math.Sin(dlon / 2) * Math.Sin(dlon / 2)

        ' c is the central angle between the two points on the Earth’s surface.
        Dim c As Double = 2 * Math.Asin(Math.Sqrt(a))

        ' Final distance
        Return R * c
    End Function

    Sub Main()

        ' Example coordinates:
        ' Austin, Texas
        Dim lat1 As Double = 30.2672
        Dim lon1 As Double = -97.7431

        ' Houston, Texas
        Dim lat2 As Double = 29.7604
        Dim lon2 As Double = -95.3698

        Dim distanceKm As Double = Haversine(lat1, lon1, lat2, lon2)

        ' Convert kilometers to miles
        Dim distanceMiles As Double = distanceKm * 0.621371

        Console.WriteLine(&quot;Distance: &quot; &amp;amp; distanceKm.ToString(&quot;0.000&quot;) &amp;amp; &quot; km&quot;)
        Console.WriteLine(&quot;Distance: &quot; &amp;amp; distanceMiles.ToString(&quot;0.000&quot;) &amp;amp; &quot; miles&quot;)

    End Sub

End Module



' run:
'
' Distance: 235.352 km
' Distance: 146.241 miles
'
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100416/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-vb-net?show=100417#a100417</guid>
<pubDate>Fri, 07 Aug 2026 06:53:57 +0000</pubDate>
</item>
<item>
<title>Answered: How to calculate the distance between two latitude-longitude points in Java</title>
<link>https://collectivesolver.com/100414/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-java?show=100415#a100415</link>
<description>&lt;pre class=&quot;brush:java;&quot;&gt;public class HaversineDistance {

    // ------------------------------------------------------------
    // Convert degrees to radians
    // ------------------------------------------------------------
    public static double degToRad(double deg) {
        return deg * Math.PI / 180.0;
    }

    // ------------------------------------------------------------
    // Compute the great-circle distance between two points on Earth
    // using the Haversine formula.
    // lat1, lon1, lat2, lon2 are in degrees.
    // The result is returned in kilometers.
    // ------------------------------------------------------------
    public static double haversine(double lat1, double lon1,
                                   double lat2, double lon2) {

        // Earth's mean radius in kilometers
        final double R = 6371.0;

        // Convert all angles to radians
        double rlat1 = degToRad(lat1);
        double rlon1 = degToRad(lon1);
        double rlat2 = degToRad(lat2);
        double rlon2 = degToRad(lon2);

        // Differences
        double dlat = rlat2 - rlat1;
        double dlon = rlon2 - rlon1;

        // Haversine formula
        // a is the Haversine of the central angle between the two points.
        double a = Math.sin(dlat / 2) * Math.sin(dlat / 2)
                 + Math.cos(rlat1) * Math.cos(rlat2)
                 * Math.sin(dlon / 2) * Math.sin(dlon / 2);

        // c is the central angle between the two points on the Earth’s surface.
        double c = 2 * Math.asin(Math.sqrt(a));

        // Final distance
        return R * c;
    }

    public static void main(String[] args) {

        // Example coordinates:
        // Austin, Texas
        double lat1 = 30.2672;
        double lon1 = -97.7431;

        // Houston, Texas
        double lat2 = 29.7604;
        double lon2 = -95.3698;

        double distanceKm = haversine(lat1, lon1, lat2, lon2);

        // Convert kilometers to miles
        double distanceMiles = distanceKm * 0.621371;

        System.out.println(&quot;Distance: &quot; + distanceKm + &quot; km&quot;);
        System.out.println(&quot;Distance: &quot; + distanceMiles + &quot; miles&quot;);
    }
}


/*
run:

Distance: 235.3521373242579 km
Distance: 146.24099292131146 miles

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100414/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-java?show=100415#a100415</guid>
<pubDate>Fri, 07 Aug 2026 06:18:52 +0000</pubDate>
</item>
<item>
<title>Answered: How to calculate the distance between two latitude-longitude points in Pascal</title>
<link>https://collectivesolver.com/100412/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-pascal?show=100413#a100413</link>
<description>&lt;pre class=&quot;brush:delphi;&quot;&gt;program HaversineDistance;

{$mode objfpc}

uses
  Math;  { Provides sin, cos, sqrt, arcsin, Pi }

{ ------------------------------------------------------------
  Convert degrees to radians
  ------------------------------------------------------------ }
function DegToRad(deg: Double): Double;
begin
  Result := deg * Pi / 180.0;
end;

{ ------------------------------------------------------------
  Compute the great-circle distance between two points on Earth
  using the Haversine formula.
  lat1, lon1, lat2, lon2 are in degrees.
  The result is returned in kilometers.
  ------------------------------------------------------------ }
function Haversine(lat1, lon1, lat2, lon2: Double): Double;
const
  R = 6371.0;  { Earth's mean radius in kilometers }
var
  rlat1, rlon1, rlat2, rlon2: Double;
  dlat, dlon: Double;
  a, c: Double;
begin
  { Convert all angles to radians }
  rlat1 := DegToRad(lat1);
  rlon1 := DegToRad(lon1);
  rlat2 := DegToRad(lat2);
  rlon2 := DegToRad(lon2);

  { Differences }
  dlat := rlat2 - rlat1;
  dlon := rlon2 - rlon1;

  { Haversine formula }
  // a is the Haversine of the central angle between the two points.
  
  // It combines the differences in latitude and longitude, adjusted by 
  // cosine terms to account for Earth’s curvature.
  a := Sqr(Sin(dlat / 2)) +
       Cos(rlat1) * Cos(rlat2) * Sqr(Sin(dlon / 2));

  // c is the central angle between the two points on the Earth’s surface.
  // This angle is measured in radians.
  // It tells you how large the arc is between the two points on the globe.
  c := 2 * ArcSin(Sqrt(a));

  { Final distance }
  Result := R * c;
end;

var
  lat1, lon1, lat2, lon2: Double;
  distanceKm, distanceMiles: Double;

begin
  { Example coordinates:
    Austin, Texas }
  lat1 := 30.2672;
  lon1 := -97.7431;

  { Houston, Texas }
  lat2 := 29.7604;
  lon2 := -95.3698;

  distanceKm := Haversine(lat1, lon1, lat2, lon2);

  { Convert kilometers to miles }
  distanceMiles := distanceKm * 0.621371;

  WriteLn('Distance: ', distanceKm:0:3, ' km');
  WriteLn('Distance: ', distanceMiles:0:3, ' miles');
end.


{
run:

Distance: 235.352 km
Distance: 146.241 miles

}
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100412/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-pascal?show=100413#a100413</guid>
<pubDate>Fri, 07 Aug 2026 06:04:08 +0000</pubDate>
</item>
<item>
<title>Answered: How to calculate the distance between two latitude-longitude points in C</title>
<link>https://collectivesolver.com/100410/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-c?show=100411#a100411</link>
<description>&lt;pre class=&quot;brush:cpp;&quot;&gt;#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;math.h&amp;gt;

/* ------------------------------------------------------------
   Convert degrees to radians
   ------------------------------------------------------------ */
double degToRad(double deg) {
    return deg * M_PI / 180.0;
}

/* ------------------------------------------------------------
   Compute the great-circle distance between two points on Earth
   using the Haversine formula.
   lat1, lon1, lat2, lon2 are in degrees.
   The result is returned in kilometers.
   ------------------------------------------------------------ */
double haversine(double lat1, double lon1, double lat2, double lon2) {
    /* Earth's mean radius in kilometers */
    const double R = 6371.0;

    /* Convert all angles to radians */
    double rlat1 = degToRad(lat1);
    double rlon1 = degToRad(lon1);
    double rlat2 = degToRad(lat2);
    double rlon2 = degToRad(lon2);

    /* Differences */
    double dlat = rlat2 - rlat1;
    double dlon = rlon2 - rlon1;

    /* Haversine formula */
    // a is the Haversine of the central angle between the two points.
   
    // It combines the differences in latitude and longitude, adjusted by 
    // cosine terms to account for Earth’s curvature.
    double a = sin(dlat / 2) * sin(dlat / 2) +
               cos(rlat1) * cos(rlat2) *
               sin(dlon / 2) * sin(dlon / 2);

    // c is the central angle between the two points on the Earth’s surface.
    // This angle is measured in radians.
    // It tells you how large the arc is between the two points on the globe.
    double c = 2 * asin(sqrt(a));

    /* Final distance */
    return R * c;
}

int main() {
    /* Example coordinates:
       Austin, Texas */
    double lat1 = 30.2672;
    double lon1 = -97.7431;

    /* Houston, Texas */
    double lat2 = 29.7604;
    double lon2 = -95.3698;

    double distanceKm = haversine(lat1, lon1, lat2, lon2);

    /* Convert kilometers to miles */
    double distanceMiles = distanceKm * 0.621371;

    printf(&quot;Distance: %.3f km\n&quot;, distanceKm);
    printf(&quot;Distance: %.3f miles\n&quot;, distanceMiles);

    return 0;
}



/*
run:

Distance: 235.352 km
Distance: 146.241 miles

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100410/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-c?show=100411#a100411</guid>
<pubDate>Fri, 07 Aug 2026 05:53:05 +0000</pubDate>
</item>
<item>
<title>Answered: How to calculate the distance between two latitude-longitude points in C++</title>
<link>https://collectivesolver.com/100408/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-c?show=100409#a100409</link>
<description>&lt;pre class=&quot;brush:cpp;&quot;&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;cmath&amp;gt;

// ------------------------------------------------------------
// Convert degrees to radians
// ------------------------------------------------------------
double degToRad(double deg) {
    return deg * M_PI / 180.0;
}

// ------------------------------------------------------------
// Compute the great-circle distance between two points on Earth
// using the Haversine formula.
// lat1, lon1, lat2, lon2 are in degrees.
// The result is returned in kilometers.
// ------------------------------------------------------------
double haversine(double lat1, double lon1, double lat2, double lon2) {
    // Earth's mean radius in kilometers
    constexpr double R = 6371.0;

    // Convert all angles to radians
    double rlat1 = degToRad(lat1);
    double rlon1 = degToRad(lon1);
    double rlat2 = degToRad(lat2);
    double rlon2 = degToRad(lon2);

    // Differences
    double dlat = rlat2 - rlat1;
    double dlon = rlon2 - rlon1;

    // Haversine formula
    // a is the Haversine of the central angle between the two points.
    
    // It combines the differences in latitude and longitude, adjusted by 
    // cosine terms to account for Earth’s curvature.
    double a = std::sin(dlat / 2) * std::sin(dlat / 2) +
               std::cos(rlat1) * std::cos(rlat2) *
               std::sin(dlon / 2) * std::sin(dlon / 2);

    // c is the central angle between the two points on the Earth’s surface.
    // This angle is measured in radians.
    // It tells you how large the arc is between the two points on the globe.
    double c = 2 * std::asin(std::sqrt(a));

    // Final distance
    return R * c;
}

int main() {
    // Example coordinates:
    // Austin, Texas
    double lat1 = 30.2672;
    double lon1 = -97.7431;

    // Houston, Texas
    double lat2 = 29.7604;
    double lon2 = -95.3698;

    double distanceKm = haversine(lat1, lon1, lat2, lon2);

    // Convert kilometers to miles
    double distanceMiles = distanceKm * 0.621371;

    std::cout &amp;lt;&amp;lt; &quot;Distance: &quot; &amp;lt;&amp;lt; distanceKm &amp;lt;&amp;lt; &quot; km\n&quot;;
    std::cout &amp;lt;&amp;lt; &quot;Distance: &quot; &amp;lt;&amp;lt; distanceMiles &amp;lt;&amp;lt; &quot; miles\n&quot;;
}


/*
run:

Distance: 235.352 km
Distance: 146.241 miles

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100408/how-to-calculate-the-distance-between-two-latitude-longitude-points-in-c?show=100409#a100409</guid>
<pubDate>Thu, 06 Aug 2026 15:48:21 +0000</pubDate>
</item>
<item>
<title>Answered: How to convert a decimal to int64 in Swift</title>
<link>https://collectivesolver.com/100406/how-to-convert-a-decimal-to-int64-in-swift?show=100407#a100407</link>
<description>&lt;pre class=&quot;brush:jscript;&quot;&gt;import Foundation

/*
    ============================================================
    Convert a decimal-like value to Int64 in Swift.

    This program demonstrates:
      • Conversion using rounded(), which rounds to the nearest integer.
      • Conversion using Int64(value), which truncates toward zero.
      • Conversion using Decimal + NSDecimalNumber for strict conversion.
      • Helper functions that print all conversion styles.

    Notes:
      • Swift does not have a built-in &quot;long&quot; type; Int64 is the closest.
      • rounded() returns a Double; cast to Int64 afterward.
      • Int64(value) truncates the fractional part.
      • Decimal → Int64 conversion is done via NSDecimalNumber.
    ============================================================
*/

// Rounds a Double to Int64
func convertDoubleToInt64(_ value: Double) -&amp;gt; Int64 {
    return Int64(value.rounded())
}

// Truncates a Double to Int64
func castDoubleToInt64(_ value: Double) -&amp;gt; Int64 {
    return Int64(value)
}

// Converts Decimal using truncation
func convertDecimalToInt64(_ value: Decimal) -&amp;gt; Int64 {
    return NSDecimalNumber(decimal: value).int64Value
}

// Converts Decimal strictly (throws if fractional or out of range)
func convertDecimalExact(_ value: Decimal) -&amp;gt; String {
    let number = NSDecimalNumber(decimal: value)
    do {
        let exact = try number.int64ValueExact()
        return &quot;\(exact)&quot;
    } catch {
        return &quot;ERROR — fractional or out of range&quot;
    }
}

// Prints conversion styles for Double
func showDoubleConversions(_ value: Double) {
    print(&quot;Input decimal (Double): \(value)&quot;)
    print(&quot;Rounded (rounded): \(convertDoubleToInt64(value))&quot;)
    print(&quot;Truncated (Int64 cast): \(castDoubleToInt64(value))&quot;)
    print()
}

// Prints conversion styles for Decimal
func showDecimalConversions(_ value: Decimal) {
    print(&quot;Input decimal (Decimal): \(value)&quot;)
    print(&quot;Truncated (int64Value): \(convertDecimalToInt64(value))&quot;)
    print(&quot;Exact (int64ValueExact): \(convertDecimalExact(value))&quot;)
    print()
}

extension NSDecimalNumber {
    // Throws if fractional or out of range
    func int64ValueExact() throws -&amp;gt; Int64 {
        if self.decimalValue != Decimal(self.int64Value) {
            throw NSError(domain: &quot;ExactConversion&quot;, code: 1, userInfo: nil)
        }
        return self.int64Value
    }
}

func main() {
    // Double examples
    showDoubleConversions(12.7)
    showDoubleConversions(12.3)
    showDoubleConversions(-5.8)
    showDoubleConversions(42.0)

    // Decimal examples
    showDecimalConversions(Decimal(string: &quot;12.7&quot;)!)
    showDecimalConversions(Decimal(string: &quot;42&quot;)!)
    showDecimalConversions(Decimal(string: &quot;-5.8&quot;)!)
}

// Call main manually
main()



/*
run:

Input decimal (Double): 12.7
Rounded (rounded): 13
Truncated (Int64 cast): 12

Input decimal (Double): 12.3
Rounded (rounded): 12
Truncated (Int64 cast): 12

Input decimal (Double): -5.8
Rounded (rounded): -6
Truncated (Int64 cast): -5

Input decimal (Double): 42.0
Rounded (rounded): 42
Truncated (Int64 cast): 42

Input decimal (Decimal): 12.7
Truncated (int64Value): 12
Exact (int64ValueExact): ERROR — fractional or out of range

Input decimal (Decimal): 42
Truncated (int64Value): 42
Exact (int64ValueExact): 42

Input decimal (Decimal): -5.8
Truncated (int64Value): -5
Exact (int64ValueExact): ERROR — fractional or out of range

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100406/how-to-convert-a-decimal-to-int64-in-swift?show=100407#a100407</guid>
<pubDate>Thu, 06 Aug 2026 15:35:52 +0000</pubDate>
</item>
<item>
<title>Answered: How to convert a decimal to integer in Kotlin</title>
<link>https://collectivesolver.com/100404/how-to-convert-a-decimal-to-integer-in-kotlin?show=100405#a100405</link>
<description>&lt;pre class=&quot;brush:jscript;&quot;&gt;import kotlin.math.round
import java.math.BigDecimal

/*
    ============================================================
    Convert a decimal-like value to Long in Kotlin.

    This program demonstrates:
      • Conversion using round() for rounding.
      • Conversion using toLong() for truncation.
      • Conversion using BigDecimal.longValueExact() for strict conversion.
      • A helper function that prints all conversion styles.

    Notes:
      • Kotlin does not have a built-in decimal type; Double and BigDecimal
        are used for decimal values.
      • round() returns a Double; cast to Long afterward.
      • toLong() truncates the fractional part.
      • BigDecimal.longValueExact() throws if the value is fractional or out of range.
    ============================================================
*/

// Rounds a Double to Long
fun convertDoubleToLong(value: Double): Long =
    round(value).toLong()

// Truncates a Double to Long
fun castDoubleToLong(value: Double): Long =
    value.toLong()

// Converts BigDecimal using truncation
fun convertBigDecimalToLong(value: BigDecimal): Long =
    value.toLong()

// Converts BigDecimal strictly (throws if fractional or out of range)
fun convertBigDecimalExact(value: BigDecimal): String =
    try {
        value.longValueExact().toString()
    } catch (e: ArithmeticException) {
        &quot;ERROR — fractional or out of range&quot;
    }

// Prints conversion styles for Double
fun showDoubleConversions(value: Double) {
    println(&quot;Input decimal (Double): $value&quot;)
    println(&quot;Rounded (round): ${convertDoubleToLong(value)}&quot;)
    println(&quot;Truncated (toLong): ${castDoubleToLong(value)}&quot;)
    println()
}

// Prints conversion styles for BigDecimal
fun showBigDecimalConversions(value: BigDecimal) {
    println(&quot;Input decimal (BigDecimal): $value&quot;)
    println(&quot;Truncated (toLong): ${convertBigDecimalToLong(value)}&quot;)
    println(&quot;Exact (longValueExact): ${convertBigDecimalExact(value)}&quot;)
    println()
}

fun main() {
    // Double examples
    showDoubleConversions(12.7)
    showDoubleConversions(12.3)
    showDoubleConversions(-5.8)
    showDoubleConversions(42.0)

    // BigDecimal examples
    showBigDecimalConversions(BigDecimal(&quot;12.7&quot;))
    showBigDecimalConversions(BigDecimal(&quot;42&quot;))
    showBigDecimalConversions(BigDecimal(&quot;-5.8&quot;))
}


/*
run:

Input decimal (Double): 12.7
Rounded (round): 13
Truncated (toLong): 12

Input decimal (Double): 12.3
Rounded (round): 12
Truncated (toLong): 12

Input decimal (Double): -5.8
Rounded (round): -6
Truncated (toLong): -5

Input decimal (Double): 42.0
Rounded (round): 42
Truncated (toLong): 42

Input decimal (BigDecimal): 12.7
Truncated (toLong): 12
Exact (longValueExact): ERROR ? fractional or out of range

Input decimal (BigDecimal): 42
Truncated (toLong): 42
Exact (longValueExact): 42

Input decimal (BigDecimal): -5.8
Truncated (toLong): -5
Exact (longValueExact): ERROR ? fractional or out of range

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100404/how-to-convert-a-decimal-to-integer-in-kotlin?show=100405#a100405</guid>
<pubDate>Thu, 06 Aug 2026 15:29:02 +0000</pubDate>
</item>
<item>
<title>Answered: How to convert a decimal to integer in Scala</title>
<link>https://collectivesolver.com/100402/how-to-convert-a-decimal-to-integer-in-scala?show=100403#a100403</link>
<description>&lt;pre class=&quot;brush:scala;&quot;&gt;/*
    ============================================================
    Convert a decimal-like value to Long in Scala.

    This program demonstrates:
      • Conversion using Math.round() for rounding.
      • Conversion using toLong for truncation.
      • Conversion using BigDecimal.toLongExact for strict conversion.
      • A helper method that prints all conversion styles.

    Notes:
      • Scala does not have a separate &quot;decimal&quot; type; Double and BigDecimal
        are used for decimal values.
      • Math.round returns a Long.
      • toLong truncates the fractional part.
      • BigDecimal.toLongExact throws if the value is fractional or out of range.
    ============================================================
*/

object DecimalToLongDemo {

  // Rounds a Double to Long
  def convertDoubleToLong(value: Double): Long =
    Math.round(value)

  // Truncates a Double to Long
  def castDoubleToLong(value: Double): Long =
    value.toLong

  // Converts BigDecimal using truncation
  def convertBigDecimalToLong(value: BigDecimal): Long =
    value.toLong

  // Converts BigDecimal strictly (throws if fractional)
  def convertBigDecimalExact(value: BigDecimal): Either[String, Long] =
    try {
      Right(value.toLongExact)
    } catch {
      case _: ArithmeticException =&amp;gt;
        Left(&quot;ERROR — fractional or out of range&quot;)
    }

  // Prints conversion styles for Double
  def showDoubleConversions(value: Double): Unit = {
    println(s&quot;Input decimal (Double): $value&quot;)
    println(s&quot;Rounded (Math.round): ${convertDoubleToLong(value)}&quot;)
    println(s&quot;Truncated (toLong): ${castDoubleToLong(value)}&quot;)
    println()
  }

  // Prints conversion styles for BigDecimal
  def showBigDecimalConversions(value: BigDecimal): Unit = {
    println(s&quot;Input decimal (BigDecimal): $value&quot;)
    println(s&quot;Truncated (toLong): ${convertBigDecimalToLong(value)}&quot;)

    convertBigDecimalExact(value) match {
      case Right(v) =&amp;gt; println(s&quot;Exact (toLongExact): $v&quot;)
      case Left(err) =&amp;gt; println(s&quot;Exact (toLongExact): $err&quot;)
    }

    println()
  }

  def main(args: Array[String]): Unit = {
    // Double examples
    showDoubleConversions(12.7)
    showDoubleConversions(12.3)
    showDoubleConversions(-5.8)
    showDoubleConversions(42.0)

    // BigDecimal examples
    showBigDecimalConversions(BigDecimal(&quot;12.7&quot;))
    showBigDecimalConversions(BigDecimal(&quot;42&quot;))
    showBigDecimalConversions(BigDecimal(&quot;-5.8&quot;))
  }
}



/*
run:

Input decimal (Double): 12.7
Rounded (Math.round): 13
Truncated (toLong): 12

Input decimal (Double): 12.3
Rounded (Math.round): 12
Truncated (toLong): 12

Input decimal (Double): -5.8
Rounded (Math.round): -6
Truncated (toLong): -5

Input decimal (Double): 42.0
Rounded (Math.round): 42
Truncated (toLong): 42

Input decimal (BigDecimal): 12.7
Truncated (toLong): 12
Exact (toLongExact): ERROR — fractional or out of range

Input decimal (BigDecimal): 42
Truncated (toLong): 42
Exact (toLongExact): 42

Input decimal (BigDecimal): -5.8
Truncated (toLong): -5
Exact (toLongExact): ERROR — fractional or out of range

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100402/how-to-convert-a-decimal-to-integer-in-scala?show=100403#a100403</guid>
<pubDate>Thu, 06 Aug 2026 15:06:37 +0000</pubDate>
</item>
<item>
<title>Answered: How to convert a decimal to integer in Ruby</title>
<link>https://collectivesolver.com/100400/how-to-convert-a-decimal-to-integer-in-ruby?show=100401#a100401</link>
<description>&lt;pre class=&quot;brush:ruby;&quot;&gt;require 'bigdecimal'
require 'bigdecimal/util'

=begin
    ============================================================
    Convert a decimal-like value to an Integer in Ruby.

    This program demonstrates:
      • Conversion using round, which rounds to the nearest integer.
      • Conversion using to_i, which truncates toward zero.
      • Conversion using BigDecimal for precise decimal arithmetic.
      • A helper method that prints all conversion styles.

    Notes:
      • Ruby does not have a separate &quot;long&quot; type; Integer expands as needed.
      • round returns an Integer.
      • to_i removes the fractional part.
      • BigDecimal#to_i also truncates.
    ============================================================
=end

# Rounds a Float to an Integer
def convert_decimal_to_integer(value)
  value.round
end

# Truncates a Float to an Integer
def cast_decimal_to_integer(value)
  value.to_i
end

# Converts BigDecimal using truncation
def convert_bigdecimal_to_integer(value)
  value.to_i
end

# Prints both conversion styles for Float
def show_float_conversions(value)
  puts &quot;Input decimal (Float): #{value}&quot;

  rounded   = convert_decimal_to_integer(value)
  truncated = cast_decimal_to_integer(value)

  puts &quot;Rounded (round): #{rounded}&quot;
  puts &quot;Truncated (to_i): #{truncated}&quot;
  puts
end

# Prints conversion styles for BigDecimal
def show_bigdecimal_conversions(value)
  puts &quot;Input decimal (BigDecimal): #{value}&quot;

  truncated = convert_bigdecimal_to_integer(value)
  puts &quot;Truncated (to_i): #{truncated}&quot;

  puts
end

# Main
show_float_conversions(12.7)
show_float_conversions(12.3)
show_float_conversions(-5.8)
show_float_conversions(42.0)

show_bigdecimal_conversions(BigDecimal(&quot;12.7&quot;))
show_bigdecimal_conversions(BigDecimal(&quot;42&quot;))
show_bigdecimal_conversions(BigDecimal(&quot;-5.8&quot;))



=begin
run:

Input decimal (Float): 12.7
Rounded (round): 13
Truncated (to_i): 12

Input decimal (Float): 12.3
Rounded (round): 12
Truncated (to_i): 12

Input decimal (Float): -5.8
Rounded (round): -6
Truncated (to_i): -5

Input decimal (Float): 42.0
Rounded (round): 42
Truncated (to_i): 42

Input decimal (BigDecimal): 0.127e2
Truncated (to_i): 12

Input decimal (BigDecimal): 0.42e2
Truncated (to_i): 42

Input decimal (BigDecimal): -0.58e1
Truncated (to_i): -5

=end
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100400/how-to-convert-a-decimal-to-integer-in-ruby?show=100401#a100401</guid>
<pubDate>Thu, 06 Aug 2026 14:51:49 +0000</pubDate>
</item>
<item>
<title>Answered: How to convert a decimal to i64 in Rust</title>
<link>https://collectivesolver.com/100398/how-to-convert-a-decimal-to-i64-in-rust?show=100399#a100399</link>
<description>&lt;pre class=&quot;brush:cpp;&quot;&gt;/*
    ============================================================
    Convert a decimal-like value to i64 in Rust.

    This program demonstrates:
      • Conversion using f64::round(), which rounds to the nearest integer.
      • Conversion using f64::trunc(), which truncates toward zero.
      • Conversion using &quot;as i64&quot;, which also truncates.
      • A helper function that prints both results for comparison.

    Notes:
      • Rust does not have a built-in decimal type.
      • f64 is used for decimal values.
      • round() returns an f64; cast to i64 afterward.
      • trunc() removes the fractional part.
    ============================================================
*/

fn convert_decimal_to_i64(value: f64) -&amp;gt; i64 {
    // Rounds to nearest integer, then cast to i64
    value.round() as i64
}

fn cast_decimal_to_i64(value: f64) -&amp;gt; i64 {
    // Truncates fractional part toward zero
    value as i64
}

fn show_conversions(value: f64) {
    println!(&quot;Input decimal: {:.4}&quot;, value);

    let rounded = convert_decimal_to_i64(value);
    let truncated = cast_decimal_to_i64(value);

    println!(&quot;Rounded (round): {}&quot;, rounded);
    println!(&quot;Truncated (as i64): {}&quot;, truncated);
    println!();
}

fn main() {
    // Example values to demonstrate behavior
    show_conversions(12.7);
    show_conversions(12.3);
    show_conversions(-5.8);
    show_conversions(42.0); // already an integer
}


/*
run:

Input decimal: 12.7000
Rounded (round): 13
Truncated (as i64): 12

Input decimal: 12.3000
Rounded (round): 12
Truncated (as i64): 12

Input decimal: -5.8000
Rounded (round): -6
Truncated (as i64): -5

Input decimal: 42.0000
Rounded (round): 42
Truncated (as i64): 42

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100398/how-to-convert-a-decimal-to-i64-in-rust?show=100399#a100399</guid>
<pubDate>Thu, 06 Aug 2026 14:48:20 +0000</pubDate>
</item>
<item>
<title>Answered: How to convert a decimal to int64 in Go</title>
<link>https://collectivesolver.com/100396/how-to-convert-a-decimal-to-int64-in-go?show=100397#a100397</link>
<description>&lt;pre class=&quot;brush:cpp;&quot;&gt;package main

import (
    &quot;fmt&quot;
    &quot;math&quot;
)

/*
    ============================================================
    Convert a decimal-like value to int64 in Go.

    This program demonstrates:
      • Conversion using math.Round(), which rounds to the nearest integer.
      • Conversion using int64(value), which truncates toward zero.
      • A helper function that prints both results for comparison.

    Notes:
      • Go does not have a built-in decimal type.
      • float64 is used for decimal values.
      • math.Round() returns a float64; cast to int64 afterward.
      • int64(value) truncates the fractional part.
    ============================================================
*/

// Converts a decimal to int64 using rounding
func convertDecimalToInt64(value float64) int64 {
    return int64(math.Round(value))
}

// Converts a decimal to int64 using truncation
func castDecimalToInt64(value float64) int64 {
    return int64(value)
}

// Prints both conversion styles for comparison
func showConversions(value float64) {
    fmt.Printf(&quot;Input decimal: %.4f\n&quot;, value)

    rounded := convertDecimalToInt64(value)
    truncated := castDecimalToInt64(value)

    fmt.Printf(&quot;Rounded (math.Round): %d\n&quot;, rounded)
    fmt.Printf(&quot;Truncated (int64 cast): %d\n\n&quot;, truncated)
}

func main() {
    // Example values to demonstrate behavior
    showConversions(12.7)
    showConversions(12.3)
    showConversions(-5.8)
    showConversions(42.0) // already an integer
}


/*
run:

Input decimal: 12.7000
Rounded (math.Round): 13
Truncated (int64 cast): 12

Input decimal: 12.3000
Rounded (math.Round): 12
Truncated (int64 cast): 12

Input decimal: -5.8000
Rounded (math.Round): -6
Truncated (int64 cast): -5

Input decimal: 42.0000
Rounded (math.Round): 42
Truncated (int64 cast): 42

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100396/how-to-convert-a-decimal-to-int64-in-go?show=100397#a100397</guid>
<pubDate>Thu, 06 Aug 2026 14:28:11 +0000</pubDate>
</item>
<item>
<title>Answered: How to convert a decimal to an integer in PHP</title>
<link>https://collectivesolver.com/100394/how-to-convert-a-decimal-to-an-integer-in-php?show=100395#a100395</link>
<description>&lt;pre class=&quot;brush:php;&quot;&gt;/*
    ============================================================
    Convert a decimal-like value to an integer in PHP.
 
    This program demonstrates:
      • Conversion using round(), which rounds to the nearest integer.
      • Conversion using intval(), which truncates toward zero.
      • Conversion using (int), which also truncates.
      • A helper function that prints all conversion styles.
 
    Notes:
      • PHP does not have a distinct &quot;long&quot; type; integers expand as needed.
      • round() follows standard rounding rules.
      • intval() and (int) remove the fractional part.
    ============================================================
*/
 
/* Converts a decimal to an integer using rounding */
function convert_decimal_to_integer(float $value): int {
    return round($value);
}
 
/* Converts a decimal to an integer using truncation */
function cast_decimal_to_integer(float $value): int {
    return intval($value);   // same as (int)$value
}
 
/* Prints both conversion styles for comparison */
function show_conversions(float $value): void {
    echo &quot;Input decimal: {$value}\n&quot;;
 
    $rounded   = convert_decimal_to_integer($value);
    $truncated = cast_decimal_to_integer($value);
 
    echo &quot;Rounded (round): {$rounded}\n&quot;;
    echo &quot;Truncated (intval): {$truncated}\n\n&quot;;
}
 
/* Main */
show_conversions(12.7);
show_conversions(12.3);
show_conversions(-5.8);
show_conversions(42.0);   // already an integer
 
 
/*
run:
 
Input decimal: 12.7
Rounded (round): 13
Truncated (intval): 12
 
Input decimal: 12.3
Rounded (round): 12
Truncated (intval): 12
 
Input decimal: -5.8
Rounded (round): -6
Truncated (intval): -5
 
Input decimal: 42
Rounded (round): 42
Truncated (intval): 42
 
*/&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100394/how-to-convert-a-decimal-to-an-integer-in-php?show=100395#a100395</guid>
<pubDate>Thu, 06 Aug 2026 09:42:35 +0000</pubDate>
</item>
<item>
<title>Answered: How to convert a decimal to a long in Java</title>
<link>https://collectivesolver.com/100392/how-to-convert-a-decimal-to-a-long-in-java?show=100393#a100393</link>
<description>&lt;pre class=&quot;brush:java;&quot;&gt;public class DecimalToLongProgram {

    /**
        ============================================================
        Convert decimal-like values to long in Java.

        This class demonstrates:
          • Conversion using Math.round() for floating-point rounding.
          • Conversion using a direct cast (long) for truncation.
          • Conversion using BigDecimal.longValue() and longValueExact().
          • A helper method that prints all conversion styles.

        Notes:
          • Math.round() returns a long and rounds to nearest integer.
          • (long)value truncates the fractional part.
          • BigDecimal.longValue() truncates.
          • BigDecimal.longValueExact() throws if fractional or out of range.
        ============================================================
    */

    // Rounds a double to long
    static long convertDoubleToLong(double value) {
        return Math.round(value);
    }

    // Truncates a double to long
    static long castDoubleToLong(double value) {
        return (long) value;
    }

    // Rounds or truncates a BigDecimal
    static long convertBigDecimalToLong(java.math.BigDecimal value) {
        return value.longValue(); // truncates
    }

    // Exact conversion (throws if fractional)
    static long convertBigDecimalExact(java.math.BigDecimal value) {
        return value.longValueExact(); // strict
    }

    // Prints all conversion styles for comparison
    static void showConversions(double value) {
        System.out.println(&quot;Input decimal (double): &quot; + value);

        long rounded   = convertDoubleToLong(value);
        long truncated = castDoubleToLong(value);

        System.out.println(&quot;Rounded (Math.round): &quot; + rounded);
        System.out.println(&quot;Truncated (cast to long): &quot; + truncated);
        System.out.println();
    }

    static void showConversions(java.math.BigDecimal value) {
        System.out.println(&quot;Input decimal (BigDecimal): &quot; + value);

        long truncated = convertBigDecimalToLong(value);
        System.out.println(&quot;Truncated (longValue): &quot; + truncated);

        try {
            long exact = convertBigDecimalExact(value);
            System.out.println(&quot;Exact (longValueExact): &quot; + exact);
        } catch (ArithmeticException ex) {
            System.out.println(&quot;Exact (longValueExact): ERROR — fractional or out of range&quot;);
        }

        System.out.println();
    }

    public static void main(String[] args) {

        // Floating-point examples
        showConversions(12.7);
        showConversions(12.3);
        showConversions(-5.8);
        showConversions(42.0);

        // BigDecimal examples
        // it only succeeds when the BigDecimal represents a whole number that fits inside a long.
        showConversions(new java.math.BigDecimal(&quot;12.7&quot;));
        showConversions(new java.math.BigDecimal(&quot;42&quot;));
        showConversions(new java.math.BigDecimal(&quot;-5.8&quot;));
    }
}



/*
run:

Input decimal (double): 12.7
Rounded (Math.round): 13
Truncated (cast to long): 12

Input decimal (double): 12.3
Rounded (Math.round): 12
Truncated (cast to long): 12

Input decimal (double): -5.8
Rounded (Math.round): -6
Truncated (cast to long): -5

Input decimal (double): 42.0
Rounded (Math.round): 42
Truncated (cast to long): 42

Input decimal (BigDecimal): 12.7
Truncated (longValue): 12
Exact (longValueExact): ERROR ? fractional or out of range

Input decimal (BigDecimal): 42
Truncated (longValue): 42
Exact (longValueExact): 42

Input decimal (BigDecimal): -5.8
Truncated (longValue): -5
Exact (longValueExact): ERROR ? fractional or out of range

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100392/how-to-convert-a-decimal-to-a-long-in-java?show=100393#a100393</guid>
<pubDate>Thu, 06 Aug 2026 09:36:16 +0000</pubDate>
</item>
<item>
<title>Answered: How to convert a decimal to a long in Pascal</title>
<link>https://collectivesolver.com/100390/how-to-convert-a-decimal-to-a-long-in-pascal?show=100391#a100391</link>
<description>&lt;pre class=&quot;brush:delphi;&quot;&gt;program DecimalToLongProgram;

{$mode objfpc}{$H+}

{
    ============================================================
    Convert a decimal-like value to a LongInt in Free Pascal.

    This program demonstrates:
      • Conversion using Round(), which rounds to the nearest integer.
      • Conversion using Trunc(), which truncates toward zero.
      • A helper procedure that prints both results for comparison.

    Notes:
      • Free Pascal does not have a built-in decimal type.
      • Real/Double/Extended are used for decimal values.
      • Round() follows standard rounding rules.
      • Trunc() removes the fractional part.
    ============================================================
}

{ Converts a floating decimal value to LongInt using rounding }
function ConvertDecimalToLong(value: Double): LongInt;
begin
    Result := Round(value);
end;

{ Converts a floating decimal value to LongInt using truncation }
function CastDecimalToLong(value: Double): LongInt;
begin
    Result := Trunc(value);
end;

{ Prints both conversion styles for comparison }
procedure ShowConversions(value: Double);
var
    rounded, truncated: LongInt;
begin
    Writeln('Input decimal: ', value:0:4);

    rounded   := ConvertDecimalToLong(value);
    truncated := CastDecimalToLong(value);

    Writeln('Rounded (Round): ', rounded);
    Writeln('Truncated (Trunc): ', truncated);
    Writeln;
end;

begin
    { Example values to demonstrate behavior }
    ShowConversions(12.7);
    ShowConversions(12.3);
    ShowConversions(-5.8);
    ShowConversions(42.0);   { already an integer }
end.



{
run:

Input decimal: 12.7000
Rounded (Round): 13
Truncated (Trunc): 12

Input decimal: 12.3000
Rounded (Round): 12
Truncated (Trunc): 12

Input decimal: -5.8000
Rounded (Round): -6
Truncated (Trunc): -5

Input decimal: 42.0000
Rounded (Round): 42
Truncated (Trunc): 42

}
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100390/how-to-convert-a-decimal-to-a-long-in-pascal?show=100391#a100391</guid>
<pubDate>Thu, 06 Aug 2026 09:29:42 +0000</pubDate>
</item>
<item>
<title>Answered: How to convert a decimal to a long in C</title>
<link>https://collectivesolver.com/100388/how-to-convert-a-decimal-to-a-long-in-c?show=100389#a100389</link>
<description>&lt;pre class=&quot;brush:cpp;&quot;&gt;#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;math.h&amp;gt;

/*
    ============================================================
    Convert a decimal-like value to a long in C.

    This program demonstrates:
      • Conversion using lround(), which rounds to the nearest integer.
      • Conversion using a direct cast (long), which truncates toward zero.
      • A helper function that prints both results for comparison.

    Notes:
      • C does not have a built-in decimal type.
      • double or long double are used for decimal values.
      • lround() follows IEEE rounding rules.
      • (long)value truncates the fractional part.
    ============================================================
*/

/* Converts a floating decimal value to long using rounding */
long convert_decimal_to_long(double value) {
    return lround(value);
}

/* Converts a floating decimal value to long using truncation */
long cast_decimal_to_long(double value) {
    return (long)value;
}

/* Prints both conversion styles for comparison */
void show_conversions(double value) {
    printf(&quot;Input decimal: %.4f\n&quot;, value);

    long rounded   = convert_decimal_to_long(value);
    long truncated = cast_decimal_to_long(value);

    printf(&quot;Rounded (lround): %ld\n&quot;, rounded);
    printf(&quot;Truncated (cast to long): %ld\n\n&quot;, truncated);
}

int main(void) {
    /* Example values to demonstrate behavior */
    show_conversions(12.7);
    show_conversions(12.3);
    show_conversions(-5.8);
    show_conversions(42.0);   /* already an integer */

    return 0;
}


/*
run:

Input decimal: 12.7000
Rounded (lround): 13
Truncated (cast to long): 12

Input decimal: 12.3000
Rounded (lround): 12
Truncated (cast to long): 12

Input decimal: -5.8000
Rounded (lround): -6
Truncated (cast to long): -5

Input decimal: 42.0000
Rounded (lround): 42
Truncated (cast to long): 42

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100388/how-to-convert-a-decimal-to-a-long-in-c?show=100389#a100389</guid>
<pubDate>Thu, 06 Aug 2026 09:23:43 +0000</pubDate>
</item>
<item>
<title>Answered: How to convert a decimal to a long in C++</title>
<link>https://collectivesolver.com/100386/how-to-convert-a-decimal-to-a-long-in-c?show=100387#a100387</link>
<description>&lt;pre class=&quot;brush:cpp;&quot;&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;cmath&amp;gt;
#include &amp;lt;string&amp;gt;

/*
    ============================================================
    Convert a decimal-like value to a long in C++.

    This program demonstrates:
      • Conversion using std::lround(), which rounds to nearest.
      • Conversion using static_cast&amp;lt;long&amp;gt;(), which truncates.
      • A helper function that prints both results.

    Notes:
      • C++ does not have a built-in decimal type.
      • double or long double are used for decimal values.
      • std::lround() follows IEEE rounding rules.
      • static_cast&amp;lt;long&amp;gt;() truncates toward zero.
    ============================================================
*/

class DecimalToLongProgram {
public:

    // Converts a floating decimal value to long using rounding.
    static long ConvertDecimalToLong(double value) {
        return std::lround(value);
    }

    // Converts a floating decimal value to long using truncation.
    static long CastDecimalToLong(double value) {
        return static_cast&amp;lt;long&amp;gt;(value);
    }

    // Prints both conversion styles for comparison.
    static void ShowConversions(double value) {
        std::cout &amp;lt;&amp;lt; &quot;Input decimal: &quot; &amp;lt;&amp;lt; value &amp;lt;&amp;lt; &quot;\n&quot;;

        long rounded   = ConvertDecimalToLong(value);
        long truncated = CastDecimalToLong(value);

        std::cout &amp;lt;&amp;lt; &quot;Rounded (std::lround): &quot; &amp;lt;&amp;lt; rounded &amp;lt;&amp;lt; &quot;\n&quot;;
        std::cout &amp;lt;&amp;lt; &quot;Truncated (static_cast&amp;lt;long&amp;gt;): &quot; &amp;lt;&amp;lt; truncated &amp;lt;&amp;lt; &quot;\n\n&quot;;
    }
};

int main() {
    // Example values to demonstrate behavior
    DecimalToLongProgram::ShowConversions(12.7);
    DecimalToLongProgram::ShowConversions(12.3);
    DecimalToLongProgram::ShowConversions(-5.8);
    DecimalToLongProgram::ShowConversions(42.0);   // already an integer
}



/*
run:

Input decimal: 12.7
Rounded (std::lround): 13
Truncated (static_cast&amp;lt;long&amp;gt;): 12

Input decimal: 12.3
Rounded (std::lround): 12
Truncated (static_cast&amp;lt;long&amp;gt;): 12

Input decimal: -5.8
Rounded (std::lround): -6
Truncated (static_cast&amp;lt;long&amp;gt;): -5

Input decimal: 42
Rounded (std::lround): 42
Truncated (static_cast&amp;lt;long&amp;gt;): 42

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100386/how-to-convert-a-decimal-to-a-long-in-c?show=100387#a100387</guid>
<pubDate>Thu, 06 Aug 2026 09:13:39 +0000</pubDate>
</item>
<item>
<title>Answered: How to convert a decimal to a long in C#</title>
<link>https://collectivesolver.com/100384/how-to-convert-a-decimal-to-a-long-in-c%23?show=100385#a100385</link>
<description>&lt;pre class=&quot;brush:csharp;&quot;&gt;using System;

/*
    ============================================================
    Convert a decimal to a long in C#.

    This program demonstrates:
      • Safe conversion using Convert.ToInt64()
      • Direct casting when the value is known to be in range
      • A helper function that performs the conversion and
        explains what happens internally.

    Notes:
      • decimal → long conversion requires the value to be within
        the range of Int64.
      • Convert.ToInt64() rounds to the nearest integer.
      • A direct cast (long)decimalValue truncates toward zero.
    ============================================================
*/

class DecimalToLongProgram
{
    // Converts a decimal to a long using the built‑in Convert class.
    // This method rounds the decimal to the nearest whole number.
    static long ConvertDecimalToLong(decimal value)
    {
        return Convert.ToInt64(value);
    }

    // Converts a decimal to a long using a direct cast.
    // This method truncates the decimal toward zero.
    static long CastDecimalToLong(decimal value)
    {
        return (long)value;
    }

    // Prints both conversion styles for comparison.
    static void ShowConversions(decimal value)
    {
        Console.WriteLine(&quot;Input decimal: &quot; + value);

        long rounded = ConvertDecimalToLong(value);
        long truncated = CastDecimalToLong(value);

        Console.WriteLine(&quot;Rounded (Convert.ToInt64): &quot; + rounded);
        Console.WriteLine(&quot;Truncated (cast to long): &quot; + truncated);
        Console.WriteLine();
    }

    static void Main()
    {
        // Example values to demonstrate behavior
        ShowConversions(12.7m);
        ShowConversions(12.3m);
        ShowConversions(-5.8m);
        ShowConversions(42m);   // already an integer
    }
}


/*
run:

Input decimal: 12.7
Rounded (Convert.ToInt64): 13
Truncated (cast to long): 12

Input decimal: 12.3
Rounded (Convert.ToInt64): 12
Truncated (cast to long): 12

Input decimal: -5.8
Rounded (Convert.ToInt64): -6
Truncated (cast to long): -5

Input decimal: 42
Rounded (Convert.ToInt64): 42
Truncated (cast to long): 42

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100384/how-to-convert-a-decimal-to-a-long-in-c%23?show=100385#a100385</guid>
<pubDate>Thu, 06 Aug 2026 09:01:48 +0000</pubDate>
</item>
<item>
<title>Answered: How to convert a decimal to a long in VB.NET</title>
<link>https://collectivesolver.com/100382/how-to-convert-a-decimal-to-a-long-in-vb-net?show=100383#a100383</link>
<description>&lt;pre class=&quot;brush:vb;&quot;&gt;Imports System

' ============================================================
' Convert a Decimal to a Long in VB.NET.
'
' This program demonstrates:
'   • Conversion using CLng(), which rounds to the nearest whole number.
'   • Conversion using a direct CType() cast, which truncates toward zero.
'   • A helper function that prints both results for comparison.
'
' Notes:
'   • Decimal → Long conversion requires the value to be within Int64 range.
'   • CLng() performs banker's rounding (to nearest even).
'   • CType(value, Long) truncates the fractional part.
' ============================================================

Module DecimalToLongProgram

    ' Converts a Decimal to a Long using CLng(), which rounds.
    Function ConvertDecimalToLong(value As Decimal) As Long
        Return CLng(value)
    End Function

    ' Converts a Decimal to a Long using CType(), which truncates.
    Function CastDecimalToLong(value As Decimal) As Long
        Return CType(value, Long)
    End Function

    ' Prints both conversion styles for comparison.
    Sub ShowConversions(value As Decimal)
        Console.WriteLine(&quot;Input decimal: &quot; &amp;amp; value)

        Dim rounded As Long = ConvertDecimalToLong(value)
        Dim truncated As Long = CastDecimalToLong(value)

        Console.WriteLine(&quot;Rounded (CLng): &quot; &amp;amp; rounded)
        Console.WriteLine(&quot;Truncated (CType): &quot; &amp;amp; truncated)
        Console.WriteLine()
    End Sub

    Sub Main()
        ' Example values to demonstrate behavior
        ShowConversions(12.7D)
        ShowConversions(12.3D)
        ShowConversions(-5.8D)
        ShowConversions(42D)   ' already an integer
    End Sub

End Module


' run:
'
' Input decimal: 12.7
' Rounded (CLng): 13
' Truncated (CType): 12
'
' Input decimal: 12.3
' Rounded (CLng): 12
' Truncated (CType): 12
'
' Input decimal: -5.8
' Rounded (CLng): -6
' Truncated (CType): -5
'
' Input decimal: 42
' Rounded (CLng): 42
' Truncated (CType): 42
'
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100382/how-to-convert-a-decimal-to-a-long-in-vb-net?show=100383#a100383</guid>
<pubDate>Thu, 06 Aug 2026 08:59:35 +0000</pubDate>
</item>
<item>
<title>Answered: How to generate a random 3×3 magic square in C</title>
<link>https://collectivesolver.com/100380/how-to-generate-a-random-3-3-magic-square-in-c?show=100381#a100381</link>
<description>&lt;pre class=&quot;brush:cpp;&quot;&gt;#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;stdlib.h&amp;gt;
#include &amp;lt;time.h&amp;gt;

#define N 3
#define CELLS (N * N)
#define MAX_MAGIC_SQUARES 8  /* exact count for digits 1-9 */

/* A square is stored as 9 ints in row-major order: index = row*3 + col */
typedef struct {
    int cell[CELLS];
} Square;

/* Advances 'arr' (length n) to the next lexicographic permutation in place.
 * Returns 1 if a next permutation exists, 0 if 'arr' was already the last
 * (fully descending) permutation. This is the standard constant-amortized
 * algorithm: find the rightmost ascent, find the smallest element to its
 * right that is still larger, swap, then reverse the suffix. */
int next_permutation(int *arr, int n) {
    int i = n - 2;
    while (i &amp;gt;= 0 &amp;amp;&amp;amp; arr[i] &amp;gt;= arr[i + 1]) {
        --i;
    }
    if (i &amp;lt; 0) {
        return 0; /* already the last permutation */
    }

    int j = n - 1;
    while (arr[j] &amp;lt;= arr[i]) {
        --j;
    }

    int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp;

    for (int lo = i + 1, hi = n - 1; lo &amp;lt; hi; ++lo, --hi) {
        tmp = arr[lo]; arr[lo] = arr[hi]; arr[hi] = tmp;
    }
    return 1;
}

/* Checks whether 'sq' is magic: every row, every column, and both
 * diagonals must sum to the same value. Returns 1 and writes that common
 * sum into *magic_sum if the square qualifies; returns 0 otherwise. */
int is_magic(const Square *sq, int *magic_sum) {
    int row_sum[N] = {0}, col_sum[N] = {0};
    int main_diag = 0, anti_diag = 0;

    for (int r = 0; r &amp;lt; N; ++r) {
        for (int c = 0; c &amp;lt; N; ++c) {
            int v = sq-&amp;gt;cell[r * N + c];
            row_sum[r] += v;
            col_sum[c] += v;
            if (r == c)         main_diag += v; /* top-left to bottom-right */
            if (r == N - 1 - c) anti_diag += v; /* top-right to bottom-left */
        }
    }

    *magic_sum = row_sum[0];
    for (int r = 0; r &amp;lt; N; ++r) if (row_sum[r] != *magic_sum) return 0;
    for (int c = 0; c &amp;lt; N; ++c) if (col_sum[c] != *magic_sum) return 0;
    return (main_diag == *magic_sum) &amp;amp;&amp;amp; (anti_diag == *magic_sum);
}

/* Enumerates all 9! = 362,880 permutations of {1,...,9} via
 * next_permutation (lexicographic order, no duplicates, no extra memory),
 * and collects every arrangement that forms a magic square into 'out'.
 * Returns the number of magic squares found. This exhaustive pass is
 * cheap: 362,880 iterations of O(1) work, well under a second at runtime. */
int collect_all_magic_squares(Square out[MAX_MAGIC_SQUARES]) {
    int current[CELLS];
    for (int i = 0; i &amp;lt; CELLS; ++i) {
        current[i] = i + 1; /* fill with 1..9 */
    }

    int count = 0;
    do {
        Square candidate;
        for (int i = 0; i &amp;lt; CELLS; ++i) {
            candidate.cell[i] = current[i];
        }
        int sum;
        if (is_magic(&amp;amp;candidate, &amp;amp;sum)) {
            if (count &amp;lt; MAX_MAGIC_SQUARES) {
                out[count++] = candidate;
            }
        }
    } while (next_permutation(current, CELLS));

    return count;
}

/* Prints a square in a readable grid layout, plus its magic sum. */
void print_square(const Square *sq) {
    for (int r = 0; r &amp;lt; N; ++r) {
        for (int c = 0; c &amp;lt; N; ++c) {
            printf(&quot;%d%c&quot;, sq-&amp;gt;cell[r * N + c], (c &amp;lt; N - 1) ? ' ' : '\n');
        }
    }
    int sum;
    is_magic(sq, &amp;amp;sum);
    printf(&quot;Magic sum per row/column/diagonal: %d\n&quot;, sum);
}

int main(void) {
    /* Step 1: build the full list of valid 3x3 magic squares (digits 1-9)
     * once. There are exactly 8, so a fixed-size array is sufficient and
     * avoids any dynamic memory management. */
    Square all_magic_squares[MAX_MAGIC_SQUARES];
    int count = collect_all_magic_squares(all_magic_squares);

    if (count == 0) {
        fprintf(stderr, &quot;No magic squares found (unexpected).\n&quot;);
        return 1;
    }

    /* Step 2: pick one uniformly at random. Seed the standard library's
     * pseudo-random generator once from the current time, then use
     * rand() with the classic scaling trick to get an unbiased index
     * in range [0, count). */
    srand((unsigned int)time(NULL));
    int index = rand() % count;
    const Square *chosen = &amp;amp;all_magic_squares[index];

    printf(&quot;Found %d valid 3x3 magic squares (digits 1-9).\n&quot;, count);
    printf(&quot;Randomly selected one:\n\n&quot;);
    print_square(chosen);

    return 0;
}


/*
run:

Found 8 valid 3x3 magic squares (digits 1-9).
Randomly selected one:

4 9 2
3 5 7
8 1 6
Magic sum per row/column/diagonal: 15

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100380/how-to-generate-a-random-3-3-magic-square-in-c?show=100381#a100381</guid>
<pubDate>Thu, 06 Aug 2026 06:37:23 +0000</pubDate>
</item>
<item>
<title>Answered: How to generate a random 3×3 magic square in C++</title>
<link>https://collectivesolver.com/100378/how-to-generate-a-random-3-3-magic-square-in-c?show=100379#a100379</link>
<description>&lt;pre class=&quot;brush:cpp;&quot;&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;
#include &amp;lt;array&amp;gt;
#include &amp;lt;algorithm&amp;gt; // next_permutation
#include &amp;lt;random&amp;gt;

// A square is stored as 9 cells in row-major order: index = row*3 + col
using Square = std::array&amp;lt;int, 9&amp;gt;;

// Checks whether a square is magic: every row, every column, and both
// diagonals must sum to the same value. Returns true and writes that
// common sum into magicSum if the square qualifies.
bool isMagic(const Square&amp;amp; sq, int&amp;amp; magicSum) {
    std::array&amp;lt;int, 3&amp;gt; rowSum{}, colSum{};
    int mainDiag = 0, antiDiag = 0;

    for (int r = 0; r &amp;lt; 3; ++r) {
        for (int c = 0; c &amp;lt; 3; ++c) {
            int v = sq[r * 3 + c];
            rowSum[r] += v;
            colSum[c] += v;
            if (r == c)     mainDiag += v; // top-left to bottom-right
            if (r == 2 - c) antiDiag += v; // top-right to bottom-left
        }
    }

    magicSum = rowSum[0];
    for (int r = 0; r &amp;lt; 3; ++r) if (rowSum[r] != magicSum) return false;
    for (int c = 0; c &amp;lt; 3; ++c) if (colSum[c] != magicSum) return false;
    
    return mainDiag == magicSum &amp;amp;&amp;amp; antiDiag == magicSum;
}

// Enumerates all 9! = 362,880 permutations of {1,...,9} using
// std::next_permutation (which generates permutations in lexicographic
// order with no duplicates and no extra bookkeeping), and collects every
// arrangement that forms a magic square. This exhaustive pass is cheap:
// 362,880 iterations, each doing O(1) work, comfortably fast at runtime.
std::vector&amp;lt;Square&amp;gt; collectAllMagicSquares() {
    std::vector&amp;lt;Square&amp;gt; results;
    results.reserve(8); // exactly 8 magic squares exist for digits 1-9

    Square current;
    std::iota(current.begin(), current.end(), 1); // fill with 1..9

    do {
        int sum;
        if (isMagic(current, sum)) {
            results.push_back(current);
        }
    } while (std::next_permutation(current.begin(), current.end()));

    return results;
}

// Prints a square in a readable grid layout, plus its magic sum.
void printSquare(const Square&amp;amp; sq) {
    for (int r = 0; r &amp;lt; 3; ++r) {
        for (int c = 0; c &amp;lt; 3; ++c) {
            std::cout &amp;lt;&amp;lt; sq[r * 3 + c] &amp;lt;&amp;lt; (c &amp;lt; 2 ? ' ' : '\n');
        }
    }
    int sum;
    isMagic(sq, sum);
    std::cout &amp;lt;&amp;lt; &quot;Magic sum per row/column/diagonal: &quot; &amp;lt;&amp;lt; sum &amp;lt;&amp;lt; '\n';
}

int main() {
    // Step 1: build the full list of valid 3x3 magic squares (digits 1-9) once.
    std::vector&amp;lt;Square&amp;gt; allMagicSquares = collectAllMagicSquares();

    if (allMagicSquares.empty()) {
        std::cerr &amp;lt;&amp;lt; &quot;No magic squares found (unexpected).\n&quot;;
        return 1;
    }

    // Step 2: pick one uniformly at random using a proper random engine
    // (Mersenne Twister seeded from a hardware entropy source), rather
    // than relying on rand()/srand().
    std::random_device rd;
    std::mt19937 rng(rd());
    std::uniform_int_distribution&amp;lt;std::size_t&amp;gt; dist(0, allMagicSquares.size() - 1);

    const Square&amp;amp; chosen = allMagicSquares[dist(rng)];

    std::cout &amp;lt;&amp;lt; &quot;Found &quot; &amp;lt;&amp;lt; allMagicSquares.size()
              &amp;lt;&amp;lt; &quot; valid 3x3 magic squares (digits 1-9).\n&quot;
              &amp;lt;&amp;lt; &quot;Randomly selected one:\n\n&quot;;
    printSquare(chosen);
}



/*
run:

Found 8 valid 3x3 magic squares (digits 1-9).
Randomly selected one:

6 1 8
7 5 3
2 9 4
Magic sum per row/column/diagonal: 15

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100378/how-to-generate-a-random-3-3-magic-square-in-c?show=100379#a100379</guid>
<pubDate>Thu, 06 Aug 2026 06:35:01 +0000</pubDate>
</item>
<item>
<title>Answered: How to generate a random 4×4 binary magic square (using only 0 and 1) in Java</title>
<link>https://collectivesolver.com/100376/how-to-generate-a-random-4-4-binary-magic-square-using-only-0-and-1-in-java?show=100377#a100377</link>
<description>&lt;pre class=&quot;brush:java;&quot;&gt;import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
    ============================================================
    Generate a random 4×4 binary magic square (0/1 only).

    A valid square must satisfy:
      • All rows have the same sum.
      • All columns have the same sum.
      • Both diagonals have that same sum.

    This class:
      1. Represents each 4×4 grid as a 16‑bit integer.
      2. Converts each mask into a 4×4 square.
      3. Checks whether it is magic.
      4. Collects all valid squares.
      5. Chooses one uniformly at random.
    ============================================================
*/

public class RandomBinaryMagicSquare {

    // A square is stored as 16 cells in row-major order: index = row*4 + col
    static class Square {
        int[] cells = new int[16];
    }

    // Builds a 4×4 square from a 16-bit mask
    static Square buildSquareFromMask(int mask) {
        Square sq = new Square();
        for (int i = 0; i &amp;lt; 16; i++) {
            sq.cells[i] = (mask &amp;gt;&amp;gt; i) &amp;amp; 1;
        }
        return sq;
    }

    // Checks whether a square is magic
    static boolean isMagic(Square sq, int[] magicSumOut) {
        int[] rowSum = new int[4];
        int[] colSum = new int[4];
        int mainDiag = 0;
        int antiDiag = 0;

        // Compute row sums, column sums, and diagonals
        for (int r = 0; r &amp;lt; 4; r++) {
            for (int c = 0; c &amp;lt; 4; c++) {
                int v = sq.cells[r * 4 + c];
                rowSum[r] += v;
                colSum[c] += v;

                if (r == c) mainDiag += v;
                if (r == 3 - c) antiDiag += v;
            }
        }

        int magicSum = rowSum[0];
        magicSumOut[0] = magicSum;

        // All rows must match the magic sum
        for (int r = 0; r &amp;lt; 4; r++)
            if (rowSum[r] != magicSum) return false;

        // All columns must match the magic sum
        for (int c = 0; c &amp;lt; 4; c++)
            if (colSum[c] != magicSum) return false;

        // Both diagonals must match the magic sum
        return mainDiag == magicSum &amp;amp;&amp;amp; antiDiag == magicSum;
    }

    // Scans all 65,536 possible 4×4 binary grids and collects the magic ones
    static List&amp;lt;Square&amp;gt; collectAllMagicSquares() {
        List&amp;lt;Square&amp;gt; results = new ArrayList&amp;lt;&amp;gt;(4096);

        for (int mask = 0; mask &amp;lt; 65536; mask++) {
            Square sq = buildSquareFromMask(mask);
            int[] sum = new int[1];
            if (isMagic(sq, sum)) {
                results.add(sq);
            }
        }

        return results;
    }

    // Prints a square in a readable grid layout
    static void printSquare(Square sq) {
        int[] sum = new int[1];
        isMagic(sq, sum);

        for (int r = 0; r &amp;lt; 4; r++) {
            for (int c = 0; c &amp;lt; 4; c++) {
                System.out.print(sq.cells[r * 4 + c] + &quot; &quot;);
            }
            System.out.println();
        }

        System.out.println(&quot;Magic sum: &quot; + sum[0]);
    }

    public static void main(String[] args) {
        // Step 1: collect all valid magic squares
        List&amp;lt;Square&amp;gt; allMagicSquares = collectAllMagicSquares();

        if (allMagicSquares.isEmpty()) {
            System.out.println(&quot;No magic squares found.&quot;);
            return;
        }

        // Step 2: pick one uniformly at random
        Random rng = new Random();
        Square chosen = allMagicSquares.get(rng.nextInt(allMagicSquares.size()));

        System.out.println(&quot;Found &quot; + allMagicSquares.size() + &quot; valid 4×4 binary magic squares.&quot;);
        System.out.println(&quot;Randomly selected one:\n&quot;);

        printSquare(chosen);
    }
}



/*
run:

Found 34 valid 4?4 binary magic squares.
Randomly selected one:

1 0 1 1 
1 1 1 0 
1 1 0 1 
0 1 1 1 
Magic sum: 3

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100376/how-to-generate-a-random-4-4-binary-magic-square-using-only-0-and-1-in-java?show=100377#a100377</guid>
<pubDate>Thu, 06 Aug 2026 06:16:47 +0000</pubDate>
</item>
<item>
<title>Answered: How to generate a random 4×4 binary magic square (using only 0 and 1) in Pascal</title>
<link>https://collectivesolver.com/100374/how-to-generate-a-random-4-4-binary-magic-square-using-only-0-and-1-in-pascal?show=100375#a100375</link>
<description>&lt;pre class=&quot;brush:delphi;&quot;&gt;program RandomBinaryMagicSquare;

{
    ============================================================
    Generate a random 4×4 binary magic square (0/1 only).

    A valid square must satisfy:
      • All rows have the same sum.
      • All columns have the same sum.
      • Both diagonals have that same sum.

    This program:
      1. Represents each 4×4 grid as a 16‑bit integer.
      2. Converts each mask into a 4×4 square.
      3. Checks whether it is magic.
      4. Collects all valid squares.
      5. Chooses one uniformly at random.
    ============================================================
}

type
    TSquare = array[0..15] of Integer;

{ Build a square from a 16‑bit mask }
procedure BuildSquareFromMask(mask: Word; var sq: TSquare);
var
    i: Integer;
begin
    for i := 0 to 15 do
        sq[i] := (mask shr i) and 1;
end;

{ Check whether a square is magic }
function IsMagic(const sq: TSquare; var magicSum: Integer): Boolean;
var
    rowSum, colSum: array[0..3] of Integer;
    r, c, v: Integer;
    mainDiag, antiDiag: Integer;
begin
    for r := 0 to 3 do rowSum[r] := 0;
    for c := 0 to 3 do colSum[c] := 0;

    mainDiag := 0;
    antiDiag := 0;

    for r := 0 to 3 do
        for c := 0 to 3 do
        begin
            v := sq[r * 4 + c];
            rowSum[r] := rowSum[r] + v;
            colSum[c] := colSum[c] + v;

            if r = c then
                mainDiag := mainDiag + v;

            if r = 3 - c then
                antiDiag := antiDiag + v;
        end;

    magicSum := rowSum[0];

    for r := 0 to 3 do
        if rowSum[r] &amp;lt;&amp;gt; magicSum then
        begin
            IsMagic := False;
            Exit;
        end;

    for c := 0 to 3 do
        if colSum[c] &amp;lt;&amp;gt; magicSum then
        begin
            IsMagic := False;
            Exit;
        end;

    IsMagic := (mainDiag = magicSum) and (antiDiag = magicSum);
end;

{ Collect all magic squares }
function CollectAllMagicSquares(var outList: array of TSquare): Integer;
var
    mask: Word;
    sq: TSquare;
    sum: Integer;
    count, i: Integer;
begin
    count := 0;

    for mask := 0 to 65535 do
    begin
        BuildSquareFromMask(mask, sq);
        if IsMagic(sq, sum) then
        begin
            for i := 0 to 15 do
                outList[count][i] := sq[i];
            Inc(count);
        end;
    end;

    CollectAllMagicSquares := count;
end;

{ Print a square }
procedure PrintSquare(const sq: TSquare);
var
    r, c: Integer;
    sum: Integer;
begin
    for r := 0 to 3 do
    begin
        for c := 0 to 3 do
            Write(sq[r * 4 + c], ' ');
        Writeln;
    end;

    IsMagic(sq, sum);
    Writeln('Magic sum: ', sum);
end;

var
    allSquares: array[0..4095] of TSquare;
    count, idx: Integer;

begin
    Randomize;

    count := CollectAllMagicSquares(allSquares);

    if count = 0 then
    begin
        Writeln('No magic squares found.');
        Halt(1);
    end;

    idx := Random(count);

    Writeln('Found ', count, ' valid 4×4 binary magic squares.');
    Writeln('Randomly selected one:');
    Writeln;

    PrintSquare(allSquares[idx]);
end.


{
run:

Found 34 valid 4×4 binary magic squares.
Randomly selected one:

1 1 0 0 
1 0 1 0 
0 1 0 1 
0 0 1 1 
Magic sum: 2

}
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100374/how-to-generate-a-random-4-4-binary-magic-square-using-only-0-and-1-in-pascal?show=100375#a100375</guid>
<pubDate>Thu, 06 Aug 2026 06:12:38 +0000</pubDate>
</item>
<item>
<title>Answered: How to generate a random 4×4 binary magic square (using only 0 and 1) in C</title>
<link>https://collectivesolver.com/100370/how-to-generate-a-random-4-4-binary-magic-square-using-only-0-and-1-in-c?show=100373#a100373</link>
<description>&lt;pre class=&quot;brush:cpp;&quot;&gt;#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;stdlib.h&amp;gt;
#include &amp;lt;time.h&amp;gt;

/*
    ============================================================
    Generate a random 4×4 binary magic square (0/1 only).

    A valid square must satisfy:
      • All rows have the same sum.
      • All columns have the same sum.
      • Both diagonals have that same sum.

    This program:
      1. Represents each 4×4 grid as a 16‑bit integer.
      2. Converts each mask into a 4×4 square.
      3. Checks whether it is magic.
      4. Collects all valid squares.
      5. Chooses one uniformly at random.
    ============================================================
*/

typedef int Square[16];   /* 16 cells, row‑major order */

/* Build a square from a 16‑bit mask */
void buildSquareFromMask(unsigned mask, Square sq) {
    for (int i = 0; i &amp;lt; 16; ++i)
        sq[i] = (mask &amp;gt;&amp;gt; i) &amp;amp; 1;
}

/* Check whether a square is magic */
int isMagic(const Square sq, int *magicSum) {
    int rowSum[4] = {0}, colSum[4] = {0};
    int mainDiag = 0, antiDiag = 0;

    for (int r = 0; r &amp;lt; 4; ++r) {
        for (int c = 0; c &amp;lt; 4; ++c) {
            int v = sq[r * 4 + c];
            rowSum[r] += v;
            colSum[c] += v;
            if (r == c)         mainDiag += v;
            if (r == 3 - c)     antiDiag += v;
        }
    }

    *magicSum = rowSum[0];

    for (int r = 0; r &amp;lt; 4; ++r)
        if (rowSum[r] != *magicSum) return 0;

    for (int c = 0; c &amp;lt; 4; ++c)
        if (colSum[c] != *magicSum) return 0;

    return (mainDiag == *magicSum &amp;amp;&amp;amp; antiDiag == *magicSum);
}

/* Collect all magic squares */
int collectAllMagicSquares(Square *out) {
    int count = 0;

    for (unsigned mask = 0; mask &amp;lt; 65536u; ++mask) {
        Square sq;
        buildSquareFromMask(mask, sq);

        int sum;
        if (isMagic(sq, &amp;amp;sum)) {
            for (int i = 0; i &amp;lt; 16; ++i)
                out[count][i] = sq[i];
            count++;
        }
    }

    return count;
}

/* Print a square */
void printSquare(const Square sq) {
    int sum;
    isMagic(sq, &amp;amp;sum);

    for (int r = 0; r &amp;lt; 4; ++r) {
        for (int c = 0; c &amp;lt; 4; ++c)
            printf(&quot;%d &quot;, sq[r * 4 + c]);
        printf(&quot;\n&quot;);
    }

    printf(&quot;Magic sum: %d\n&quot;, sum);
}

int main() {
    /* Collect all valid magic squares */
    Square all[4096];
    int count = collectAllMagicSquares(all);

    if (count == 0) {
        printf(&quot;No magic squares found.\n&quot;);
        return 1;
    }

    /* Choose one at random */
    srand((unsigned)time(NULL));
    int idx = rand() % count;

    printf(&quot;Found %d valid 4×4 binary magic squares.\n&quot;, count);
    printf(&quot;Randomly selected one:\n\n&quot;);

    printSquare(all[idx]);

    return 0;
}


/*
run:

Found 34 valid 4×4 binary magic squares.
Randomly selected one:

0 1 0 1 
0 1 0 1 
1 0 1 0 
1 0 1 0 
Magic sum: 2

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100370/how-to-generate-a-random-4-4-binary-magic-square-using-only-0-and-1-in-c?show=100373#a100373</guid>
<pubDate>Thu, 06 Aug 2026 05:38:58 +0000</pubDate>
</item>
<item>
<title>Answered: How to generate a random 4×4 binary magic square (using only 0 and 1) in C++</title>
<link>https://collectivesolver.com/100368/how-to-generate-a-random-4-4-binary-magic-square-using-only-0-and-1-in-c?show=100372#a100372</link>
<description>&lt;pre class=&quot;brush:cpp;&quot;&gt;#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;
#include &amp;lt;array&amp;gt;
#include &amp;lt;random&amp;gt;

// A square is stored as 16 cells in row-major order: index = row*4 + col
using Square = std::array&amp;lt;int, 16&amp;gt;;

// Builds a 4x4 square from a 16-bit mask: bit i becomes cell i (0 or 1).
Square buildSquareFromMask(unsigned mask) {
    Square sq{};
    for (int i = 0; i &amp;lt; 16; ++i) {
        sq[i] = (mask &amp;gt;&amp;gt; i) &amp;amp; 1;
    }
    
    return sq;
}

// Checks whether a square is &quot;magic&quot;: every row, every column, and both
// diagonals must all sum to the same value. Returns true and writes that
// common sum into magicSum if the square qualifies.
bool isMagic(const Square&amp;amp; sq, int&amp;amp; magicSum) {
    std::array&amp;lt;int, 4&amp;gt; rowSum{}, colSum{};
    int mainDiag = 0, antiDiag = 0;

    for (int r = 0; r &amp;lt; 4; ++r) {
        for (int c = 0; c &amp;lt; 4; ++c) {
            int v = sq[r * 4 + c];
            rowSum[r] += v;
            colSum[c] += v;
            if (r == c)         mainDiag += v; // top-left to bottom-right
            if (r == 3 - c)     antiDiag += v; // top-right to bottom-left
        }
    }

    magicSum = rowSum[0];
    for (int r = 0; r &amp;lt; 4; ++r) if (rowSum[r] != magicSum) return false;
    for (int c = 0; c &amp;lt; 4; ++c) if (colSum[c] != magicSum) return false;
    
    return mainDiag == magicSum &amp;amp;&amp;amp; antiDiag == magicSum;
}

// Scans all 65,536 possible 4x4 binary grids and collects every one that
// satisfies the magic-square property. This exhaustive pass is cheap
// (constant-size, ~2^16 iterations) and guarantees we know the full
// population to sample from uniformly.
std::vector&amp;lt;Square&amp;gt; collectAllMagicSquares() {
    std::vector&amp;lt;Square&amp;gt; results;
    results.reserve(4096); // rough headroom; avoids repeated reallocations

    for (unsigned mask = 0; mask &amp;lt; 65536u; ++mask) {
        Square candidate = buildSquareFromMask(mask);
        int sum;
        if (isMagic(candidate, sum)) {
            results.push_back(candidate);
        }
    }
    
    return results;
}

// Prints a square in a readable grid layout, plus its magic sum.
void printSquare(const Square&amp;amp; sq) {
    for (int r = 0; r &amp;lt; 4; ++r) {
        for (int c = 0; c &amp;lt; 4; ++c) {
            std::cout &amp;lt;&amp;lt; sq[r * 4 + c] &amp;lt;&amp;lt; (c &amp;lt; 3 ? ' ' : '\n');
        }
    }
    int sum;
    isMagic(sq, sum);
    std::cout &amp;lt;&amp;lt; &quot;Magic sum per row/column/diagonal: &quot; &amp;lt;&amp;lt; sum &amp;lt;&amp;lt; '\n';
}

int main() {
    // Step 1: build the full list of valid 4x4 binary magic squares once.
    std::vector&amp;lt;Square&amp;gt; allMagicSquares = collectAllMagicSquares();

    if (allMagicSquares.empty()) {
        std::cerr &amp;lt;&amp;lt; &quot;No magic squares found (unexpected).\n&quot;;
        return 1;
    }

    // Step 2: pick one uniformly at random using a proper random engine
    // (Mersenne Twister seeded from a hardware entropy source), rather
    // than relying on rand()/srand().
    std::random_device rd;
    std::mt19937 rng(rd());
    std::uniform_int_distribution&amp;lt;std::size_t&amp;gt; dist(0, allMagicSquares.size() - 1);

    const Square&amp;amp; chosen = allMagicSquares[dist(rng)];

    std::cout &amp;lt;&amp;lt; &quot;Found &quot; &amp;lt;&amp;lt; allMagicSquares.size()
              &amp;lt;&amp;lt; &quot; valid 4x4 binary magic squares.\n&quot;
              &amp;lt;&amp;lt; &quot;Randomly selected one:\n\n&quot;;
    printSquare(chosen);
}


/*
run:

Found 34 valid 4x4 binary magic squares.
Randomly selected one:

1 0 0 1
0 1 1 0
1 0 0 1
0 1 1 0
Magic sum per row/column/diagonal: 2

*/
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100368/how-to-generate-a-random-4-4-binary-magic-square-using-only-0-and-1-in-c?show=100372#a100372</guid>
<pubDate>Thu, 06 Aug 2026 05:33:07 +0000</pubDate>
</item>
<item>
<title>Answered: How to generate a random 4×4 binary magic square (using only 0 and 1) in Ruby</title>
<link>https://collectivesolver.com/100366/how-to-generate-a-random-4-4-binary-magic-square-using-only-0-and-1-in-ruby?show=100367#a100367</link>
<description>&lt;pre class=&quot;brush:ruby;&quot;&gt;# ============================================================
# Generate a random 4×4 magic square containing only 0 and 1.
#
# A valid square must satisfy:
#   • All rows sum to the same target value.
#   • All columns sum to that same target value.
#   • Both diagonals also match that target value.
#
# The program:
#   1. Precomputes all 4‑bit binary rows.
#   2. Groups rows by their sum.
#   3. Generates *all* valid magic squares.
#   4. Picks one at random.
# ============================================================

# Generate all binary rows of length 4
def binary_rows
  (0..15).map { |n| &quot;%04b&quot; % n }.map { |s| s.chars.map(&amp;amp;:to_i) }
end

# Group rows by their sum
ROWS_BY_SUM = binary_rows.group_by(&amp;amp;:sum)

# Generate all magic squares
def generate_all_magic_squares
  results = []

  (0..4).each do |target|
    candidate_rows = ROWS_BY_SUM[target]

    square   = []
    col_sums = [0, 0, 0, 0]

    build = lambda do |row_index|
      if row_index == 4
        main_diag = square[0][0] + square[1][1] + square[2][2] + square[3][3]
        anti_diag = square[0][3] + square[1][2] + square[2][1] + square[3][0]

        if main_diag == target &amp;amp;&amp;amp; anti_diag == target
          results &amp;lt;&amp;lt; square.map(&amp;amp;:dup)
        end
        return
      end

      candidate_rows.each do |row|
        feasible = true
        4.times do |c|
          if col_sums[c] + row[c] &amp;gt; target
            feasible = false
            break
          end
        end
        next unless feasible

        square &amp;lt;&amp;lt; row
        old_cols = col_sums.dup
        4.times { |c| col_sums[c] += row[c] }

        build.call(row_index + 1)

        square.pop
        col_sums.replace(old_cols)
      end
    end

    build.call(0)
  end

  results
end

# Pick a random magic square
all_squares = generate_all_magic_squares
random_square = all_squares.sample

puts &quot;Random 4×4 binary magic square:&quot;
random_square.each { |row| puts row.join(&quot; &quot;) }



# run:
#
# Random 4×4 binary magic square:
# 1 0 0 1
# 0 1 1 0
# 1 0 0 1
# 0 1 1 0
#

&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100366/how-to-generate-a-random-4-4-binary-magic-square-using-only-0-and-1-in-ruby?show=100367#a100367</guid>
<pubDate>Wed, 05 Aug 2026 15:48:41 +0000</pubDate>
</item>
<item>
<title>Answered: How to generate all 4×4 binary magic squares (using only 0 and 1) in Ruby</title>
<link>https://collectivesolver.com/100364/how-to-generate-all-4-4-binary-magic-squares-using-only-0-and-1-in-ruby?show=100365#a100365</link>
<description>&lt;pre class=&quot;brush:ruby;&quot;&gt;# ============================================================
# Generate all 4x4 magic squares containing only 0 and 1.
# A &quot;magic square&quot; here means:
#   - All rows sum to the same target
#   - All columns sum to the same target
#   - Both diagonals also sum to that same target
#
# Because entries are only 0 or 1, the row/column sums can only
# be 0, 1, 2, 3, or 4. We try all possibilities.
#
# The algorithm:
#   1. Precompute all 4‑element binary rows and group them by sum.
#   2. For each possible magic sum S:
#        - Build all 4‑row combinations whose row sums are S.
#        - Prune early by checking column sums as rows are added.
#        - When 4 rows are placed, check diagonals.
#   3. Collect and print all valid squares.
#
# This avoids brute‑forcing all 2^16 grids and instead uses
# structured pruning, which is dramatically faster.
# ============================================================

# Generate all binary rows of length 4
ROWS = (0..15).map { |n| &quot;%04b&quot; % n }.map { |s| s.chars.map(&amp;amp;:to_i) }

# Group rows by their sum
ROWS_BY_SUM = ROWS.group_by { |r| r.sum }

# Store results
magic_squares = []

# Try all possible magic sums
(0..4).each do |target_sum|
  candidate_rows = ROWS_BY_SUM[target_sum]

  # Backtracking search
  build = []

  # Column accumulator
  col_sums = [0, 0, 0, 0]

  # Recursive function to assemble rows
  define_method(:place_row) do |idx|
    # If 4 rows placed, check diagonals
    if idx == 4
      main_diag = build[0][0] + build[1][1] + build[2][2] + build[3][3]
      anti_diag = build[0][3] + build[1][2] + build[2][1] + build[3][0]
      if main_diag == target_sum &amp;amp;&amp;amp; anti_diag == target_sum
        magic_squares &amp;lt;&amp;lt; build.map(&amp;amp;:dup)
      end
      return
    end

    candidate_rows.each do |row|
      # Try placing this row
      valid = true

      # Update column sums and prune early
      4.times do |c|
        new_sum = col_sums[c] + row[c]
        # If column exceeds target sum, prune
        if new_sum &amp;gt; target_sum
          valid = false
          break
        end
      end

      next unless valid

      # Apply row
      build &amp;lt;&amp;lt; row
      old_cols = col_sums.dup
      4.times { |c| col_sums[c] += row[c] }

      # Continue
      place_row(idx + 1)

      # Undo row
      build.pop
      col_sums.replace(old_cols)
    end
  end

  place_row(0)
end

# Print results
magic_squares.each_with_index do |sq, i|
  puts &quot;Magic square ##{i + 1}:&quot;
  sq.each { |row| puts row.join(&quot; &quot;) }
  puts
end



# run:
#
# Magic square #1:
# 0 0 0 0
# 0 0 0 0
# 0 0 0 0
# 0 0 0 0
#
# Magic square #2:
# 0 0 0 1
# 0 1 0 0
# 1 0 0 0
# 0 0 1 0
#
# Magic square #3:
# 0 0 0 1
# 1 0 0 0
# 0 0 1 0
# 0 1 0 0
#
# Magic square #4:
# 0 0 1 0
# 0 1 0 0
# 0 0 0 1
# 1 0 0 0
#
# Magic square #5:
# 0 0 1 0
# 1 0 0 0
# 0 1 0 0
# 0 0 0 1
#
# Magic square #6:
# 0 1 0 0
# 0 0 0 1
# 0 0 1 0
# 1 0 0 0
#
# Magic square #7:
# 0 1 0 0
# 0 0 1 0
# 1 0 0 0
# 0 0 0 1
#
# Magic square #8:
# 1 0 0 0
# 0 0 0 1
# 0 1 0 0
# 0 0 1 0
#
# Magic square #9:
# 1 0 0 0
# 0 0 1 0
# 0 0 0 1
# 0 1 0 0
#
# Magic square #10:
# 0 0 1 1
# 0 1 0 1
# 1 0 1 0
# 1 1 0 0
#
# Magic square #11:
# 0 0 1 1
# 1 1 0 0
# 0 0 1 1
# 1 1 0 0
#
# Magic square #12:
# 0 0 1 1
# 1 1 0 0
# 1 1 0 0
# 0 0 1 1
#
# Magic square #13:
# 0 1 0 1
# 0 1 0 1
# 1 0 1 0
# 1 0 1 0
#
# Magic square #14:
# 0 1 0 1
# 1 0 1 0
# 1 0 1 0
# 0 1 0 1
#
# Magic square #15:
# 0 1 0 1
# 1 1 0 0
# 0 0 1 1
# 1 0 1 0
#
# Magic square #16:
# 0 1 1 0
# 0 1 1 0
# 1 0 0 1
# 1 0 0 1
#
# Magic square #17:
# 0 1 1 0
# 1 0 0 1
# 0 1 1 0
# 1 0 0 1
#
# Magic square #18:
# 1 0 0 1
# 0 1 1 0
# 1 0 0 1
# 0 1 1 0
#
# Magic square #19:
# 1 0 0 1
# 1 0 0 1
# 0 1 1 0
# 0 1 1 0
#
# Magic square #20:
# 1 0 1 0
# 0 0 1 1
# 1 1 0 0
# 0 1 0 1

# Magic square #21:
# 1 0 1 0
# 0 1 0 1
# 0 1 0 1
# 1 0 1 0
#
# Magic square #22:
# 1 0 1 0
# 1 0 1 0
# 0 1 0 1
# 0 1 0 1
#
# Magic square #23:
# 1 1 0 0
# 0 0 1 1
# 0 0 1 1
# 1 1 0 0

# Magic square #24:
# 1 1 0 0
# 0 0 1 1
# 1 1 0 0
# 0 0 1 1
#
# Magic square #25:
# 1 1 0 0
# 1 0 1 0
# 0 1 0 1
# 0 0 1 1
#
# Magic square #26:
# 0 1 1 1
# 1 1 0 1
# 1 1 1 0
# 1 0 1 1
#
# Magic square #27:
# 0 1 1 1
# 1 1 1 0
# 1 0 1 1
# 1 1 0 1
#
# Magic square #28:
# 1 0 1 1
# 1 1 0 1
# 0 1 1 1
# 1 1 1 0
#
# Magic square #29:
# 1 0 1 1
# 1 1 1 0
# 1 1 0 1
# 0 1 1 1
#
# Magic square #30:
# 1 1 0 1
# 0 1 1 1
# 1 0 1 1
# 1 1 1 0
#
# Magic square #31:
# 1 1 0 1
# 1 0 1 1
# 1 1 1 0
# 0 1 1 1
#
# Magic square #32:
# 1 1 1 0
# 0 1 1 1
# 1 1 0 1
# 1 0 1 1
#
# Magic square #33:
# 1 1 1 0
# 1 0 1 1
# 0 1 1 1
# 1 1 0 1
#
# Magic square #34:
# 1 1 1 1
# 1 1 1 1
# 1 1 1 1
# 1 1 1 1
#
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100364/how-to-generate-all-4-4-binary-magic-squares-using-only-0-and-1-in-ruby?show=100365#a100365</guid>
<pubDate>Wed, 05 Aug 2026 15:37:38 +0000</pubDate>
</item>
<item>
<title>Answered: How to check whether a matrix is a magic square or not in Ruby</title>
<link>https://collectivesolver.com/100362/how-to-check-whether-a-matrix-is-a-magic-square-or-not-in-ruby?show=100363#a100363</link>
<description>&lt;pre class=&quot;brush:ruby;&quot;&gt;# This program checks whether a square matrix is a magic square.
# A magic square has:
#   1. All rows summing to the same value
#   2. All columns summing to the same value
#   3. Both main diagonals summing to that same value
#   4. The matrix must be square

# Compute the sum of each row
def row_sums(matrix)
  matrix.map { |row| row.sum }
end

# Compute the sum of each column
def column_sums(matrix)
  size = matrix.size
  (0...size).map { |col| matrix.map { |row| row[col] }.sum }
end

# Compute the two diagonal sums
def diagonal_sums(matrix)
  size = matrix.size
  main_diag     = (0...size).map { |i| matrix[i][i] }.sum
  secondary_diag = (0...size).map { |i| matrix[i][size - 1 - i] }.sum
  [main_diag, secondary_diag]
end

# Check whether the matrix is a magic square
def magic_square?(matrix)
  return false if matrix.empty?
  return false unless matrix.all? { |row| row.size == matrix.size }

  target = matrix[0].sum

  return false unless row_sums(matrix).all? { |s| s == target }
  return false unless column_sums(matrix).all? { |s| s == target }

  diag1, diag2 = diagonal_sums(matrix)
  return false unless diag1 == target &amp;amp;&amp;amp; diag2 == target

  true
end

# Matrix
matrix = [
  [8, 1, 6],
  [3, 5, 7],
  [4, 9, 2]
]

puts &quot;Matrix:&quot;
matrix.each { |row| p row }

puts &quot;\nIs magic square? #{magic_square?(matrix)}&quot;


=begin
run:

Matrix:
[8, 1, 6]
[3, 5, 7]
[4, 9, 2]

Is magic square? true

=end
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100362/how-to-check-whether-a-matrix-is-a-magic-square-or-not-in-ruby?show=100363#a100363</guid>
<pubDate>Wed, 05 Aug 2026 15:25:01 +0000</pubDate>
</item>
<item>
<title>Answered: How to implement the merge sort algorithm in Python</title>
<link>https://collectivesolver.com/100360/how-to-implement-the-merge-sort-algorithm-in-python?show=100361#a100361</link>
<description>&lt;pre class=&quot;brush:python;&quot;&gt;# Merge sort implementation in Python.
# The algorithm works by:
#   1. Recursively splitting the list into two halves.
#   2. Sorting each half.
#   3. Merging the two sorted halves into one sorted list.
#
# This approach guarantees O(n log n) time complexity and stable sorting.

def merge(left, right):
    &quot;&quot;&quot;
    Merge two sorted lists into one sorted list.
    The function walks through both lists and picks the smallest
    available element each time.
    &quot;&quot;&quot;
    merged = []
    i = j = 0

    # Compare elements from both lists and append the smaller one
    while i &amp;lt; len(left) and j &amp;lt; len(right):
        if left[i] &amp;lt;= right[j]:
            merged.append(left[i])
            i += 1
        else:
            merged.append(right[j])
            j += 1

    # Append any remaining elements
    merged.extend(left[i:])
    merged.extend(right[j:])

    return merged


def merge_sort(arr):
    &quot;&quot;&quot;
    Recursively sort a list using merge sort.
    If the list has length 0 or 1, it is already sorted.
    Otherwise, split it, sort each half, and merge.
    &quot;&quot;&quot;
    if len(arr) &amp;lt;= 1:
        return arr

    mid = len(arr) // 2
    left_sorted = merge_sort(arr[:mid])
    right_sorted = merge_sort(arr[mid:])

    return merge(left_sorted, right_sorted)


if __name__ == &quot;__main__&quot;:
    data = [38, 27, 43, 3, 9, 82, 10]
    result = merge_sort(data)

    print(&quot;Original:&quot;, data)
    print(&quot;Sorted:&quot;, result)



&quot;&quot;&quot;
run:

Original: [38, 27, 43, 3, 9, 82, 10]
Sorted: [3, 9, 10, 27, 38, 43, 82]

&quot;&quot;&quot;
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
<guid isPermaLink="true">https://collectivesolver.com/100360/how-to-implement-the-merge-sort-algorithm-in-python?show=100361#a100361</guid>
<pubDate>Wed, 05 Aug 2026 15:06:22 +0000</pubDate>
</item>
<item>
<title>How to search a string using bitwise operators C</title>
<link>https://collectivesolver.com/100358/how-to-search-a-string-using-bitwise-operators-c</link>
<description></description>
<guid isPermaLink="true">https://collectivesolver.com/100358/how-to-search-a-string-using-bitwise-operators-c</guid>
<pubDate>Wed, 05 Aug 2026 09:47:43 +0000</pubDate>
</item>
<item>
<title>How to search a string using bitwise operators C++</title>
<link>https://collectivesolver.com/100356/how-to-search-a-string-using-bitwise-operators-c</link>
<description></description>
<guid isPermaLink="true">https://collectivesolver.com/100356/how-to-search-a-string-using-bitwise-operators-c</guid>
<pubDate>Wed, 05 Aug 2026 09:33:49 +0000</pubDate>
</item>
<item>
<title>How to calculate the volume of a cube in Swift</title>
<link>https://collectivesolver.com/100354/how-to-calculate-the-volume-of-a-cube-in-swift</link>
<description></description>
<guid isPermaLink="true">https://collectivesolver.com/100354/how-to-calculate-the-volume-of-a-cube-in-swift</guid>
<pubDate>Tue, 04 Aug 2026 15:40:17 +0000</pubDate>
</item>
</channel>
</rss>