How to create combinations of a Scala queue while preserving order? - scala

I have a Scala queue like this:
import scala.collection.mutable._
val q = Queue(golden, lion, and, golden, lady)
I want to generate slices of this queue like this preserving the order:
golden
golden lion
golden lion and
golden lion and golden
golden lion and golden lady
lion
lion and
lion and golden
lion and golden lady
and
and golden
and golden lady
golden
golden lady
lady
I know I can do something like this below, but it is not an efficient solution due to the multiple for loops:
for (i <- 0 to queue.length){
for (j <- 0 to queue.length){
val slice = queue.slice(i, j).mkString(" ")
println(slice)
}
}
Does anyone know a more optimized way of doing this? Thanks in advance!

Depends on what you want to "optimize" for. If you're optimizing for brevity & laziness, it's basically
words.tails.flatMap(_.inits)
With filtering of empty lists and a bit more formatting:
List("golden", "lion", "and", "golden", "lady")
.tails
.flatMap(_.inits)
.filter(_.nonEmpty)
.map(_.mkString(" "))
.mkString("\n")
golden lion and golden lady
golden lion and golden
golden lion and
golden lion
golden
lion and golden lady
lion and golden
lion and
lion
and golden lady
and golden
and
golden lady
golden
lady
Consider also .flatMap(_.inits.toList.reverse) for the exact same order, if that matters.

Related

Same feature value for all corresponding feature

I have tried to set the sentence as a feature for each Me_UnitSpacing. But I'm getting the same sentence value for all the occurence of the Me_UnitSpacing
Sample Code:
DECLARE LOWERCAMELCASE,UPPERCAMELCASE;
DECLARE ME_UNITSPACING(STRING sentence, STRING replace,STRING description);
Document{-> RETAINTYPE(SPACE)};
SW CW{->MARK(LOWERCAMELCASE,1,2)};
CW CW{->MARK(UPPERCAMELCASE,1,2)};
Document{-> RETAINTYPE};
LOWERCAMELCASE{REGEXP("mmHg")->MARK(ME_UNITSPACING)};
UPPERCAMELCASE{REGEXP("MmHg")->MARK(ME_UNITSPACING)};
W{REGEXP("Mmhg",true)->MARK(ME_UNITSPACING)};
DECLARE UnitspacingSENTENCE;
SENTENCE{CONTAINS(ME_UNITSPACING)->UnitspacingSENTENCE};
STRING unitspacingsent;
UnitspacingSENTENCE{->MATCHEDTEXT(unitspacingsent)};
ME_UNITSPACING{->ME_UNITSPACING.sentence=unitspacingsent};
Sample Input:
A number of psychological and mmHg psychiatric correlates have been found
implicated in the onset and/or repetition of NSSI behavior. Nock et al. 14
reported 9 k that more than half of the clinical adolescents they studied
met the DSM-IV criteria for an internalizing disorder, an externalizing
disorder, or a substance-related disorder, with a prevalence mmHg rate of
psychiatric pathologies estimated to be as high as 87%. In a large
community-based sample of 12,068 adolescents from 11 countries, Brunner et
al. (2014) found significant associations mmHg with symptoms of depression
and anxiety in adolescents who engaged in self-harming behavior 6, and they
emphasized that self-injury is strongly indicative of psychological
problems that require professional attention. Their results are consistent
with previous reports of a significantly higher rate of depressive and
anxious symptoms in self-injurers.5,15,16,17,18,19 The onset of NSSI
behavior in teenagers with depression is mainly attributable to the
function of NSSI as a way to seek relief from the depressive symptoms. 20
The literature generally stresses the broad variety of psychiatric problems
seen in mmHg teenagers with history of NSSI. Cluster B personality
disorders are often identified, especially in self-cutting adolescent
females, and so are eating disorders; approximately one in three
adolescents with eating disorders are also self-injurers, the NSSI
frequently coinciding with or following the eating disorder 21, 22.
DECLARE LOWERCAMELCASE,UPPERCAMELCASE;
DECLARE ME_UNITSPACING(STRING sentence, STRING replace,STRING description);
Document{-> RETAINTYPE(SPACE)};
SW CW{->MARK(LOWERCAMELCASE,1,2)};
CW CW{->MARK(UPPERCAMELCASE,1,2)};
Document{-> RETAINTYPE};
LOWERCAMELCASE{REGEXP("mmHg")->MARK(ME_UNITSPACING)};
UPPERCAMELCASE{REGEXP("MmHg")->MARK(ME_UNITSPACING)};
W{REGEXP("Mmhg",true)->MARK(ME_UNITSPACING)};
DECLARE UnitspacingSENTENCE;
SENTENCE{CONTAINS(ME_UNITSPACING)->UnitspacingSENTENCE};
BLOCK(foreach)UnitspacingSENTENCE{}
{
STRING unitspacingsent;
UnitspacingSENTENCE{->MATCHEDTEXT(unitspacingsent)};
ME_UNITSPACING{->ME_UNITSPACING.sentence=unitspacingsent};
}

