Xtend: add indentation to template - xtend

I want to create a template that's indented 4 spaces, like below:
def myMethod() '''
for (int i =0; i!= size; ++i) {
doSomething();
}
'''
But Xtend removes the 4 spaces before the for() and the closing '}'. How can I add indentation that's not removed?

I have had similar issues, Xtend's template system can be finicky, but there are workarounds. When using something like the method you showed I usually find I call it from another part of the template and you can create the indentation in the calling method. For instance:
def callingMethod() {'''
for (1 to 10) {
«myMethod()» ««« This puts indents before everything within the method
}
'''}
def myMethod() {'''
for (int i =0; i!= size; ++i) {
doSomething();
}
'''}
Another option is to explicitly add whitespace within the template such as:
def myMethod() {'''
«" "»for (int i =0; i!= size; ++i) {
«" "» doSomething();
«" "»}
'''}
Or another way I found looking just now
def myMethod() {'''
«""»
for (int i =0; i!= size; ++i) {
doSomething();
}
«""»
'''}
Personally I think it is much cleaner the first way where possible. There are probably other ways to achieve this as well, these are just a few things I have found in my own work.

Related

Selection sort Max to end

This is my first question or time on this site so sorry if i do anything wrong. I have been trying to get this to work for my class. my eclipse has been broken for a little while so i have been coding blind as i cant find the end result or run and execute my programs. a classmate told me this question of mine was wrong but won't tell me what. it is supposed to be a selection sort that takes the greatest integers to the end then print after each pass. this looks right to me please help.
public class selectSort {
public static void Sort (){
int[] num= {5,20,8,6,7,1,3,11,15,9};
int i;
int n;
int temp;
for (i=num.length-1; i>0; i--){
int first=0;
for(n= 1; n >= i; n++){
if( num[n] > num[first])
first=n;
}
temp = num[first];
num[first] = num[i];
num[i] = temp;
System.out.println(num);
}}}

Simple For loops not working on cs6?

In my code I have a few for loops in the main timeline that look like this
for (i = 0; i<2*speedY; i++)
{
code
}
I've done this exact syntax many times and there have been no issues, however when I did it it gave me the error that i is undefined. I then tried the same loops defining i as var i:int; however now it just gave me a namespace error. What am I doing wrong here?
To avoid the undefined error, you have to define your variable i, but also to avoid the namespace error you should do that once. So you can do that like this :
var i:int;
// 1st for loop
for(i = 0; i < 5; i++){
trace('1 : '+i);
}
// 2nd for loop
for(i = 5; i > 0; i--){
trace('2 : ' + i);
}
If you only need the variable i within the loop itself and don't need the variable beyond the scope of the loop, you can also declare it within the loop parameters:
for(var i:int = 0; i < 5; i++) {
trace(i);
}
In terms of performance it's a marginal difference, however it's generally a good practice to declare variables only within the scope in which they will be used.

How to exit a loop (while loop) with an if statement from a function called within the loop?

