Oh god, I ran a quick test, and it looks like your way appears to be slightly faster then just looking it up in a normal lookup table. Welp, guess that makes this algorithm canonical.
Reminds me of a similar bug in Python: http://ideone.com/m5txM
Except it's twice as vicious because when you sanity-check your results, everything looks all right.
The reason for the bug is that at some point they switched from a simple linear generator to Mersenne Twister. Unlike linear generators, Mersenne Twister doesn't allow jumping ahead in the sequence, on the other hand its enormous state space (623*32
bits) makes it OK to jump anywhere instead. Except that contrary to the belief of the implementers changes made to initial bits of the state do not propagate further immediately (and in fact take a damn long time to scramble the entire state -- it looks like you get up to 397 runs of 623 output values with longer and longer initial segments scrambled).
That they still advise to use a seed + jumpahead
for multithreaded applications in the documentation doesn't help either (you should just use seed now).
So, this ad:
Has correct and clean JS code
Can be understood even by people who don't know any programming languages.
Is actually pretty funny
And still some people hate it, because hurr durr durr "targeting tech workers with its desperate attempt at making ice cream high-tech."
Also whoever wrote this ad knows more about code than article's author. "ersatz CSS-type code" my ass, it's a goddamn javascript (and perhaps some other languages too) program. What even is "CSS-type code"?
Just fyi: N=N++; has no effect on N's value
N++ will increment N by 1, but it evaluates to N's original value, so N will be set back to what it was. You could do N=++N; but the best way would just be N++;
In order they appear in the source code:
stdafx.h
header is not standard, and is of no use to you now.ctime
, not time.h
.enemy
a constructor that takes all fields, unless I wanted to use the fact that it's POD.createEnemy
should be called createEnemies
and return an std::vector
.std::ostream& operator<<(std::ostream&, enemy const&)
for printing.system("pause");
.Example rewrite: http://ideone.com/Msyno
Assuming this is Java, which I'm not overly familiar with, how about this (since Java 8)?
static boolean isAlpha(String s) { return s.chars().allMatch(c -> Character.isAlphabetic(c)); }
I think enums are the wrong tool for the job here the fact that C enums allow for ORing is just a distraction, why not just:
namespace flags { constexpr int a=1, b=1<<1, c=1<<2; }
auto a=flags::a | flags::b;
At the end of the day you aren't enumerating anything, you are "orring" named constant integers, so why not use them?
I don't understand, what would the status quo be? Lexical scope as found in Scheme, following pretty much the same rules as first-order-logic, though clean and understandable, has almost never been emulated, with every other programming language author just making up their own, ad-hoc, kludgy rules about where and how a variable may be declared, or (re)assigned.
Thus we have Python, which had to patch its ten-years-broken scope syntax and semantics with nonlocal, Java, relatively sane, allows shadowing only within inner classes, with variables defined within a scope being 'fresh' (at least you can perform that infamous lambda-in-a-loop with it...), or Javascript which seems to have scope for functions and for-loops, and nothing else?
Godspeed to anyone who wants to explain PHP's.
At the end, this recent 'innovation' from CoffeeScript isn't much of a stand against the establishment, it follows an inexplicably well-esteemed tradition of arbitrariness and the eschewing of Computer Science in the making of programming languages.
Edit: sausagefest said CS as in CoffeeScript, not computer science, *facepalm* on me. But yeah, I can't begin to like a language where re-assignment is the only choice, save for rolling your own let
with closures.
I would have just posted a link to the page on ideone (http://ideone.com/nO8gOM) but odds are it'll stop eventually, and then it won't make sense.
EDIT: Yep, now it says "Compilation error #stdin #stdout 0s 0KB".
You're going to incur the structure padding one way or another due to the alignment of the larger type: http://ideone.com/ubKV6Z
The reason for not having a special templated version for types with a sentinel value is because the whole point of optional is to avoid sentinel values -- if sentinel values solve the problem then there's no reason to use optional.
I think I mixed up something here. On C++, 'a' is of type char, yet in C, 'a' is of type int. This can be verified simply by doing sizeof('a') in gcc and g++.
Edit: I got downvoted for explaining. Sasuga /r/programmerhumor
Edit edit: http://ideone.com/4kEA3i http://ideone.com/Epkl2a
It's pretty easy to see why when you look at it in binary: http://ideone.com/m2vsbz
Also TIL signed integer overflow in C is undefined behavior.
Edit: Changed the order of digits from little endian to big endian
>Why they used a signed integer, we may never know.
Presumably because that's pretty much the default. Nobody uses unsigned integers without actually thinking that it closer. Also, many languages don't have unsigned integers (they're not that useful).
Besides, it's a bad idea to make an integer unsigned just because it will never be negative. That can make the bugs less obvious (it'll wrap to zero, which is often a valid number, but still entirely undesirable) and removes the possibility of using a negative as an obviously invalid temporary value or placeholder (which is useful).
Unsigned arithmetic is slightly different and can be confusing. If i
is unsigned, what is i * -2
? i - 2 * i
? Answers. With signed arithmetic, the first case is obvious (assuming no overflow). The second case will be negative (again assuming no overflow), which is very idiomatic to detect with something like if(result < 0) result = 0
.
Unsigned integers are more useful when you're dealing with things like raw binary data (which is often unsigned). In fact, that's the only thing I have ever had to use unsigned types directly for (and I guess typedefs like size_t
).
> This should return false.
That is not true. According to the documentation for empty
:
> No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.
Notice that last line? ... || $var == false
. If it were $var === false
, you would be correct. But an integer 0
or a string '0'
both == false
.
Example: http://ideone.com/WUbVSE
Edit: I'm not saying that '0' == FALSE
isn't lolphp enough on its own, just pointing out that the documentation clearly says ==
not ===
.
It's an abstract method.
The point is that someone is going to extend it with their own implementation, when they do this, they're able to scope it differently.
Also look up the definition of public again. Anyone who imports it can call it, regardless of package.
The answer I'd give op is to use an interface with the methods he wants exposed. Callers would go through the interface and not be aware of other methods.
interface Doable { void doStuff(); }
abstract class BaseImpl implements Doable { @Override public void doStuff() { doOtherStuff(); } protected abstract void doOtherStuff(); }
class ConcreteImpl extends BaseImpl { @Override public void doOtherStuff() { //this is possible, but because we're going through an interface, being public here doesn't change the user experience System.out.println("Raise ur dongers"); } }
public static void main(String[] args) { Doable d = new ConcreteImpl(); d.doStuff(); d.doOtherStuff(); //<- won't build, this isn't exposed. }
So I decided to compare it with C++, as a baseline of sorts.
A naive implementation turned out to be twice as slow as perl, using a shitton of sys time, while turning off output made it much faster. Turns out it's pretty hard to turn off line buffering on cout (or on stdout for that matter), in fact I admitted defeat on that one and used my own string as a buffer and just called write()
when it grew larger than 16kbytes, then C++ was like 5-10% faster than perl, while still using the straightforward std::getline(cin, line)
for input.
An interesting thing is that head -n xxx
is more than an order of magnitude faster than that, despite still reading all the data, scanning it for EOLs, and writing it out. So I suspect that it's possible to drastically speed up this stuff by using a huge input buffer and calling read()
manually as well.
EDIT: because I really wanted to see if I'm correct about the bottleneck and how fast it could possibly go http://ideone.com/N5g6iS
$ time cat test.tsv | head -n 1000000000 > /dev/null
real 0m2.150s user 0m1.682s sys 0m1.632s
$ time cat test.tsv | ./testcpp > /dev/null
real 0m3.323s user 0m2.917s sys 0m1.521s
$ time cat test.tsv | perl -pe 's/$/\t2/' > /dev/null
real 0m50.793s user 0m49.924s sys 0m2.801s
I'm entirely satisfied.
pastebins that can actually run your code can be found at http://ideone.com and http://codepad.org. http://pastie.org is pretty much better than pastebin as well. For instance, the raw texts of pastebin have all their newlines converted to [CR+LF], which is great for people running windows but disgusting for anyone else (it will ruin hashbang scripts, for instance).
It's not luck, it's endianness. The x86 architecture is little-endian, so the lower bits of the '?'
converted to an int
are stored first, and the rest are zero. Check.
As rifter5000 says, Python is duck typed and so any type annotations should work within this paradigm. The checker in the article implements a nominal type system.
Instead, we could create a system of traits which values must adhere to:
class Trait: def init(self, name, methods=None): self.name = name self.methods = [] if methods is None else methods
def is_satisfied(self, value): return all(hasattr(value, method) for method in self.methods)
num = Trait("num", ["add", "sub", "mul", "truediv"])
def gcd(a: num, b: num) -> num: ...
And the implementation of do_typecheck
:
def do_typecheck(name, arg): trait = f.annotations.get(name, None) if trait and not trait.is_satisfied(arg): raise RuntimeError("{} is {} which does not satisfy trait {}".format(name, type(arg).name, trait.name))
A demo: http://ideone.com/9uCEV1
He probably has 2 leading zeros because he printed every byte, so he has a multiple of 8 number of bits. However, his answer is also wrong (which is obvious because he has over 4000 bits for a 543 long base 10 integer, which can have at most 1807 significant bits).
Here's the right answer: http://ideone.com/jlSJ4M
It's just an interface to http://ideone.com, a code-compiling paste site that pretty much every programmer knows about. They provide an API that lets you write scripts that interact with it, though they'll freeze your API key and demand you upgrade to a pro account that charges a monthly subscription fee if your API usage gets too high.
> Lambdas allow ad-hoc functions to be declared at block scope (something that was illegal before in C++). The lambda function (functor) is only available within the scope of func() in this example; unlike a function, which would have global scope (or file scope if declared as static).
It can be done in pre-C++11 indirectly by creating a local scoped class definition with static function. Like this for example. It is not pretty, but I have seen this done here and there. The lambda did help clean this up (and allowed for less typing).
What would be nice to have though are polymorphic lambdas.
I don't know what you're talking about, the below compiles perfectly well (http://ideone.com/fCiq3K)
#include <iostream> #include <memory> #include <vector>
int main() { std::vector<std::unique_ptr<int>> v; v.resize(200);
for(int i = 0; i < 100; ++i) { v.emplace_back(new int{i}); }
for(auto&& p : v) { if(p) { std::cout << *p << ", "; } } }
What compiler are you using?
So how do you like this:
f(x) = ⌊30+2*sin(93*sin(145*x+155))⌋
Edit: removed some parenthesis
There you go, 2156 crates to get every item!
However, we're not taking into consideration that you don't have the same chances of getting a common, rare, epic and legendary.
I'm sure you can just fit the whole thing in the for statement in C++, I don't know about C, though.
for (int i = 0; i < 8; (ret_value += (number & (1 << i)) != 0),i++);
here's some code to test it against the previous two liner http://ideone.com/GWPZ7Y
It seems to work
The issue is that __FUNCTION__
doesn't work the same across all platforms. You could use __PRETTY_FUNC__
on clang/gcc but it's a different format from MSVC's __FUNCTION__
so you'd need a macro switch and I think a bit of parsing on the clang/gcc side as __PRETTY_FUNC__
is a fair bit more verbose.
EDIT2: Link was pointing at the wrong ideone.
Probably because the std::bitset
inlines its content see ideone:
Of course, the functionality provided is way different, you cannot grow a bitset...
One possible reason is that you can consider it as an offset from where it starts in memory. For example, in C, if you have an array x
, then x[3]
is the same as *(x+3)
. You have to start with 0
otherwise you'd skip over the first element.
#include <stdio.h>
int main(void) {
int x[10] = {0,1,2,3,4}; printf("%d %d\n",x[3],*(x+3));
return 0; }
Sucks to get downvoted when you are essentially correct. It is basically a for loop with a nested switch statement and a little bit of logic to handle each hero power.
Here is an example I wrote in like 2 minutes.
well you shouldn't use naked new
in you c++ code anymore (since std 11) also new
can be only assigned to pointers, you are leaking memory now since you don't delete obscure object. use this instead.
std::shared_ptr<Thing> obscure = make_shared<Thing>(); std::explain(obscure); return 0;
/u/compilebot (or more specifically, ideone, which /u/compilebot uses) uses print
for the console (when using spidermonkey; if using rhino, it uses System.out.println). However, print
does open the print dialog in actual browsers.
Yeah, except createDictionary's time and space complexity is O(n log n), and you stated that the required time complexity is O(n). A better way to solve this would be using std::bitset, like this.
My favourite example (that I keep seeing people re-enacting):
#include <cstdio> #include <climits> using namespace std;
int main(int argc, char ** argv) { int x = argc + INT_MAX; if (x < argc) { printf("overflow happened\n"); } printf("%d < %d = %d\n", x, argc, x < argc); return 0; }
Clang is way more conscientious about exploiting undefined behaviour than GCC, but even it fucks your shit up in this case without any warnings.
Integer overflow is undefined behaviour, not "implementation-defined behaviour", not even "unspecified behaviour", it's "undefined behaviour", meaning that you, as a programmer, make a solemn promise to the compiler that you know for sure that argc
can't be a positive number and therefore cause an integer overflow. So the compiler is free to unroll loops, optimize away checks, propagate "known truths" about results of comparisons, etc. So nothing is printed re: overflow, and -2147483648 is not less than 1.
This happens with default optimization settings on one of the most forgiving modern compilers. Undefined behaviour is here to stay, folks, no amount of complaining about it being not worth it can make it go away, if you don't like it then don't code in C or C++.
A first D version, it isn't that fast if you use the old back-end of the DMD compiler (and currently in Phobos file I/O is not that optimized): http://ideone.com/0ZiXg
With DMD if you want to go significantly faster than the Java version VecGenOpt.java (and a bit faster than the C++ version vec_gen_opt.cc) you have to write bad looking code like this (more than 20 times faster than the first D version): http://ideone.com/ImOdF
An even faster D program unrolls the while loop manually, because the number of digits of an int is limited, and uses gotos to the end, in a kind of finite state machine, it's not hard to do, but I go there only rarely (about 10% faster): http://ideone.com/5t3hk
Edit: added third version. Edit: shorter third version.
#include <stdint.h>
int main(void) {
uint64_t bugs = 0;
bugs--;
printf("%llu", bugs);
}
>18446744073709551615
You need to remove the trailing ;
from each of your for
loops, e.g. change:
for (a = 1; a < 10; a ++);
to:
for (a = 1; a < 10; a ++)
You also need to move the line printf("the count is %d\n", count);
so that it's outside the loops, i.e. just before the return 0;
, otherwise it will print on every loop iteration - you just want it to print once, at the end.
Evaluating the left side of an assignment is not the same as executing the assignment itself. If there's any code that has to run in order to figure out where the right side's value gets stored, it runs before the code on the right side.
I don't get it... See my code at http://ideone.com/Wu6WJj
Firstly, your example as stated doesn't compile.
Secondly, (once it does compile) it doesn't do anything I would regard as unreasonable.
Thirdly,
> The C++ standardization body wishes you a happy stack corruption!
... seems to be completely unjustified. I don't see stack corruption anywhere in this code. Unless I'm just being dense...
> Your statement is incorrect. The _Bool type may be larger than one bit
Yes, but the standard says
6.3.1.2 Boolean type
When any scalar value is converted to _Bool, the result is 0 if the value compares equal
to 0; otherwise, the result is 1.
So (_Bool)2 == 1 yields 1. Also,
6.7.2.1 Structure and union specifiers
122) While the number of bits in a _Bool object is at least CHAR_BIT, the width (number of sign and value bits) of a _Bool may be just 1 bit.
The maximum width of a _Bool bit-field is 1 with GCC (8 with LLVM).
Computers agrees with you:
#include<stdio.h>
int main(){ int zero = 0; int one = 1; if(zero = one) printf("zero equals one\n"); else printf("zero does not equal one\n"); return 0; } prints:
zero equals one
/u/compilebot is banned from this subreddit (Every time he appeared people tried to hack the bot, because that's what people do). It's unfortunate.
You can just put the code onto IDEOne though; that'll do the same thing that compilebot does. So your result is this.
So this got me wondering, who uses what actually. I mean, it's a sort of invisible thing cross-culturally, pretty much like wiping sitting/standing or the orientation of the TP roll.
So I wrote this.
Looks like people who start week on Sunday are mostly former British colonies (but not the UK itself, curiously), some catholic countries such as Brazil and Ireland, and a lot of Asian countries including China, Japan, Korea. Most Islamic countries use Saturday.
Other fun facts: on ideone (which is currently somewhat down) Syria shows as starting its week on Thursday (hi, /u/david-me). Dari (Afghanistan) start the week on Friday (Pashto (Afghanistan) start on Saturday) on my Windows 7 but not on whatever rextester uses. China and India can't make their mind re: Monday vs Sunday too. And Equador on rextester.
Another interesting list I found on Wikipedia: http://en.wikipedia.org/wiki/Workweek_and_weekend -- turns out that a lot of countries actually start their working week on Sunday or even Saturday.
Ruby affords a pretty straightforward solution:
n, alphabet = gets.split(/\s+/)
words = n.to_i.times.reduce([]) { |words| words << gets.chomp }
puts words.sort_by { |word| word.split('').map { |letter| alphabet.index(/#{letter}/i) } }
I was going to do another one of my non-alphanumeric programs, but I can't figure out how to simulate #gets
without using any numbers or letters. :/
Edit to include a link to a C solution I wrote up just to make sure I still could.
Edit the Second
So I ended up accepting my fate; I concede that I'm addicted to the lambda calculus and its manifestation as symbol-laden Ruby code. To that end, here is my completely non-alphanumeric solution to today's problem.
As I mentioned, I've not yet discovered a way to obtain user input in Ruby without using letters, so this program cheats a bit by passing the data as parameters to the Gorellian procedure (called $________
in the code). Still, it's a workaround I can deal with, as the rest of the program is pretty glorious, and it was a hell of a lot of fun to tinker with.
IdeOne is phenomenal! It has syntax highlighting as well as a ton of languages. The problem is that it doesn't support multiple files (AFAIK). I use it to screw around with languages all the time.
Between 2156 and 2157 crates to get every item, assuming it's a truly random distribution. However, we're not taking into consideration that you don't have the same chances of getting a common, rare, epic or legendary.
constexpr
: values of variables and functions can be determined at compile-time.
auto
: type inference specifier.
references
: this doesn't make sense. I think OP means move semantics, which "moves" one object into another instead of requiring expensive copies. The reference type associated with move semantics is an "rvalue reference."
for each loop
: loop over all objects in a container instead of using iterators (directly).
universal initialization
is quite a large topic, but it deals with aggregate initialization and prevents narrowing conversions. Here's a bit more info.
Edit: Here are examples of all these features.
Was it not just C++17's library part, not whole? AFAIK it's not even clear yet what C++17 will have...
I'm VS user and i really like it, but it bugs me, that they just don't give too much shit about being standard compliant. Example. I'm guessing GCC gets it right.
So i wouldn't be so hyped about VS' support for supporting standards too much.
Making your own mods is done through the Lua files in the mods folder. You can use the existing Encounter Skeleton mod as a base, if you'd like, but I'd recommend copying it to a separate folder if you do just in case something breaks.
If you need help getting started, make sure to read the included documentation (open the HTML file in the Documentation folder to view it). If that doesn't cut it, check /u/BtheDestryr's tutorial (also linked in the sidebar) and /u/ReddehWow's resources list.
And don't be discouraged if things break a lot at first - that's pretty normal! Lua takes a while to get the hang of, and it's easy for small errors (like using the wrong quotation marks or missing an end) to sneak by. Should you have trouble finding an error and Unitale's own error handler isn't quite helping, try running your script through Ideone, as it's pretty good at catching most errors.
Are you sure you're not confusing something? The first version is 2x slower on 3.4: http://ideone.com/PJQ7Pa, as it should be.
There are other cases, things can work differently if you're using __slots__
for example (though you'll still have at least one dictionary lookup to get the descriptor), but as far as I know __dict__
is pretty much the usual dict
otherwise.
ninjaedit: attribute access is roughly the same http://ideone.com/yYPIPX
As /u/zifyoip said, the problem is not inside your code, it's the class name. You have to be careful how you name your classes so that you don't accidentally override Java internal classes.
The code itself is fine as can be seen here: http://ideone.com/UgCvR9
Just rename your class to something else (like "TestString") and you're good to go.
I put some code up here: http://ideone.com/3rwCfa
the idea here is that you don't know which variable you're solving for, this program is supposed to accept 'solve' as an input for one of the four variables, and numbers for the rest
another idea behind this script is that it could be expanded to run with 3,4,5...n variables on either side of the equation with less extra coding than would be required for a string of 'if,else' statements
that's the general idea - if you actually wanted to use it for something practical you could build on that
edit: don't downvote me bro I'm editing
If you have no idea, plug it into Ideone.
You will see the results immediately and it helps understanding the code.
What you see in line 6 is called the Ternary Operator
Another cool fact is that because that number is so large, adding 1 to it is waaaaay below rounding error. So there's this idea of "unit in the last place," which is the smallest number that can be added or subtracted from a number that will change its value Here's how it looks in java
Even though your question was already answered by /u/Taylee:
People, please learn to google, learn to read the documentation, and try out the code.
Yes, you will mostly get a quick answer, but you will learn much more if you find/try things on your own.
Definitely can't get that to compile, visual studio is having an issue with the F_OO()'s trying to recognize them as a function name entirely
Was able to get it to run- not quite sure what the point of this code is... I mean if there were instructions to an assignment I might understand but it's just random code that prints 0.250
C++ solution, with a few (mildly obfuscating) tricks:
#include <iostream> #include <string> #include <cctype> using namespace std;
enum action { ENCRYPT, DECRYPT }; string crypt(action type, int nrails, string data) { int cyclesize = 2*(nrails-1); string ret(data); int pos = 0, i, a; int & rpos = type ? i : pos, & dpos = type ? pos : i; for (int rail = 0; rail < nrails; ++rail) { for (i = rail, a = 2*rail; i < data.length(); a = cyclesize - a, i += a) { if (a==cyclesize) continue; ret[rpos] = data[dpos]; ++pos; } } return ret; }
int main() { string data; action act; int nrails; cin >> data >> nrails; if (data == "enc") act = ENCRYPT; else if (data == "dec") act = DECRYPT; else { cout << "Unknown action.\n"; return 1; }
while (isspace(cin.peek())) cin.ignore(); getline(cin, data);
cout << crypt(act, nrails, data); return 0; }
> my friend mistakenly set the first char array to have size 10 instead of 20, you would expect it to fail
That program has undefined behavior, which means you have absolutely no guarantees about the behavior of any part of the program.
You should not "expect it to fail," nor should you "expect it to succeed." You have absolutely no guarantees about its behavior in any way. It may work some of the time on some systems under some compilers, and it may fail in other cases.
The C standard is a contract between the programmer and the compiler. The compiler is obligated to produce an executable program that behaves in a specified way as long as the programmer follows the rules in the standard. By writing beyond the bounds of an array, you, the programmer, have violated the rules in the standard, and so that contract is no longer in force. The compiler is under no obligations to produce a program that behaves in any particular way.
Heapsort is slow as fuck on real hardware for big arrays though.
Try this with the array size being significantly larger than the L3 cache size of your system -- heapsort turns out to be anywhere between 3 and 10 times slower.
You should probably check with ideone.com to make sure this is permitted in their ToS or that they're OK with it. They appear to be ad supported, and this bot circumvents the ads.
It would be really cool if the bot was able to sandbox everything itself, but yeah - that's playing with fire. :-)
Informally-ish:
"X implements Y" means "For every method y in Y, there exists a method x in X such that the names of x and y are the same, x's return type is either y's return type or a subtype, and for each parameter p in y, the parameter with the same index in x is of the same type (my intuition would be to also allow supertypes here, but this is generally not allowed, see here)."
Doesn't even begin to cover things like generics, though.
Edited to fix swapped names.
I recently discovered the Java syntax "feature" where Unicode escape sequences are validated in comments:
public class Main { public static void main(String[] args) { // Unicode escape sequences look like this: \uXXXX System.out.println("\u0048\u0065\u006c\u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064\u0021"); } }
The Java compiler will complain that \uXXXX
is not a valid Unicode escape sequence, even though it appears within a comment.
Discovered while writing code to parse Java-like Unicode escape sequences, where I resorted to the funny-looking \ uXXXX
in my comments instead.
Not perfect, but here we go, C++: http://ideone.com/t25IJ
typedef pair<char, uint8_t> RunLength;
vector<RunLength> runLengthEncode(const string& s) { if(s == "") return {}; vector<RunLength> res;
size_t i = 0, nextPos; while(s.npos != (nextPos = s.find_first_not_of(s[i], i + 1)) ) { auto diff = nextPos - i; assert(diff <= 255); res.push_back( {s[i], diff} ); i = nextPos; } res.push_back( {s[i], s.size() - i} ); return res; }
string runLengthDecode(const vector<RunLength>& encoding) { string res; auto addFun = [&res](const RunLength& rl) { res += string(rl.second, rl.first); }; for_each(encoding.begin(), encoding.end(), addFun); return res; }
See this is why people like you fail. You see an extremely minor hurdle, give up, then whine how unfair things are.
Programmers see a problem and do a google search:
You don't need luck. You just need to stop making excuses. It's YOU. It's all YOU choosing to fail.
There are cases where the type of a tern can't be resolved at compile time. Take http://ideone.com/LXZWs for example. You get a nonsensical error because neither my silly Int nor Double class can be converted to the other, despite the fact that they're both convertible to Number.
I make a lot of cool batch / AHK / c++ files using system commands to automate things.
Examples:
http://ideone.com/v9YSK -- C++ - Switching my power settings between "sleep" (while I stream music and go to bed) and full power (gaming)
https://ideone.com/xuwlx -- Switching between 2 sound cards using autohotkey
The previous post on the topic was very strange to me, so I wrote a basic simulator (that reinforced my gut feeling, that climbing with a more consistent deck is better). It doesn't consider what might be the best strategy (get two quick wins with fast decks, then switch to a consistent deck), though.
If you're interested, it's here.
Yeah, as I mentioned: I wasn't trying to defend the CE - it's more or less useless nonetheless (as are almost all of those chance based CEs imo), I was just pointing out that it doesn't have the exact same effect as Nightless Rose (single use Guts) and only a chance to activate this effect on top of that.
I'm not exactly a fan of statistics either, but shouldn't the expected value for the number of activations be 1? The chances for 1, 2, 3, 4 ... activations are 1/2, 1/4, 1/8, etc. which is a geometric sequence. For the geometric distribution, the expected number of failures before the first success is E(Y) = (1-p)/p. Failure and success are interchangeable here (p = 0.5), so we'd get E(Y) = (1 - 0.5) / 0.5 = 1.
edit: Just to be sure (because I don't trust my statistics knowledge either ...), here's a quick simulation, which supports this as well. :P
You could use some template magic to detect if a specific function exists. You'll need a partial template specialization that fails if the function does not exist (example).
Then use SFINAE to select the correct print function.
Implemented it so I'm less rusty now!
It can indeed be done in place with a straightforward MSB radix sort, but the stack has depth proportional to the number of bits (no big deal) because it's a divide and conquer recursive algorithm.
> B. I'm using floating point because we don't have large numbers to calculate, and we're supposed to round anyways.
That's the point: pH might be equal 6.99999999999999999999999999999999999999999999999978923145 or 7.00000000000000000000000000000000052 due to non-exactness of pow, log, binary representations of 0.1
> E. How can you tell I'm declaring namespace in the header file? I am, but seeing as that wasn't in the picture I'm impressed.
Because it would not compile otherwise
> From what I read, i and J are being incremented at the same exact time they are being checked.
Nope. Perhaps this will help demonstrate what's going on. When for
loops are nested, the inner loop runs in its entirety once for every iteration of the outer loop.
How about something like this: http://ideone.com/rhwhQQ
I feel the readability is a bit better here.
For better prime number generation, check the "find primes" post on SO. They are a bit more advanced.
EDIT: My code can be optimized a bit in isPrime by only checking 2 as the only even number. But it was more an example for readability.
Nice, I failed most of them =) I have some corrections though:
#3:
> When the ToString() method override is called, struct c is automatically boxed to an object type to facilitate the call.
Nah, if we call ToString() ourselves, it's called on the unboxed struct
(makes sense, otherwise it would be impossible to have any mutating methods on structs). The
boxing occurs when the struct is passed to the void Console.WriteLine(object obj);
overload.
#5:
> The \Udddddddd
escape code is used for encoding UTF-16 unicode characters (also referred to as codepoints).
UTF-16 is an encoding itself, so the correct way to say it is that the \U
escape is used for
encoding unicode characters (codepoints), period. This is not an entirely pointless pedantry because
codepoints above 0xFFFF look nothing like their '\U' encoding (which
uses straight numeric value) when encoded in UTF-16.
#14: > Overflows in floating point (float and double) types always wrap around and never throw an overflow exception in any context. They can also produce special IEEE754 values such as Infinity or NaN as results.
Floating point overflows don't "wrap around", wrapping around is an artefact of representation of integers. Adding something to float.MaxValue results either in float.MaxValue or float.PositiveInfinity, depending on how big that something was and which way it got rounded.
Thanks to the beauty of smartphones, I got this just as I was about to sleep (it's 2am here).
My guess is you are getting those warnings/errors because you don't yet understand the this
keyword, or (less likely) you don't yet understand the new
keyword.
Static variables are mainly used for to accessing class members without creating class instance. For example:
class Foo {
static int num = 6;
}
Here num
can be accessed like Foo.num
. An instance of Foo does not need to be created. num
is like a global variable (which are usually also evil).
In this example, an instance of Bar is needed to access num
class Bar {
int num = 5;
}
num
is accessed like:
Bar bar = new Bar(); bar.num; // Always use getters and setters, this is a toy example.
Here's an example showing the difference
If you need further clarification, consider a Person class. If we modify one Person's name, should another Person's name also change?
You have other options. You could use std::replace_if
and string::find
to figure out what to replace. Here is an example using some C++11 features, though this is doable without C++11 too. It's just a matter of how much time you want to spend figuring all this out to have a nice, clean, consistent solution.
I would recommend a different technique that doesn't require exceptions and unsafePerformIO. This requires that you are able to construct a function that can determine whether or not the function is defined for a given input:
partial :: (a -> b) -> (a -> Bool) -> a -> Maybe b partial f p x | p x = Just $ f x | otherwise = Nothing
safeHead :: [a] -> Maybe a safeHead = partial head (not . null)
Example usage: http://ideone.com/pF44q
Both your concerns are not caused by OP, but by IDEONE, the online IDE OP linked to.
> Why do you think that making the class public would mean is has to be named Main?
This is a comment from IDEONE
> Also, why not put things in a package? It is extremely bad practice to not put things in a package.
Again, an IDEONE comment.
See an empty IDEONE project: http://ideone.com/myK1pf
The link above is to a default setup of IDEONE without even a single letter entered.
It works great for functions, but can cause issues for template classes. Explicitly instantiating a class will instantiate all the members, including some that may cause compile errors.
For example, it's perfectly fine to put a move-only type in a std::vector
because the methods that use the copy-constructor won't be selected by tag dispatch (or enable_if
or whatever). But it's definitely going to be an error to say template class std::vector<MoveOnlyType>;
because it will instantiate those methods anyway. See here.
O(n) with c++ code online
#include <iostream> #include <vector> #include <unordered_map>
std::pair<int, int> find_range_with_sum(std::vector<int> const& numbers, int k) { std::unordered_map<int, int> sum_map; sum_map.emplace(0, 0); int sum = 0; for (int i = 0; i < numbers.size(); i++) { sum += numbers[i]; auto it = sum_map.find(sum - k); if (it != sum_map.end()) { return std::make_pair(it->second, i); } sum_map.emplace(sum, i+1); } return std::make_pair(-1, -1); }
int main() { std::vector<int> numbers = {-1, 5, -3, 5, 1, 2, -4, 6, -2}; auto range = find_range_with_sum(numbers, 1);
//output std::cout << range.first+1 << ". to " << range.second+1 << "." << std::endl; return 0; }
I am afraid you are misunderstanding me (or C++).
You can have dangling references without ever using pointers (yourself):
#include <iostream> #include <string>
template <typename T> T const& id(T const& t) noexcept { return t; }
int main() { std::string const& s = id(std::string("Hello, World!")); std::cout << s << "\n"; }
This sample is Modern C++, I would think. There certainly is no pointer arithmetic. Yet, it exhibits undefined behavior. For example, on this ideone run nothing is printed.
On other compilers (or compiler versions), it's happened to crash (segmentation fault) or print "Hello, World!"
. And none of them gave any warning, no matter the settings.
A quick Python script, which simulates the actions of town members shooting and dying. Repeats for about 10000 trials, and counts how many times maf is left standing.
Edit: http://ideone.com/BemyiG
Edit: Whoops. I forgot to take into account that Vig can't shoot the first night. Also that he will commit suicide after shooting a vig. So my estimate is likely way off. It's all down to whether he can survive the second night, and following hanging. I'll fix this sometime when I can be bothered.
Sorry, I must have accidentally confused packaged_task with promise when trying to find the bug report I was thinking about. The issue I'm actually think about is the following, which seems to work in clang/g++ (ideone link), but hangs with MSVC 2015 U1:
#include <iostream> #include <thread> #include <future>
int main() { try { std::promise<void> p; auto f = p.get_future(); std::thread{[p = std::move(p)] () mutable { // p.set_value(); // Imagine the value isn't set (was: exception happens, but that's a bad example) }}.detach(); f.get(); } catch (const std::future_error&) { // promise broken as expected. return 0; } std::cout << "Promise not broken?\n"; return 1; }
Just to be sure:
+/u/CompileBot Perl
sub equalize { print join "", sort grep { m/[a-z]/ } split m//, lc shift }; equalize("I am an alicorn princess"); equalize("M. A. Larson cries in panic.")
EDIT: Bot seems to be down (no posts in 11 days), so Ideone (with a slight modification for the newlines).
The difference in speed wouldn't be that bad though. Example: in a rotating station with a radius of 150 meter, where you have 17 floors rotating at different speeds, with each floor being 8 meters high (so maybe 3 corridors in height per rotating floor and you'll have plenty of room, and you'll leave the inner-most 14 meters for the mechanics), the difference between each floor would be around
That's not worse than walking speed. (code)
I did a lot of research for this comment because I ALWAYS get precedence wrong and didn't want to say something bad.
This code outputs zero, not one:
#include <iostream> #include <bitset> int main() { std::cout << std::bitset<8>(0b10 & 0b10 != 0) << "\n"; }
Here's a C++ operator precedence table. Note how multiplication is above addition (yay!), and how equality is above both bitwise and non-bitwise and.
> or even WHY - really
Recursion is an important paradigm in programming that is needed quite frequently, so it's essential to learn it.
You will need a method that:
reverse
s
for simplicity)
reverse
with the string s
minus the first character plus the first character in s
.It's actually a 4 liner with proper formatting.
Come up with some code from the pseudocode above and then I'll show you a working version in Ideone
> Other question: how do I format this into the readable lines I see on here?
About your problem:
You are overstepping the Array boundaries of the T
array in your for
loop:
for (i = 0; i <= T.length; i++)
You run the for loop until i == T.length
, which is a problem. An Array of length
has the highest array index length - 1
since array indexes start at 0
, not at 1
.
Your statement that the code runs "fine" when you remove the for
loop can be explained by the for
loop. Once you run the for
loop, you will receive an ArrayIndexOutOfBounds
exception which will stop the execution and thus also not print the while
loop.
Your for
loop should be:
for(i = 0; i < T.length; i++)
or
for(i = 0; i <= T.length-1; i++)
Your second do-while
loop actually produces the same problem with the same runtime exception.
It also needs to be:
while(j < T.length);
This is a common beginner's mistake. Always be wary of your array indexes when looping!
I think you missed the fact that you have to pay a dollar if you guess wrong (so your expected profit is definitely lower than 26, though still greater than 0).
You can compute the expected profit using [dynamic programming. The base case is f(i,0) = 1 and f(0,j) = 1 for all i,j <=N because you know that if one type of card is depleted, you can always guess right. The recurrence relation is f(i,j) = (|i-j| + i f(i-1,j) + j f(i,j-1))/(i+j). The |i-j|/(i+j) term is simply equal to max(i,j)/(i+j) - min(i,j)/(i+j) since the strategy makes you win with probability max(i,j)/(i+j) and lose with probability min(i,j)/(i+j).](#sp) I implemented this in C++ (spoilers obviously). You can expect to profit around [$7.1554](#sp).
You are doing wrong with pointers. I won't show you all of the errors in your second code (with pointers) because that way, I'll be doing your assignment. That's your job. Moreover, you need to learn it by correcting your mistakes.
However, I'll show one of the mistakes and will try to explain what's wrong. Try to figure out other mistakes and correct them yourself. Following code is wrong:
runningTot -= array[*old];
As you might already know that pointers are pointing to a memory address. That's it. They are that simple.
Look at the following three examples that I just wrote: http://ideone.com/CTYroc http://ideone.com/rScXEr http://ideone.com/lggkOk
See, how I am using pointer to access elements of array. You are getting error because you are trying to access the element of array which may not exists (array[*old]);
The line probably should be like:
runningTot -= *old;
I hope I gave you enough hints. If you are still unclear on how pointers for array in C works then Google it to search for more examples. Maybe read the chapter (in your book) on C Pointers again. Good luck :)
I was going to get /u/CompileBot, but it's banned here, so... ideone time.
+/u/pokechu22 C
#include <stdio.h>
int main() { int x = ('c' * 0.00001); void* a = x["AAAAA!"];
printf("%c\n", a); }
Some 19xx lines later.
File "prog.py", line 9, in bible File "prog.py", line 6, in god File "prog.py", line 9, in bible File "prog.py", line 6, in god File "prog.py", line 9, in bible File "prog.py", line 6, in god File "prog.py", line 9, in bible RuntimeError: maximum recursion depth exceeded
Python prevents stack overflow with run time errors, max recursion depth is 1000[or 999.. 998...]
^source display's the full output in case you don't know....
In C#, the difference is between class
and struct
. In C++, the difference is between new
and not-new
(minus the irrelevant member visibility). In Java, stack allocation doesn't exist for non-primitive types, so it's irrelevant. When I looked into D about a year ago, the difference was between <code>class</code> and <code>struct</code> as well as <code>new</code> and not-<code>new</code>, and that's a mistake. It might have been a compiler bug and the situation could well have changed by now, I only remember I spent a long time figuring out a segfault that was caused by accidentally new
'ing a struct.
And I thought making the typo "std::end" instead of "std::endl" with both <iostream> and <iterator> included was bad: http://ideone.com/u2ZGib
Try it with gcc 4.7.x and with some preceding output operations, the typo blends in.
What you want to do is to apply bitwise operations (look at operator names that start with "bitwise").
Here is a small example (you should be able to figure out yourself how to apply the same idea to your code):
std::uint8_t lowByte = 0x88; std::uint8_t highByte = 0x44; std::uint16_t combinedBytes = (highByte << 8) | lowByte; // combinedBytes will be 0x4488
See it here in action: http://ideone.com/4UhQ9N.
I will look for the error in your code, and while that you can look at how I would solve this problem: http://ideone.com/bMD6Hp
#include <string> #include <iostream>
int main() { std::string input, output;
std::cin >> input;
if (input.size() > 0) { output += input[0]; } for (auto it = input.begin() + 1; it != input.end(); ++it) { if (*it != *(it-1)) { output += *it; } }
std::cout << output << std::endl;
return 0; }
I think it depends on whether you consider the - as part of the integer literal (-10) or as an operator that is applied to the expression. In most languages that I'm familiar with it would be the former. I guess Python doesn't work that way. Are all literals in Python positive then?
EDIT: I'm totally wrong, C and C++ work this way as well:
http://msdn.microsoft.com/en-us/library/00a1awxf.aspx
(Note there is no mention at all of - or + characters).
However in C and C++ there are no operators that can be meaningfully applied to an integer literal that have higher precedence than unary negate (as exponentiation can in Python).
EDIT 2: I've put together a code snippet that demonstrates this. I was wrong in my statement that there are no operators that this can apply to , [] works just fine.
If -1 were truly a numeric literal, you'd expect this to print 2. But instead 1[p] is evaluated first and then the result is negated.
For kicks and giggles I made a script to simulate the "optimal" betting strategy. The strategy is as follows:
Here's the simulation: http://ideone.com/TvXkIB
I'm aware that 100,000 games isn't a great sample size, but that's merely a limitation of the website. Running it on a personal computer shows that - at least in simulation - the odds of winning tends towards 50%.
The results shouldn't be surprising though. Consider any deck state that has R red cards and B black cards:
If you decide to flip a card there's an R/(R+B) chance of being red and a B/(R+B) chance of being black.
If the deck has more red cards, then flipping a card means you're more likely to draw a red card, lowering R closer to B.
If the deck has more black cards, then flipping a card means you're more likely to draw a black card, lowering B closer to R.
That means that no matter the deck state, flipping a card has the tendency to even out R and B, bringing the ratio of R and B closer to 1.
Knowing this, and recognizing that the expected value of a bet at any point is (Bet * (R - B)/(R + B)), it means that from the initial deck state of R = B, you can either bet now and win with 50% odds, or you can flip cards which will eventually tend towards a state of R = B anyways.