I am trying to create a memory game based on shapes and colors. The graphical design is done but I can't seem to get the code right. This is what it is supposed to do:
1) there are 3 shapes and three colors for each shapes for a total of 9 possibilities;
2) They appear at random one after the other and the goal is to press right if the second shape is the same as the first one, or left if it isn't.
3) the rest I know how to code, but this first part.... I have no idea how to write it :(
I thought about making an array with all nine possibilities but how am I supposed to take one of the shapes at random from the array and make it appear on the stage, make the system remember it, select a second one at random again and than, compare it to the first?
You can try something like this in JAVA
String arr[]=new String[9];
arr[0]="1";
arr[1]="2";
arr[2]="3";
arr[3]="4";
arr[4]="5";
arr[5]="6";
arr[6]="7";
arr[7]="8";
arr[8]="9";
String firstVal=null;
String secondVal=null;
int index1=(int) (Math.random() * arr.length);
int index2=(int) (Math.random() * arr.length);
firstVal=arr[index1];
secondVal=arr[index2];
System.out.println(firstVal+" "+secondVal);
Related
Background
I apologize for the music-based question, but the details don't really mean all that much. I'm sequentially going through a midi file and I'm looking for an efficient way to find a pattern in the data to find something called a tuplet. See image below:
The tuplets have the numbers (3 or 6) over top of them. I need to know at which position they begin in the data file. The numbers below the notes are the values you would see sequentially in the data file. Just in case you can't decipher the data below, here it is:
1, 2, 2.3333, 2.6666, 3, 3.5, 3.6666, 3.83333, 4, 4.1666, 4.3333, 4.5, 4.6666, 4.8333,
5, 6.3333, 6.6666, 7.1666, 7.3333, 7.5, 7.6666, 7.8333, 8, 8.1666, 8.333, 8.5, 8.6666.
The first tuplet begins at position 2 and the difference between the position of notes is 0.3333 (repeating)
The second tuplet begins at position 3.5 and the difference between the position of notes is 0.1666 (repeating)
The main issue is that in the note, unlike the image below, position 7 will not be noted in the data file because the data only file only lists note locations. The icon that you see in that location is called a rest, which is not notated in the data file.
Question
How can I find an efficient method to find the start of each tuplet? Is there some sort of recursive method?
I don't think you need any recursion for this.
The normal note values can only be represented by fractions of the beat of the type a / 2^b. The tuplets can be arbitrary fractions, but mostly I've seen something like triplets, quintuplets or (in your case sextuplets).
So the simplest way would be to compute the length of every note (maybe the time difference between two MIDI events? Or the length is stored explicitly in MIDI? I'm not that familiar with the format) and compute the rational representation of this length.
Every group of notes with a denominator that is not a power of two belongs to such a tuplet. To group the notes together, I would recommend the following approach (assuming that all notes of a tuplet have the same value):
Factorize the denominator into a power of two a and the rest b (e.g. a * b = 4 * 5)
Initialize an empty tuplet of size b
For every note compute the distance to the beginning of the tuplet and store the note at the corresponding position, inserting rests if necessary. The length of the tuplet can be computed by taking the minimum length l of all notes in the tuplet, so greedily adding them until the end of these notes exceeds a distance of l * b from the beginning of the tuplet
This way, you base the tuplet on the minimum note length and add all notes that fit into it.
The title is perhaps misleading but I don't know how this is called. I do want to know how to type cast for example an int variable to create a string image_number, where number is the value of that variable.
But the thing that bothers me the most is how to call for example an imageSprite with a string constructed in similar way.
I have 16 sprites in a list and some for loops, and have trouble calling sprites. I want to for example check whether that particular sprite has an image set. I know I can use the block that tells me whether that's the case or not, but I want to say:
if the number you are increasing is n, I want you to check whether imageSprite_n has an image set or not (without using if number == n, use imageSprite_n).
I hope my question is clear. Is there any way to do that or should this be done without a loop?
Learn how to work with lists
How to work with Lists by Saj
How to work with Lists and Lists of
lists (pdf) by appinventor.org
and learn how to use the advanced blocks
Then you can do it like this
The example uses 4 image sprites and checks, if image sprite 3 has an image set
I have a very specific problem:
I have uniformly random values spread on a 15x50 grid and the sample I want to hash corresponds to a square of 5x5 cells centered around any possible grid position.
The number of samples can thus vary from 25 (away from borders, most cases) to 20, 15 (near a border) down to a minimum of 9 (in a corner).
So even though the cell values are random, the location introduces a deterministic variation in the sequence length.
The hash table size is a small number, typically between 50 and 20.
The function will operate on a large set of randomly generated grids (a few hundreds/thousands), and might be called a few thousands times per grid. The positions on the grid can be considered random.
I would like a function that could spread the 15x50 possible samples as evenly as possible.
I have tried the following pseudo-code:
int32 hash = 0;
int i = 0; // I guess i could take any initial value and even be left uninitialized, but fixing one makes the function deterministic
foreach (value in block)
{
hash ^= (value << (i%28))
i++
}
hash %= table_size
but the results, though not grossly imbalanced, do not seem very smooth to me. Maybe it's because the sample is too small, but the circumstances make it difficult to run the code on a bigger sample, and I would rather not have to write a complete test harness if some computer savvy has an answer ready for me :).
I am not sure pairing the values two by two and using a general purpose byte hashing strategy would be the best solution, especially since the number of values might be odd.
I have tought of using a 17th value to represent off-grid cells, but that seems to introduce a bias (the sequences from cells near a border will have a lot of "off grid" values).
I am not sure either what would be the best way to test the efficiency of various solutions (how many grids shall I generate to have an idea of the performances, for instance).
http://www.partow.net/programming/hashfunctions/
Here are few different hash function from experts on various fields. Functions are designed for 8bit values, but I am sure you can extend for your case. I dont know what to suggest, but I think that any of them should work better than your current idea.
Problem with current approach you propose is that values are cyclic in field 2^n and if you make mod 64 at the end for example you lost most values out and only last 3 values remains in final result.
Despite your scepticism I would just shove them through a standard hash function.
If they are well randomised (and relatively independent - you don't say) to begin with you probably don't need to do too much work. Fowler-Noll-Vo (FNV) is a good candidate in these circumstances.
FNV operates on a series of 8-bit input and your input is (logically) 4-bit.
I would start without even bothering to pack 'two by two' as you describe.
If you feel like trying that, just logically pad odd length series with the message length (reduced to a 4 bit value obviously).
I wouldn't expect that packing to improve the hash. It may save you a tiny number of cycles because it swaps a relatively expensive * with a << and a |.
Try both and report back!
Here are implementations of packed and 'normal' versions of FNV1a in C:
#include <inttypes.h>
static const uint32_t sFNVOffsetBasis=2166136261;
static const uint32_t sFNVPrime= 16777619;
const uint32_t FNV1aPacked4Bit(const uint8_t*const pBytes,const size_t pSize) {
uint32_t rHash=sFNVOffsetBasis;
for(size_t i=0;i<pSize;i+=2){
rHash=rHash^(pBytes[i]|(pBytes[i+1]<<4));
rHash=rHash*sFNVPrime;
}
if(pSize%2){//Length is odd. The loop missed the last element.
rHash=rHash^(pBytes[pSize-1]|((pSize&0x1E)<<3));
rHash=rHash*sFNVPrime;
}
return rHash;
}
const uint32_t FNV1a(const uint8_t*const pBytes,const size_t pSize) {
uint32_t rHash=sFNVOffsetBasis;
for(size_t i=0;i<pSize;++i){
rHash=(rHash^pBytes[i])*sFNVPrime;
}
return rHash;
}
NB: I've edited it to skip the first bit when adding in the length. Obviously the bottom bit of an odd length is 100% biased to 1. I don't know how length is distributed. It may be wiser to put it in at the start than the end.
I was given a brain puzzle from lonpos.cc as a present. I was curius of how many different solutions there were, and I quite enjoy writing algorithms and code, so I started writing an application to brute force it.
The puzzle looks like this : http://www.lonpos.cc/images/LONPOSdb.jpg / http://cdn100.iofferphoto.com/img/item/191/498/944/u2t6.jpg
It's a board of 20x14 "points". And all puzzle pieces can be flipped and turned. I wrote an application where each piece (and the puzzle) is presented like this:
01010
00100
01110
01110
11111
01010
Now my application so far is reasonably simple.
It takes the list of pieces and a blank board, pops of piece #0
flips it in every direction, and for that piece tries to place it for every x and y coordinate. If it successfully places a piece it passes a copy of the new "board" with some pieces taken to a recursive function, and tries all combinations for their pieces.
Explained in pseudocode:
bruteForce(Board base, List pieces) {
for (Piece in pieces.pop, piece.pop.flip, piece.pop.flip2...) {
int x,y = 0;
if canplace(piece, x, y) {
Board newBoard = base.clone();
newBoard.placePiece(piece, x, y);
bruteForce(newBoard, pieces);
}
## increment x until x > width, then y
}
}
Now I'm trying to find out ways to make this quicker. Things I've thought of so far:
Making it solve in parallel - Implemented, now using 4 threads.
Sorting the pieces, and only trying to place the pieces that will fit in the x,y space we're trying to fit. (Aka if we're on the bottom row, and we only have 4 "points" from our position to the bottom, dont try the ones that are 8 high).
Not duplicating the board, instead using placePiece and removePiece or something like it.
Checking for "invalid" boards, aka if a piece is impossible to reach (boxed in completely).
Anyone have any creative ideas on how I can do this quicker? Or any way to mathematically calculate how many different combinations there are?
I don't see any obvious way to do things fast, but here are some tips that might help.
First off, if you ignore the bumps, you have a 6x4 grid to fill with 1x2 blocks. Each of the blocks has 6 positions where it can have a bump or a hole. Therefore, you're trying to find an arrangement of the blocks such that at each edge, a bump is matched with a hole. Also, you can represent the pieces much more efficiently using this information.
Next, I'd recommend trying all ways to place a block in a specific spot rather than all places to play a specific block anywhere. This will reduce the number of false trails you go down.
This looks like the Exact Cover Problem. You basically want to cover all fields on the board with your given pieces. I can recommend Dancing Links, published by Donald Knuth. In the paper you find a clear example for the pentomino problem which should give you a good idea of how it works.
You basically set up a system that keeps track of all possible ways to place a specific block on the board. By placing a block, you would cover a set of positions on the field. These positions can't be used to place any other blocks. All possibilities would then be erased from the problem setting before you place another block. The dancing links allows for fast backtracking and erasing of possibilities.
Is it possible to extract that info from the equivalence value?
I understand that the higher the equivalence value the better. Category and rank can also be extracted from the equivalence value. But is there a way to find out what the best 5 cards combination are from the 7 that you passed to it?
Twoplustwo is the fastest poker hand evaluator around (14-15 million hands evaluated per second). You give your 7 cards to it and it spits out a hand equivalence value. The higher the value, the better is card is.
Here's a great summary on twoplustwo: http://www.codingthewheel.com/archives/poker-hand-evaluator-roundup#2p2
Cached version of the link above:
http://web.archive.org/web/20130116102452/http://www.codingthewheel.com/archives/poker-hand-evaluator-roundup
(disclaimer: I'm working on a poker software that does, amongst other, hand evaluations)
You give your 7 cards to it and it spits out a hand equivalence value.
there are several evaluators doing that and if I'm not mistaken some of them compute more than a hundred million hands per second (!). These evaluators basically come down to 7 array lookups in a gigantic array and it only takes a few cycles (despite the cache misses) to evaluate a hand. I don't think 14-15 millions / second is anywhere near the fastest. CactusKev's evaluator is 10x faster if I'm not mistaken.
Now to answer your question:
how do you get the best 5 cards combination out of the 7 that you
passed to it?
Well it doesn't tell you but once you have the strength of the hand it can become very easy: you don't need to re-invent the wheel.
You can use the strength to simplify your "best five out of seven" computation.
You could also use other libraries, giving your directly the five best card (instead of just their strength) or you can use the strength to find the five best cards yourself.
I'll just give a few examples...
You know you have a full house (a.k.a. a "boat"), then you know that you're looking for three cards that have the same rank and then the best pair (if there are two pairs, but you're sure to find at least one, because the evaluator told you you have a boat).
You know you have a straight: find five cards that follow each other, starting from the best one (beware of the special wheel case case).
You could also get a bit fancier for the straight: you could take the strength of every possible straight and compare the strength that the evaluator gives you with these. If it matches, say, a ten-high straight, then simply look for any T, 9, 8, 7 and 6 card (no matter the suit).
You know you have "no pair": simply take the five highest card you find
etc.
There are only a few different ranks... They could be, for example:
NO_PAIR
ONE_PAIR
TWO_PAIRS
SET
STRAIGHT
FLUSH
FULL_HOUSE
FOUR_OF_A_KIND
STRAIGHT_FLUSH
(you could of course create intermediate "wheel straight" and "wheel straight flush" and "royal flush" cases if you want, etc.)
Once you know the which type of hand your hand is (thanks to the fast evaluator you're using), simply switch to a piece of code that finds the five best out of seven for that particular hand.
I think it's a good way to proceed because you leverage the ultra-fast evaluator and it then greatly simplifies your logic.
At startup, you'd need to compute the strenth once, for example by computing:
HIGHEST_NO_PAIR_HAND = ultraFastEvaluator( "As Kd Qh Jc 9d 5s 2c" );
HIGHEST_FULL_HOUSE = ultraFastEvaluator( "As Ac Ad Kh Ks 8s 2h" );
I'm of course not advocating to use strings here. It's just an example...
You could then, for each hand you want to find the actual five best:
compute the strength using the fast evaluator
is it <= HIGHEST_NO_PAIR_HAND ?
yes: take five highest cards
no: is it <= HIGHEST_ONE_PAIR_HAND ?
yes: take highest pair + highest three cards
no: is it <= HIGHEST_TWO_PAIRS_HAND?
etc.
So in my opinion you could reuse an API that directly finds the five best out of seven or entirely rewrite your own, but it's going to faster if you use the fast evaluator's result to then simplify your logic.
EDIT note that there's not necessarily one way to do "five best out of seven". For example with As Ac on a Kc Kd Qh Qs 2c board, both "As Ac Kc Kd Qh" and "As Ac Kc Kd Qs" are "five best" (the last queen's suit doesn't matter).
No, it's not possible to extract that information. The lookup table contains only the equivalence values, which are broken into hand type and rank; no other information is preserved.
If you need to evaluate millions of hands per second and get the winning hand for each, instead of just the rank, you'll need to use a different evaluator. If you only need to extract the winning hand rarely, you could use this evaluator, and resort to a slower method to find the best 5 cards when necessary.
Old post but I'll give it a shot. If you're using a table lookup (e.g., the 7-card arrays mentioned above, aka the Ray Wotton method), construct a second table with your target information in the same slot positions. Example: I ended up in slot 167,452 to find my eval, now I'll look at my other array in slot 167,452 to find my 5-card hand.
A single card can be represented by 6 bits - 2 for the suit and 4 for the rank. 30 bits would give you the entire 5-card hand. Maybe not quite that simple, but that's the general idea. I've used this exact technique for some stuff I did awhile back.
Alternatively, you could pass in all the 7-choose-5-card combinations (21 of 'em I believe) and find out which matches the original eval.
The twoplustwo hand evaluator can evaluate five cards hands. Here's the code for that in C#:
int LookupFiveCardHand(int[] cards) {
//assert cards size is 5
int p = HR[53 + cards[i++]];
p = HR[p + cards[i++]];
p = HR[p + cards[i++]];
p = HR[p + cards[i++]];
p = HR[p + cards[i++]];
return HR[p];
}
Notice there's 6 array look-ups despite there being 5 cards.
Anyways, since the evaluator is so fast, you can just compare every possible 5 card combination. A hand containing 7 card hands will have twenty-one 5 card combinations. Code in C#:
List<int> GetBestFiveCards(List<int> sevenCardHand) {
List<List<int>> fiveCardHandCombos = new List<List<int>>();
// adds all combinations of five cards to fiveCardHandCombos
for (int i = 0; i < sevenCardHand.Count; i++) {
for (int j = i+1; j < sevenCardHand.Count; j++) {
List<int> fiveCardCombo = new List<int>(sevenCardHand);
fiveCardHandCombos.RemoveAt(j); // j > i, so remove j first
fiveCardHandCombos.RemoveAt(i);
fiveCardHandCombos.Add(fiveCardCombo);
}
}
Dictionary<List<int>, int> comboToValue = new Dictionary<List<int>, int>();
for (int i = 0; i < fiveCardHandCombos.Count; i++) {
comboToValue.Add(fiveCardHandCombos[i], LookupFiveCardHand(fiveCardHandCombos[i]));
}
int maxValue = comboToValue.Values.Max();
return comboToValue.Where(x => x.Value == maxValue).Select(x => x.Key).First(); //grab only the first combo in the event there is a tie
}