So like:
void aLoop(){
int i = 0;
while(i < 10){
aFunction();
i++;
}
}
int aFunction(int i){
if(aVariable == 1){
i = 10;
}
if(aVariable != 1){
statement;
statement;
i = i;
}
return i;
}
Where aFunction() will be called for each i (0,1,2,3,...,9) and for each call will satisfy either the first if statement or the second.
Assuming all functions and variables are declared, would this be able to stop the while loop if aVariable == 1?
How else could you accomplish the same thing?
I'm really inexperienced with programming.
FIXED:
void aLoop(){
int i = 0;
while(i < 10){
i = aFunction(i);
i++;
}
}
int aFunction(int i){
if(aVariable == 1){
i = 10;
}
if(aVariable != 1){
statement;
statement;
i = i;
}
return i;
}
instead of
aFunction(x);
just use
i = aFunction(x);
use return to terminate a method.
USe break to terminate a for/ while loop or in a switch statement.
void aLoop(){
int i = 0;
do{
aFunction();
System.out.print(i+" ");
i++;
}while(i < 10);
}
Your suggested solution under "FIXED" will work but if you wrote a large program using this approach you'd end up with software that would be very complex and very costly to work on. This is because aFunction is dependent on the function aLoop that calls it. Functions should ideally be independent of each other, whereas aFunction only works if it's being called from a while loop. You almost never want a called function to be dependent on the structure of the function that calls it.
Try to code so that the the responsibilities or "intentions" of each part of the program are clear, so that any dependencies are minimal and obvious. E.g. here you could write
void aLoop(){
bool continueProcessing = true;
for(int i=0;
continueProcessing && i < 10;
i++) {
continueProcessing = aFunction(i);
}
}
int aFunction(int i){
bool stillProcessing = aVariable != 1;
if (stillProcessing) {
statement;
statement;
}
return stillProcessing;
}
Of course, in aLoop there are some other options which amount to the same thing. You could carry on with a while loop (I think for is clearer). Also, you could break out of the loop instead of having an extra continueProcessing variable.
void aLoop(){
for(int i=0; i < 10; i++) {
if (!aFunction(i))
break;
}
}
Finally I'm not sure you even need to pass the variable i into aLoop. If you don't, or some other data is more appropriate, it would be better to change this too.

Using Prettify with angle brackets