Floating point determinism between Apple A5 and Apple A6 CPUs

I am developing a multiplayer game with Box2D physics for iOS. The multiplayer is using lock-step method as usual. The game updates physics world fixed-timely. There is no desync among iOS devices with same CPU.
However, when testing with new iOS devices with Apple A6 chip, desync happened. Viewing my log file gives me the impression that desync happens quite fast and it was probably because of some floating point operation that I could not find out which yet.
I can guarantee that only Box2D is the only module needed to be synchronized in the design of the game, and all mutliplayer commands and inputs are not out-of-sync according to my log.
I have tried changing all transcendental functions: sinf, cosf, pow, sqrtf, atan2f to double version, but without any luck.
Is there any way to force Apple A6 treating floating point numbers as same as Apple A5 like some compiler options?
I will really appreciate any answer.
A number of math library functions use different algorithms on the A5 and A6. If they differ by more than an ulp or two, you may have found a bug; please report it. Otherwise, the variation is likely within the expected tolerances of good-quality math library. For a glimpse into the reasons of why this is so, the best reference is Ian Ollmann's email to the mac-games-dev mailing list several years ago, "the math library is not a security tool", which addressed this exact issue in the context of Mac OS X. (the tl;dr version is that the goal of delivering bit-identical results across architectures, which some game developers want, is fundamentally in conflict with delivering high-accuracy answers as efficiently as possible on all architectures, which all developers [and users, since it benefits responsiveness and battery life] want; something has to give, and for a general-purpose system library the latter necessarily takes priority). The Apple developer forums would be another good place to look for information.
it is actually Nguyen Truong Chung again.
Thank you all very much for your answers so far. I really appreciate your answers, which enlightened me the path to continue debugging! At the moment, I somehow found out the reason of the desync, but without concrete solutions yet. I wish to provide you with information I got, and hopefully I can get some more in-sights.
1. Finding:
I have this function that use cos. I printed the log like this:
void rotateZ( float angle )
{
if( angle )
{
const float sinTheta = sin( angle );
const float cosTheta = cos( angle );
// I logged here
myLog( "Vector3D::SelfRotateZ(%x) %x, %x", *(unsigned int*)&angle, *(unsigned int*)&cosTheta, *(unsigned int*)&sinTheta );
....
}
}
Desync happened like this:
On iPad4: Vector3D::SelfRotateZ(404800d2) bf7ff708, 3c8782bc
On iPhone4: Vector3D::SelfRotateZ(404800d2) bf7ff709, 3c8782bc
2. Re-testing:
And the story does not stop here because:
I tried these line of code at the beginning of the game:
{
unsigned int zz = 0x404800d2;
float yy = 0;
memcpy( &yy, &zz, 4 );
const float temp1 = cos( yy );
printf( "%x\n", *(unsigned int*)&temp1;
}
I ran the code above on the same iPhone4, and guess what? I got this: bf7ff708
I put that code in the update loop of the game and the result I got was still bf7ff708 at every loop.
What is more? The value 0x404800d2 is an initialize value of the game, so every time the game starts, the two desync lines above are always present there.
3: The questioning:
So, I decided to forget what happened above, and temporarily replaced sin, cos function with simple Taylor implementations I found on dreamcode.net. The desync no longer happened.
It seems that the cos function is not even deterministic on the same iPhone 4 (OS version 5).
My question is: Do we have an explanation why cos function returns different result for the same input on a same phone? Here I have the input 0x404800d2, and two different outputs: bf7ff708 and bf7ff709. However, I cannot reproduce the result bf7ff709 by simply coding.
I guess I need the source code of math functions of the OS (floating-point version) in order to understand this clearly. Is above problem I found enough as a bug report?
It's actually Nguyen Truong Chung again. :)
Thank you very much for your help so far.
I just want to report that the desync is fixed after I rewrote all transcendental functions like cos, sin, sqrt, pow, atan2, atan, asin, acos, etc. ( as many as possible ).

iphone sdk - poker odds calculation

i'm playing with xcode to create a poker hand analizer.
I've used the specialK hand evaluator.
after included the evaluator in my project i've detached two threads ( with 125k cycles each ) to attempt to run monte carlo simulation in order to check percentage of winning for each player... my problem is that 125k x 2 cycles takes about 40 seconds to run on an iphone 4. does anyone have any suggestions ?
Have you tried comparing the percentages derived from runs at 125K simulations versus those derived from smaller runs, say 5K or 10K? It's possible the percentages converge closely enough for practical purposes.

Making predictions from a CV

I have a database with many CVs, including structured data of the gender, age, address, number of years of education, and many other parameters of each person.
For about 10% of the sample, I also have additional data about a certain action they've made at some point in time. For instance, that Jane took a home loan in July 1998 or that John started pilot training in Jan. 2007 and got his license in Dec. 2007.
I need an algorithm that will give, for each of the actions, the probability that it will happen for each person in future time increments. For instance, that the chance of Bill taking a home loan is 2% in 2011, 3.5% in 2012, etc.
How should I approach this? Regression analysis? SVM? Neural net? Something else?
Is there perhaps even some standard tool/library that I can use with just the obvious customizations?
The probability that X happens given that Y happened is right out of Bayesian inference, I think.
Lou is right, this is the case for 'Bayesian Inference'.
The best tool/library to solve this is the R statistic programming language (r-project.org).
Take a look at the Bayesian Inference Libraries in R:
http://cran.r-project.org/web/views/Bayesian.html
How many people are in the "10% of the sample"? If it's below 100 people or so, I would fear that the results of the analysis could not be significant. If it's 1000 or more people, the results will be quite good (rule of thumb).
I would fist export the data to R (r-project) and do some data cleaning necessary. Then find a person familiar with R and advanced statistics, he will be able to solve this very quickly. Or try yourself, but R takes some time in the beginning.
Concerning the tool/library choice, I suggest you give Weka a try. It's an open source tool for experimenting with data mining and machine learning. Weka has several tools for reading, processing and filtering your data, as well as prediction and classification tools.
However, you must have a strong foundation in the above mentioned fields in order to strive for a useful result.

iPhone-SDK: Remove uneccessary white spaces from big paragraph string?

I want to remove unnecessary white spaces from the big paragraph string mentioned below.
I tried removing it by stringByTrimmingCharactersInSet and using replaceOccurrencesOfString and all. No success. Can someone please see my paragraph string and provide me the code snippet which can replace all the unnecessary white spaces and make it worth read.
Paragraphs String starts from below ------------------------------------------
World wealth down 11 pct, fewer millionaires - report
Top News
World wealth down 11 pct, fewer millionaires - report
11:29 AM IST
By Joe Rauch
NEW YORK (Reuters) - The 2008 global recession caused the first worldwide contraction in assets under management in nearly a decade, according to a study that found wealth dropped 11.7 percent to $92.4 trillion.
A return to 2007 levels of wealth will take six years, according to a Boston Consulting Group study that examined assets overseen by the asset management industry.
North America, particularly the United States, was the hardest hit region, reporting a 21.8 percent decline in wealth firms' assets under management to $29.3 trillion, primarily because of the beating U.S. equities investments took in 2008.
Also hit hard were off-shore wealth centers, like Switzerland and the Caribbean, where assets declined to $6.7 trillion in 2008 from $7.3 trillion in 2007, an 8 percent drop.
The downturn has "shattered confidence in a way we have not seen in a long time," said Bruce Holley, senior partner and managing director at BCG's New York office.
The study forecasts that wealth management firms' assets under management will not return to 2007 levels, $108.5 trillion, until 2013, a six-year rebound.
Europe posted a slightly higher $32.7 trillion of assets under management, edging out North America for the wealthiest region, though the total wealth in region dropped 5.8 percent.
Latin America was the only region to report a gain in assets under management, posting a 3 percent uptick from $2.4 trillion in 2007 to $2.5 trillion in 2008.
MILLIONAIRE ... NOT
The economy's retreat also pounded millionaires who made risky investments during the economic boom.
The number of millionaires worldwide shrank 17.8 percent to 9 million, the BCG study found.
Europe and North America were hardest hit in that regard, posting 22 percent declines. The United States still boasts 3.9 million millionaires, the highest population on the globe.
Singapore had the highest density of millionaires at 8.5 percent of the population. Other countries included Switzerland, at 6.6 percent, Kuwait, at 5.1 percent, United Arab Emirates, at 4.5 percent, and the United States, at 3.5 percent.
----------------- Paragraph string ends just above ------------------------------------
Please see my answer to your identical previous question:
iPhone-SDK:Remove white spaces from a paragraph string?