- Jen heir rick
- Aug 4, 2004
-
when a woman says something's not funny, you better not laugh your ass off
|
I love this so much, especially because it doesn't even work if you execute it on a German Windows
So here is the correct version that is actually safe to deploy internationally
code:
string decimalSeparator = Directory.Exists("C:\\Programme") ? "," : ".";
is_odd = (number / 2).ToString().Contains(decimalSeparator);
You can also set the current culture to en-us:
code:System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("EN-US");
is_odd = (number / 2).ToString().Contains(decimalSeparator);
I see no downsides.
|
#
?
Mar 7, 2024 23:14
|
|
- Adbot
-
ADBOT LOVES YOU
|
|
#
?
Jun 8, 2024 08:59
|
|
- OddObserver
- Apr 3, 2009
-
|
You can also set the current culture to en-us:
code:System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("EN-US");
is_odd = (number / 2).ToString().Contains(decimalSeparator);
I see no downsides.
Well, it's plausibly threadsafe, making it less appropriate for this thread. It needs to be rewritten using getting/putenv.
|
#
?
Mar 7, 2024 23:38
|
|
- McGlockenshire
- Dec 16, 2005
-
GOLLOCKS!
|
I imagine there must be a way of writing the mapping in a way that's actually readable and reviewable?
This article breaks down how the whole thing works, simplifies it, and then offers a much more sane approach to the whole problem at the end.
|
#
?
Mar 8, 2024 00:27
|
|
- GABA ghoul
- Oct 29, 2011
-
|
You can also set the current culture to en-us:
code:System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("EN-US");
is_odd = (number / 2).ToString().Contains(decimalSeparator);
I see no downsides.
Totally agree. Just think of all the types of exciting heisenbugs you can generate when one or two out of 30+ threads in the System.Threading thread pool suddenly have a different culture from the rest(but only occasionally, because of the random life time of a pool thread of anything between milliseconds and forever). It could drive developers insane for months trying to diagnose this
|
#
?
Mar 8, 2024 10:25
|
|
- Bruegels Fuckbooks
- Sep 14, 2004
-
Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.
|
I love this so much, especially because it doesn't even work if you execute it on a German Windows
So here is the correct version that is actually safe to deploy internationally
code:
string decimalSeparator = Directory.Exists("C:\\Programme") ? "," : ".";
is_odd = (number / 2).ToString().Contains(decimalSeparator);
many years ago i used to work as a localization qa tester. did you know the decimal separator is actually a user setting in windows? bugcount go brrr....
quote:
Well, it's plausibly threadsafe, making it less appropriate for this thread. It needs to be rewritten using getting/putenv.
lmao
https://learn.microsoft.com/en-us/dotnet/api/system.threading.thread.currentculture?view=net-8.0
quote:
The CurrentCulture property doesn't work reliably when used with any thread other than the current thread. In .NET Framework, reading the property is reliable, although setting it for a thread other than the current thread is not. On .NET Core, an InvalidOperationException is thrown if a thread attempts to read or write the CurrentCulture property on a different thread. We recommend that you use the CultureInfo.CurrentCulture property to retrieve and set the current culture.
|
#
?
Mar 8, 2024 12:49
|
|
- darthbob88
- Oct 13, 2011
-
YOSPOS
|
My submission for isEven, which can even take advantage of tail-call optimization.
code:function isEven(number) {
return isEvenTCO(number, true)
}
function isEvenTCO(number, accumulator) {
if (number === 0) {
return true === accumulator;
} else if (number < 0) {
return isEvenTCO(number + 1, !accumulator);
}
else {
return isEvenTCO(number - 1, !accumulator);
}
}
|
#
?
Mar 11, 2024 06:07
|
|
- Jabor
- Jul 16, 2010
-
#1 Loser at SpaceChem
|
code:
boolean isEven(int number, IsEvenStrategySupplier strategySupplier) {
IsEvenStrategy strategy = strategySupplier.get();
return strategy.isEven(number);
}
|
#
?
Mar 11, 2024 07:11
|
|
- Volmarias
- Dec 31, 2002
-
EMAIL... THE INTERNET... SEARCH ENGINES...
|
Is that even a strategy????
|
#
?
Mar 11, 2024 07:12
|
|
- QuarkJets
- Sep 8, 2008
-
|
Python code:def is_even(x):
raise NotImplementedError()
|
#
?
Mar 11, 2024 07:18
|
|
- Qwertycoatl
- Dec 31, 2008
-
|
code:var isOdd = require('is-odd');
module.exports = function isEven(i) {
return !isOdd(i);
};
code:var isEven = require('is-even');
module.exports = function isOdd(i) {
return !isEven(i);
};
|
#
?
Mar 11, 2024 08:05
|
|
- GABA ghoul
- Oct 29, 2011
-
|
This good solid code, but personally I would go with a more modern functional programming approach
Python code:
class Monad(Enum):
NO = 1
YES = 2
MAYBE = 3
def is_even(x):
return Monad.MAYBE
|
#
?
Mar 11, 2024 10:34
|
|
- Soricidus
- Oct 21, 2010
-
freedom-hating statist shill
|
|
#
?
Mar 11, 2024 10:41
|
|
- seiken
- Feb 7, 2005
-
hah ha ha
|
My approach also takes dyslexic users into consideration.
Python code:
def iseven(person):
return person.name == "Steven"
|
#
?
Mar 11, 2024 10:58
|
|
- leper khan
- Dec 28, 2010
-
Honest to god thinks Half Life 2 is a bad game. But at least he likes Monster Hunter.
|
This good solid code, but personally I would go with a more modern functional programming approach
Python code:
class Monad(Enum):
NO = 1
YES = 2
MAYBE = 3
def is_even(x):
return Monad.MAYBE
kleene logic leads to kleene code
|
#
?
Mar 11, 2024 14:07
|
|
- Jen heir rick
- Aug 4, 2004
-
when a woman says something's not funny, you better not laugh your ass off
|
My isEven implementation:
code:bool isEven(int number){
if(File.ReadAllLines("all-even-numbers.txt").Count(x => x == number.ToString()) > 0)
return true;
if(File.ReadAllLines("all-odd-numbers.txt").Count(x => x == number.ToString()) > 0)
return false;
throw new UnknownNumberException("the number does not exist";)
}
|
#
?
Mar 11, 2024 15:17
|
|
- Athas
- Aug 6, 2007
-
fuck that joker
|
My submission for isEven, which can even take advantage of tail-call optimization.
code:function isEven(number) {
return isEvenTCO(number, true)
}
function isEvenTCO(number, accumulator) {
if (number === 0) {
return true === accumulator;
} else if (number < 0) {
return isEvenTCO(number + 1, !accumulator);
}
else {
return isEvenTCO(number - 1, !accumulator);
}
}
This is a good approach, but in 2024 sequential execution is just not going to cut it. The following implementation is based on a similar idea, but by leveraging map-reduce parallelism it can perform the O(n) work in a mere O(log(n)) parallel steps:
quote:
def isEven n = reduce (^) 0 (replicate n 1) == 0
|
#
?
Mar 11, 2024 15:18
|
|
- Bruegels Fuckbooks
- Sep 14, 2004
-
Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.
|
Here's a C# version that precomputes all even numbers up to IntMax, which obviously will save on calculation speed. We improve the initialization speed using a Lazy<T> so we only pay the cost of the precomputation on first use of IsEven()
code:using System;
using System.Collections.Generic;
public static class MemoizedEvenChecker
{
private static readonly Lazy<HashSet<int>> _evenNumbers = new Lazy<HashSet<int>>(() =>
{
var numbers = new HashSet<int>();
for (int i = 0; i <= int.MaxValue; i += 2)
{
numbers.Add(i);
}
return numbers;
});
public static bool IsEven(int number)
{
return _evenNumbers.Value.Contains(number);
}
}
|
#
?
Mar 11, 2024 15:35
|
|
- Jen heir rick
- Aug 4, 2004
-
when a woman says something's not funny, you better not laugh your ass off
|
Here's a C# version that precomputes all even numbers up to IntMax, which obviously will save on calculation speed. We improve the initialization speed using a Lazy<T> so we only pay the cost of the precomputation on first use of IsEven()
code:using System;
using System.Collections.Generic;
public static class MemoizedEvenChecker
{
private static readonly Lazy<HashSet<int>> _evenNumbers = new Lazy<HashSet<int>>(() =>
{
var numbers = new HashSet<int>();
for (int i = 0; i <= int.MaxValue; i += 2)
{
numbers.Add(i);
}
return numbers;
});
public static bool IsEven(int number)
{
return _evenNumbers.Value.Contains(number);
}
}
You should use Count instead of Contains. That way it'll iterate over all the numbers and you won't miss anything.
|
#
?
Mar 11, 2024 15:38
|
|
- Jen heir rick
- Aug 4, 2004
-
when a woman says something's not funny, you better not laugh your ass off
|
My new and improved version. No text files needed. Runtime may be a problem though, just get a faster computer.
code:bool isEven(long number){
if(AllEvenNumbers().Count(x => x == number)> 0)
return true;
if(AllOddNumbers().Count(x => x == number) > 0)
return false;
throw new Exception("the number does not exist");
}
IEnumerable<long> AllEvenNumbers(){
for(long i =long.MinValue;i< long.MaxValue;i+=2){
yield return i;
}
}
IEnumerable<long> AllOddNumbers(){
for(long i =long.MinValue;i< long.MaxValue;i+=2){
yield return i;
}
}
|
#
?
Mar 11, 2024 15:50
|
|
- Qwertycoatl
- Dec 31, 2008
-
|
My isEven implementation:
code:bool isEven(int number){
if(File.ReadAllLines("all-even-numbers.txt").Count(x => x == number.ToString()) > 0)
return true;
if(File.ReadAllLines("all-odd-numbers.txt").Count(x => x == number.ToString()) > 0)
return false;
throw new UnknownNumberException("the number does not exist";)
}
The list of numbers should come from a web service instead of files on disk, so it can automatically update if there's a mistake in the lists or new even numbers are discovered
|
#
?
Mar 11, 2024 15:51
|
|
- Bruegels Fuckbooks
- Sep 14, 2004
-
Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.
|
I thought about it a bit and I think we can use tensorflow for this application. This may or may not work depending upon your CPU type and CUDA version present on your system - when you generate the model, it's important to take a vm of your working environment so you can ensure consistent results.
code:import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Dense(128, activation='relu', input_shape=(1,)),
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(1024, activation='relu'),
tf.keras.layers.Dense(2048, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
X_train = tf.range(0, 1000000, dtype=tf.float32)
y_train = tf.cast(X_train % 2 == 0, tf.float32)
model.fit(X_train, y_train, epochs=10, batch_size=32)
def is_even(number):
number = tf.cast(number, tf.float32)
prediction = model.predict([[number]])
return tf.round(prediction) == 1
print(is_even(2)) # True
print(is_even(3)) # False
print(is_even(42)) # True
print(is_even(777)) # False
|
#
?
Mar 11, 2024 16:02
|
|
- Bruegels Fuckbooks
- Sep 14, 2004
-
Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.
|
It'd be even more efficient to move the precomputation to compile time.
That's actually a great idea! Here's the improved version:
code:using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using System.Text;
[Generator]
public class EvenNumberGenerator : ISourceGenerator
{
public void Initialize(GeneratorInitializationContext context)
{
}
public void Execute(GeneratorExecutionContext context)
{
var source = GenerateEvenNumbersCode();
context.AddSource("EvenNumbers.g.cs", SourceText.From(source, Encoding.UTF8));
}
private string GenerateEvenNumbersCode()
{
var sb = new StringBuilder();
sb.AppendLine("using System.Collections.Generic;");
sb.AppendLine();
sb.AppendLine("public static class EvenNumbers");
sb.AppendLine("{");
sb.AppendLine(" public static readonly HashSet<int> Numbers = new HashSet<int>");
sb.AppendLine(" {");
for (int i = 0; i <= int.MaxValue; i += 2)
{
sb.AppendLine($" {i},");
}
sb.AppendLine(" };");
sb.AppendLine("}");
return sb.ToString();
}
}
|
#
?
Mar 11, 2024 16:17
|
|
- leper khan
- Dec 28, 2010
-
Honest to god thinks Half Life 2 is a bad game. But at least he likes Monster Hunter.
|
It'd be even more efficient to move the precomputation to compile time.
use a generator expression so you only precompute values you might use
|
#
?
Mar 11, 2024 16:28
|
|
- Bruegels Fuckbooks
- Sep 14, 2004
-
Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.
|
I briefly looked into generating a lookup table using templates but that's way too much effort for me.
I have a French colleague who swears this will work but I have my doubts:
code:#include <iostream>
#include <array>
#include <climits>
template<int N, int... Ns>
struct EvenNumberGenerator : EvenNumberGenerator<N - 2, N, Ns...> {};
template<int... Ns>
struct EvenNumberGenerator<0, Ns...> {
static constexpr std::array<int, sizeof...(Ns)> Numbers = {Ns...};
};
template<int N>
struct EvenNumbers {
static constexpr auto Numbers = EvenNumberGenerator<N>::Numbers;
static constexpr bool IsEven(int number) {
return std::binary_search(Numbers.begin(), Numbers.end(), number);
}
};
int main() {
constexpr auto evenNumbers = EvenNumbers<INT_MAX>::Numbers;
std::cout << "Even numbers generated: " << evenNumbers.size() << std::endl;
// Example usage
constexpr int number = 42;
if (EvenNumbers<INT_MAX>::IsEven(number)) {
std::cout << number << " is an even number!" << std::endl;
} else {
std::cout << number << " is not an even number!" << std::endl;
}
return 0;
}
|
#
?
Mar 11, 2024 16:38
|
|
- Soricidus
- Oct 21, 2010
-
freedom-hating statist shill
|
You should use Count instead of Contains. That way it'll iterate over all the numbers and you won't miss anything.
This will also ensure the runtime is constant, which is an important security property as it will stop hackers using timing attacks to work out what number you are testing for evenness.
|
#
?
Mar 11, 2024 16:43
|
|
- Jen heir rick
- Aug 4, 2004
-
when a woman says something's not funny, you better not laugh your ass off
|
I thought about it a bit and I think we can use tensorflow for this application. This may or may not work depending upon your CPU type and CUDA version present on your system - when you generate the model, it's important to take a vm of your working environment so you can ensure consistent results.
code:import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Dense(128, activation='relu', input_shape=(1,)),
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(1024, activation='relu'),
tf.keras.layers.Dense(2048, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
X_train = tf.range(0, 1000000, dtype=tf.float32)
y_train = tf.cast(X_train % 2 == 0, tf.float32)
model.fit(X_train, y_train, epochs=10, batch_size=32)
def is_even(number):
number = tf.cast(number, tf.float32)
prediction = model.predict([[number]])
return tf.round(prediction) == 1
print(is_even(2)) # True
print(is_even(3)) # False
print(is_even(42)) # True
print(is_even(777)) # False
welp, I'm out. No idea how this works.
|
#
?
Mar 11, 2024 16:54
|
|
- GABA ghoul
- Oct 29, 2011
-
|
I thought about it a bit and I think we can use tensorflow for this application. This may or may not work depending upon your CPU type and CUDA version present on your system - when you generate the model, it's important to take a vm of your working environment so you can ensure consistent results.
code:import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Dense(128, activation='relu', input_shape=(1,)),
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(1024, activation='relu'),
tf.keras.layers.Dense(2048, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
X_train = tf.range(0, 1000000, dtype=tf.float32)
y_train = tf.cast(X_train % 2 == 0, tf.float32)
model.fit(X_train, y_train, epochs=10, batch_size=32)
def is_even(number):
number = tf.cast(number, tf.float32)
prediction = model.predict([[number]])
return tf.round(prediction) == 1
print(is_even(2)) # True
print(is_even(3)) # False
print(is_even(42)) # True
print(is_even(777)) # False
lmao
It should throw an UnsafeNumberContentDetected exception if you pass "80085" to it. Children might be using it
|
#
?
Mar 11, 2024 17:01
|
|
- DoctorTristan
- Mar 11, 2006
-
I would look up into your lifeless eyes and wave, like this. Can you and your associates arrange that for me, Mr. Morden?
|
I thought about it a bit and I think we can use tensorflow for this application. This may or may not work depending upon your CPU type and CUDA version present on your system - when you generate the model, it's important to take a vm of your working environment so you can ensure consistent results.
code:import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Dense(128, activation='relu', input_shape=(1,)),
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(1024, activation='relu'),
tf.keras.layers.Dense(2048, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
X_train = tf.range(0, 1000000, dtype=tf.float32)
y_train = tf.cast(X_train % 2 == 0, tf.float32)
model.fit(X_train, y_train, epochs=10, batch_size=32)
def is_even(number):
number = tf.cast(number, tf.float32)
prediction = model.predict([[number]])
return tf.round(prediction) == 1
print(is_even(2)) # True
print(is_even(3)) # False
print(is_even(42)) # True
print(is_even(777)) # False
Speaking as someone who has seen similar ML applications in the wild, well played and gently caress you.
|
#
?
Mar 11, 2024 17:11
|
|
- Bruegels Fuckbooks
- Sep 14, 2004
-
Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.
|
You guys are missing an obvious optimization. If the number is greater than 2 you first check if it's prime, because every prime number greater than 2 is odd. And since there are infinitely many prime numbers, that greatly reduces size of the problem set.
Slight optimization - only check the set of prime numbers up to the tested number.
code:function sieveOfEratosthenes(n) {
const isPrime = new Array(n + 1).fill(true);
isPrime[0] = false;
isPrime[1] = false;
for (let i = 2; i * i <= n; i++) {
if (isPrime[i]) {
for (let j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
return isPrime;
}
function isEven(n) {
const maxNumber = Math.max(n, 2);
const isPrime = sieveOfEratosthenes(maxNumber);
if (isPrime[n]) {
return false; // It's prime, so it can't be even
}
const binaryString = n.toString(2);
const lastBit = binaryString[binaryString.length - 1];
return lastBit === '0';
}
|
#
?
Mar 12, 2024 18:22
|
|
- Volmarias
- Dec 31, 2002
-
EMAIL... THE INTERNET... SEARCH ENGINES...
|
Honestly, I'm disappointed that no one except Jabor is considering the case of business requirements changing. What happens when business decides that every number beginning with an even number is also even? Or 99 is even, because that's how they run sale prices? And even Jabor only mentions a strategy, and nothing else.
|
#
?
Mar 12, 2024 19:26
|
|
- repiv
- Aug 13, 2009
-
|
this is all getting too hard, can someone just offer a hosted IEAAS solution for me to throw money at?
|
#
?
Mar 12, 2024 19:34
|
|
- Volmarias
- Dec 31, 2002
-
EMAIL... THE INTERNET... SEARCH ENGINES...
|
My fees start at $200/hr and have a 4 hour minimum, rising to $400/hr and 2 week minimum if I have to talk to anyone.
|
#
?
Mar 12, 2024 19:38
|
|
- Adbot
-
ADBOT LOVES YOU
|
|
#
?
Jun 8, 2024 08:59
|
|
- LOOK I AM A TURTLE
- May 22, 2003
-
"I'm actually a tortoise."
-
Grimey Drawer
|
this is all getting too hard, can someone just offer a hosted IEAAS solution for me to throw money at?
You're in luck, because I have for you today a basic Terraform template so you can easily integrate IEaaS into your global multi-cloud environment:
code:provider "evencorp" {
region = "eu-west"
}
provider "evencorp" {
alias = "use"
region = "us-east"
}
resource "ieaas_group" "ieeas_prod" {
name = "ieeas"
tags = {
purpose = "ieeas"
environment = "production"
}
}
resource "ieaas_instance" "ieeas_prod_euw" {
provider = evencorp
group = ieeas_group.ieeas_prod
ieeas_type = "m7gd.16xlarge"
ieeas_alg = "distributed"
ieeas_zero_behavior = "zero-is-even"
}
resource "ieaas_instance" "ieeas_prod_use" {
provider = evencorp.use
group = ieeas_group.ieeas_prod
ieeas_type = "t2.micro"
ieeas_zero_behavior = "zero-is-not-even"
}
|
#
?
Mar 12, 2024 20:44
|
|