I want to include this java code in my blog (this is with the enclosing pre's):
<pre class="prettyprint">
public Vector<Instruction> decodeTree(Tree<String> gene) {
Vector<Instruction> ret = new Vector<Instruction>();
ret.add(decodeString(gene.getValue()));
Vector<Tree<String>> currentLayer = gene.getChildren();
Vector<Tree<String>> nextLayer = new Vector<Tree<String>>();
for(int i=0; i<currentLayer.size(); i++) {
for(Tree<String> t: currentLayer.get(i).getChildren()) {
nextLayer.add(t);
}
}
</pre>
But because it has several angle brackets, Blogger goes in and autocompletes all the inferred tags, transforming that chunk into the following:
<pre class="prettyprint">public Vector<instruction> decodeTree(Tree<string> gene) {
Vector<instruction> ret = new Vector<instruction>();
ret.add(decodeString(gene.getValue()));
Vector<tree tring="">> currentLayer = gene.getChildren();
Vector<tree tring="">> nextLayer = new Vector<tree tring="">>();
for(int i=0; i<currentlayer .size="" for="" i="" ree="" tring=""> t: currentLayer.get(i).getChildren()) {
nextLayer.add(t);
}
}
</currentlayer></tree></tree></tree></instruction></instruction></string></instruction></pre>
Which then shows up as:
public Vector decodeTree(Tree gene) {
Vector ret = new Vector();
ret.add(decodeString(gene.getValue()));
Vector> currentLayer = gene.getChildren();
Vector> nextLayer = new Vector>();
for(int i=0; i t: currentLayer.get(i).getChildren()) {
nextLayer.add(t);
}
}
Which is different from the code I'm trying to present. I think the problem originates in the html confusing my things with angle brackets with HTML tags. Is there a way I could get the parser to ignore all that? I tried changing all the angle brackets to &gt and &lt and got the following output:
public Vector&ltInstruction&gt decodeTree(Tree&ltString&gt gene) {
Vector&ltInstruction&gt ret = new Vector&ltInstruction&gt();
ret.add(decodeString(gene.getValue()));
Vector&ltTree&ltString&gt&gt currentLayer = gene.getChildren();
Vector&ltTree&ltString&gt&gt nextLayer = new Vector&ltTree&ltString&gt&gt();
for(int i=0; i&ltcurrentLayer.size(); i++) {
for(Tree&ltString&gt t: currentLayer.get(i).getChildren()) {
nextLayer.add(t);
}
}
html entities are terminated with a semicolon:
<
>

shuffle card deck issues in language agnostic [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Not so long ago I was in an interview, that required solving two very interesting problems. I'm curious how would you approach the solutions.
Problem 1 :
Product of everything except current
Write a function that takes as input two integer arrays of length len, input and index, and generates a third array, result, such that:
result[i] = product of everything in input except input[index[i]]
For instance, if the function is called with len=4, input={2,3,4,5}, and index={1,3,2,0}, then result will be set to {40,24,30,60}.
IMPORTANT: Your algorithm must run in linear time.
Problem 2 : ( the topic was in one of Jeff posts )
Shuffle card deck evenly
Design (either in C++ or in C#) a class Deck to represent an ordered deck of cards, where a deck contains 52 cards, divided in 13 ranks (A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K) of the four suits: spades (?), hearts (?), diamonds (?) and clubs (?).
Based on this class, devise and implement an efficient algorithm to shuffle a deck of cards. The cards must be evenly shuffled, that is, every card in the original deck must have the same probability to end up in any possible position in the shuffled deck.
The algorithm should be implemented in a method shuffle() of the class Deck:
void shuffle()
What is the complexity of your algorithm (as a function of the number n of cards in the deck)?
Explain how you would test that the cards are evenly shuffled by your method (black box testing).
P.S. I had two hours to code the solutions
First question:
int countZeroes (int[] vec) {
int ret = 0;
foreach(int i in vec) if (i == 0) ret++;
return ret;
}
int[] mysticCalc(int[] values, int[] indexes) {
int zeroes = countZeroes(values);
int[] retval = new int[values.length];
int product = 1;
if (zeroes >= 2) { // 2 or more zeroes, all results will be 0
for (int i = 0; i > values.length; i++) {
retval[i] = 0;
}
return retval;
}
foreach (int i in values) {
if (i != 0) product *= i; // we have at most 1 zero, dont include in product;
}
int indexcounter = 0;
foreach(int idx in indexes) {
if (zeroes == 1 && values[idx] != 0) { // One zero on other index. Our value will be 0
retval[indexcounter] = 0;
}
else if (zeroes == 1) { // One zero on this index. result is product
retval[indexcounter] = product;
}
else { // No zeros. Return product/value at index
retval[indexcounter] = product / values[idx];
}
indexcouter++;
}
return retval;
}
Worst case this program will step through 3 vectors once.
For the first one, first calculate the product of entire contents of input, and then for every element of index, divide the calculated product by input[index[i]], to fill in your result array.
Of course I have to assume that the input has no zeros.
Tnilsson, great solution ( because I've done it the exact same way :P ).
I don't see any other way to do it in linear time. Does anybody ? Because the recruiting manager told me, that this solution was not strong enough.
Are we missing some super complex, do everything in one return line, solution ?
A linear-time solution in C#3 for the first problem is:-
IEnumerable<int> ProductExcept(List<int> l, List<int> indexes) {
if (l.Count(i => i == 0) == 1) {
int singleZeroProd = l.Aggregate(1, (x, y) => y != 0 ? x * y : x);
return from i in indexes select l[i] == 0 ? singleZeroProd : 0;
} else {
int prod = l.Aggregate(1, (x, y) => x * y);
return from i in indexes select prod == 0 ? 0 : prod / l[i];
}
}
Edit: Took into account a single zero!! My last solution took me 2 minutes while I was at work so I don't feel so bad :-)
Product of everything except current in C
void product_except_current(int input[], int index[], int out[],
int len) {
int prod = 1, nzeros = 0, izero = -1;
for (int i = 0; i < len; ++i)
if ((out[i] = input[index[i]]) != 0)
// compute product of non-zero elements
prod *= out[i]; // ignore possible overflow problem
else {
if (++nzeros == 2)
// if number of zeros greater than 1 then out[i] = 0 for all i
break;
izero = i; // save index of zero-valued element
}
//
for (int i = 0; i < len; ++i)
out[i] = nzeros ? 0 : prod / out[i];
if (nzeros == 1)
out[izero] = prod; // the only non-zero-valued element
}
Here's the answer to the second one in C# with a test method. Shuffle looks O(n) to me.
Edit: Having looked at the Fisher-Yates shuffle, I discovered that I'd re-invented that algorithm without knowing about it :-) it is obvious, however. I implemented the Durstenfeld approach which takes us from O(n^2) -> O(n), really clever!
public enum CardValue { A, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, J, Q, K }
public enum Suit { Spades, Hearts, Diamonds, Clubs }
public class Card {
public Card(CardValue value, Suit suit) {
Value = value;
Suit = suit;
}
public CardValue Value { get; private set; }
public Suit Suit { get; private set; }
}
public class Deck : IEnumerable<Card> {
public Deck() {
initialiseDeck();
Shuffle();
}
private Card[] cards = new Card[52];
private void initialiseDeck() {
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 13; ++j) {
cards[i * 13 + j] = new Card((CardValue)j, (Suit)i);
}
}
}
public void Shuffle() {
Random random = new Random();
for (int i = 0; i < 52; ++i) {
int j = random.Next(51 - i);
// Swap the cards.
Card temp = cards[51 - i];
cards[51 - i] = cards[j];
cards[j] = temp;
}
}
public IEnumerator<Card> GetEnumerator() {
foreach (Card c in cards) yield return c;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
foreach (Card c in cards) yield return c;
}
}
class Program {
static void Main(string[] args) {
foreach (Card c in new Deck()) {
Console.WriteLine("{0} of {1}", c.Value, c.Suit);
}
Console.ReadKey(true);
}
}
In Haskell:
import Array
problem1 input index = [(left!i) * (right!(i+1)) | i <- index]
where left = scanWith scanl
right = scanWith scanr
scanWith scan = listArray (0, length input) (scan (*) 1 input)
Vaibhav, unfortunately we have to assume, that there could be a 0 in the input table.
Second problem.
public static void shuffle (int[] array)
{
Random rng = new Random(); // i.e., java.util.Random.
int n = array.length; // The number of items left to shuffle (loop invariant).
while (n > 1)
{
int k = rng.nextInt(n); // 0 <= k < n.
n--; // n is now the last pertinent index;
int temp = array[n]; // swap array[n] with array[k] (does nothing if k == n).
array[n] = array[k];
array[k] = temp;
}
}
This is a copy/paste from the wikipedia article about the Fisher-Yates shuffle. O(n) complexity
Tnilsson, I agree that YXJuLnphcnQ solution is arguably faster, but the idee is the same. I forgot to add, that the language is optional in the first problem, as well as int the second.
You're right, that calculationg zeroes, and the product int the same loop is better. Maybe that was the thing.
Tnilsson, I've also uset the Fisher-Yates shuffle :). I'm very interested dough, about the testing part :)
Trilsson made a separate topic about the testing part of the question
How to test randomness (case in point - Shuffling)
very good idea Trilsson:)
YXJuLnphcnQ, that's the way I did it too. It's the most obvious.
But the fact is, that if you write an algorithm, that just shuffles all the cards in the collection one position to the right every time you call sort() it would pass the test, even though the output is not random.
Shuffle card deck evenly in C++
#include <algorithm>
class Deck {
// each card is 8-bit: 4-bit for suit, 4-bit for value
// suits and values are extracted using bit-magic
char cards[52];
public:
// ...
void shuffle() {
std::random_shuffle(cards, cards + 52);
}
// ...
};
Complexity: Linear in N. Exactly 51 swaps are performed. See http://www.sgi.com/tech/stl/random_shuffle.html
Testing:
// ...
int main() {
typedef std::map<std::pair<size_t, Deck::value_type>, size_t> Map;
Map freqs;
Deck d;
const size_t ntests = 100000;
// compute frequencies of events: card at position
for (size_t i = 0; i < ntests; ++i) {
d.shuffle();
size_t pos = 0;
for(Deck::const_iterator j = d.begin(); j != d.end(); ++j, ++pos)
++freqs[std::make_pair(pos, *j)];
}
// if Deck.shuffle() is correct then all frequencies must be similar
for (Map::const_iterator j = freqs.begin(); j != freqs.end(); ++j)
std::cout << "pos=" << j->first.first << " card=" << j->first.second
<< " freq=" << j->second << std::endl;
}
As usual, one test is not sufficient.