From a string of 3 numbers to 3 integers I'm solving some puzzles to learn Rust. A problem I faced is to turn a string of 3 integers into 3 integers. I succeeded with the following example:

fn main() {
    let mut it = "   455   123   42  ".split_whitespace();
    let (a, b, c) = match (it.next(), it.next(), it.next()) {
        (Some(a), Some(b), Some(c)) => {
            (a.parse::<i32>().unwrap(),
             b.parse::<i32>().unwrap(),
             c.parse::<i32>().unwrap())
        }
        _ => panic!("Oops"),
    };

    println!("{:?}", (a, b, c));
}

However, this code appears to have bad quality:

bad error handling
does not scale (works only for 3) with N integers.

How can I improve this code?

I'd write the code as

fn main() {
    let input = "   455   123   42  ";

    let numbers: Result<Vec<i32>, _> = input
        .split_whitespace()
        .map(str::parse)
        .collect();

    println!("{:?}", numbers);
}

As mentioned in a comment, iterators are very idiomatic in Rust. The Iterator trait is the main documentation to check out. Once you have an iterator, such as by calling split_whitespace, you can do powerful things.

In this case, we can map a closure or a function across each element in the iterator, converting it from one type to another. Although we could have used map(|the_string| the_string.parse()), I prefer the shorter form of syntax when I can use it.

We converted each element using str::parse, which returns a Result, one of Rust's main error handling types. At this point, each element from the iterator will be a Result, but we don't know what type it is yet! parse is powerful in that you can parse to many types, but that power comes at a cost — you have to specify what type you want to parse to. In the original code, the turbofish operator was used (::<>), but I'm not the biggest fan of the fish.

After all this code, we haven't really done anything yet. Rust iterators don't do anything until you pull values from them via next. We could call next over and over ourselves, but in this case I'd like a collection of all the values. That's where collect comes into play.

Similar to str::parse, collect allows the caller to specify what type should be collected into. This allows us to collect into a Vec or a HashSet or many other types. In this case, we can collect into Result. If any of the iterator values were invalid, the entire collection will be invalid with the first found error. Otherwise, we will construct a Vec. Here is where we finally specify what type to parse into as well: an i32. We leave the error type up to the compiler by using the underscore _; once we have specified what kind of type to parse to, we also specify the error type.

To wrap it all up, we print the value to the user using the Debug formatter. This will show us if the Result was an Ok with the entire vector of values or an Err along with the error itself.

  bad error handling

I'd point out that your original code has more error handling compared to many other languages, just because of Rust. For example, each call to unwrap or panic is error handling that other languages might have deferred to runtime (or never!). You handled the cases of the iterator being too short (although see below) as well as when the number failed to parse.

Your error reporting mechanism is fairly basic: the program ends when an error is encountered. There's nothing wrong with that though. It's far better than continuing on when you don't know how to!

As a side note, it's undefined behavior what the result of calling Iterator::next after it returns None the first time. The iterator is free to return nonsense values. If you need to call an next multiple times without checking the value in between each call, you should fuse the iterator, ensuring it will always return None after the first None.


Recursive string reverse function I'm studying C on K&R and now I'm facing a recursion exercise that states:

  Write a recursive version of the function reverse(s), which reverses the string s in place.

I've written the code below and I'm pretty sure that it works.  I'll be glad to receive some critiques about it.

Reverse function:

/* reverse: reverse string s in place */
void reverse(char s[])
{
    static int i, j = 0;
    int c;

    if (i == 0) {
        i = 0;
        j = strlen(s)-1;
    }
    c = s[i];
    s[i] = s[j];
    s[j] = c;
    i++;
    j--;
    while(i < j)
        reverse(s);
}

Main:

#include <stdio.h>
#include <string.h>

#define MAXLINE 100

void reverse(char s[]);

int main(void)
{
    char s[MAXLINE] = "foo bar baz";

    reverse(s);
    printf("%s\n", s);
    return 0;
}

While this is recursive, it entirely misses the point.  As the while loop will only ever execute once (because the function it calls only returns when i < j it could just as well have been an if, and thus all you've got is tail-recursion.

What you have is equivalent to the following, but impossible to call twice and maybe less efficient:

void reverse(char s[])
{
    int i = 0, j = strlen(s)-1;
    int c;
    while (i < j) {
        c = s[i];
        s[i] = s[j];
        s[j] = c;
        i++;
        j--;
    }
}

That's obviously not recursive.  The way you'd do it recursively is always swap the outer two characters of the string and then pass pointers to the beginning and end of a substring along.

Apart from that, you're initialising j but not i, which makes little sense: both will be 0 initially anyway, so at least be consistent.  You're also not using MAXLINE, so you might as well get rid of it (if C allows it).  You're also not checking for a NULL being passed in.


Simple string-root detection in a string-family (This problem is related to Simple string-split by root and sufix algorithm)

There are many ways to find a "common root" of a list of similar strings, that begins with the same substring... The question is what the best way (faster and elegant)?  Do you know a book or library with these algorithms?

Example: in the set {"foo2", "foo1", "foofo"} the root is "foo".

In practical use we need also ignore extrange itens, so we can expect the same "foo" root in the set {"hello", "foo2", "foo1", "foofo", "bye"}. A "root minimal length" parameter is also a practical issue.

Here is a sample and a first candidate algorithm:

  $words = array('i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', 'your', 'yours',
   'yourself', 'yourselves', 'he', 'him', 'his', 'himself', 'she', 'her', 'hers', 'herself',
   'it', 'its', 'itself', 'they', 'them', 'their', 'theirs', 'themselves', 'what', 'which',
   'who', 'whom', 'this', 'that', 'these', 'those', 'am', 'is', 'are', 'was', 'were', 'be',
   'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', 'did', 'doing', 'a', 'an',
   'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', 'at', 'by', 'for',
   'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after',
   'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under',
   'again', 'further', 'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all',
   'any', 'both', 'each', 'few', 'more', 'most', 'other', 'some', 'such', 'no', 'nor', 'not',
   'only', 'own', 'same', 'so', 'than', 'too', 'very', 's', 't', 'can', 'will', 'just', 'don',
   'should', 'now');

  /**
   * Get the common start-string of two strings.
   * @param $a string.
   * @param $b string with probable common root.
   * @return string $root or empty.
   * @see this function can feed the root for str_splitByRoot() function.
   */
  function str_getRoot($a,$b) {
        $rootLen = strspn($b ^ $a, "\0"); // length before difference.
        return substr($a,0,$rootLen);
  }

  /**
   * Get the common start-string of many strings.
   * The algorithm splits the string by its differences.
   * @param $a array of strings.
   * @param $b string with probable common root, or integer for array index.
   * @return array of strings with $root and family.
   */
  function array_getRoot($a,$b='',$minLen=1) {
    if (is_integer($b))
        $b = $a[$b];
    if (!$b) $b=$a[0];
    $family = array();
    foreach ($a as $item) {
        $r = str_getRoot($item,$b);
        if (strlen($r)>=$minLen) {
            $family[]=$item;
            if ($r!=$b) $b=$r;
        } //if
    } // for
    array_unshift($family,$b);
    return  $family;
  }

Applying in the example:

$list = array("foo2", "hello", "foo1", "foofo", "bye");
$fam = array_getRoot($list);
print "\nThe root of list is ".array_shift($fam); // foo

Using to show the roots of the $words list:

  sort($words); // not necessary
  foreach($words as $i){
       $fam4 = array_getRoot($words,$i,4);
       $root = array_shift($fam4);
       if (count($fam4)>1)
            print "\n * $i - ($root) ".join(', ',$fam4);
       else { // repeate da same procedure:
            $fam3 = array_getRoot($words,$i,3);
            $root = array_shift($fam3);
            if (count($fam3)>1)
                 print "\n * $i - ($root) ".join(', ',$fam3);
       }
  }

Some results:

* about - (abo) about, above
* again - (again) again, against
* her   - (her) her, here, hers, herself
* hers  - (hers) hers, herself
* you   - (you) you, your, yours, yourself, yourselves
* yourself - (your) your, yours, yourself, yourselves

(this is not a good answer because... the answer needs performance analysis and comparison with alternative algorithms)

Only to show a tested and "unified" (str+array) algorithm... A "code" based on the defined (see question's statement) functions,

  function str_getRoot2($a,$b='',$minLen=1) { // "2" to avoid recurrence
    if (is_array($a)) // and $b is a seed.
       return array_getRoot($a,$b,$minLen);
    else  // $b is a root
       return str_getRoot($a,$b);
  }

Complete code, with an aditional retFamily parameter, and recurrence:

  /**
   * Get the commom start-string of two or more strings.
   * @version v1.2 of 2015-06-11.
   * @param $a mix, string for final operation, or array for scan.
   * @param $b string with probable commom root, or integer for array index.
   * @param $retFamily boolean for show "family".
   * @return string $root.
   * @see http://codereview.stackexchange.com/q/92700
   */
  function str_getRoot($a,$b='',$minLen=1,$retFamily=false) {
    if (is_array($a)) { // $b is a seed.
        $family = array();
        if (is_integer($b))
            $b = $a[$b];
        if (count($a)>1) {
            foreach ($a as $item) if ($item) {
                if (is_array($item)) die("array of array is invalid");
                if (!$b) $b=$item; // or trim($b)..trim($item)
                $r = str_getRoot($item,$b,$minLen); // go to str
                if ($r) {
                   if ($retFamily) $family[]=$item;
                   if ($r!=$b) $b=$r;
                } //if
            } // for
        } elseif (isset($a) && count($a)>0)
            $family[]= $b = $a[0];
        if ($retFamily) {
            array_unshift($family,$b);
            return $family;
        } else
            return $b;
    } else {  // $b is a root
        $rooLen = strspn($b ^ $a, "\0"); // split by diff
        return ($rooLen>=$minLen)? substr($a,0,$rooLen): '';
    }
  }

Examples of use: get family array with $fam4 = str_getRoot($words,'yourself',4);  or get specific root of a pair by        str_getRoot('yourself','your');


Selecting a div with a blue border and changing its text I have a function that I created in Codepen. It does what I want, where the div that you select gets a blue border and changes its text. But I would like to know if there is any way to make the JavaScript that actually makes this work more compact/efficient.
Codepen
JavaScript
function toggle(el) {
  const contentReference = document.querySelectorAll('.content');
  for (div of contentReference) { div.className = 'content'; }
  el.className = 'content selected';
  const selectedContentReference = document.querySelectorAll('.selectedContent');
  for (div of selectedContentReference) {
    if (div.parentNode.className == 'content') {
      div.className = 'selectedContent contentThatShouldBeHidden';
    }
    else if (div.parentNode.className == 'content selected') {
      div.className = 'selectedContent';
    }
  }
  const notselectedContentReference = document.querySelectorAll('.notselectedContent');
  for (div of notselectedContentReference) {
    if (div.parentNode.className == 'content') {
      div.className = 'notselectedContent';
    }
    else if (div.parentNode.className == 'content selected') {
      div.className = 'notselectedContent contentThatShouldBeHidden';
    }
  }
}

const selectedContentReference = document.querySelectorAll('.selectedContent');
  for (div of selectedContentReference) {
    if (div.parentNode.className == 'content') {
      div.className = 'selectedContent contentThatShouldBeHidden';
    }
    else if (div.parentNode.className == 'content selected') {
      div.className = 'selectedContent';
    }
  }
  const notselectedContentReference = document.querySelectorAll('.notselectedContent');
  for (div of notselectedContentReference) {
    if (div.parentNode.className == 'content') {
      div.className = 'notselectedContent';
    }
    else if (div.parentNode.className == 'content selected') {
      div.className = 'notselectedContent contentThatShouldBeHidden';
    }
  }
```

To be honest this is very over-engineered. The same can be done with very little to no JavaScript by taking advantange of the features of CSS. But one by one.

First off the class name content is bad choice. It is very generic. It runs into the danger to be used in some other context on the same page and it doesn't describe what you are using it for. Something like selectable would be better.

Using className to identify elements is for one verbose, for the other unrelatiabe. An element, for example, that has both the classes content and selected could have a className "content selected" or "selected content" or "content selected someOtherClass", etc. Just because you set it to "content selected" there is no guarantee that it will stay that.
Instead you should use the classList property. It allows you the set, remove, toggle and check for separate classes (and more).
So, for example, the block
const selectedContentReference = document.querySelectorAll('.selectedContent');
for (div of selectedContentReference) {
  if (div.parentNode.className == 'content') {
    div.className = 'selectedContent contentThatShouldBeHidden';
  }
  else if (div.parentNode.className == 'content selected') {
    div.className = 'selectedContent';
  }
}

can become:
const selectedContentReference = document.querySelectorAll('.selectedContent');
for (div of selectedContentReference) {
  const parentIsSelected = div.parentNode.classList.contains("selected");
  div.classList.toggle("contentThatShouldBeHidden", !parentIsSelected);
}

There is more that could be said to the JavaScript, however all this class toggling is unnecessary. By using, for example, the CSS child combinator and the :not pseudo class you can show and hide the approprate texts depending on the selected class on the parent element alone.
Using the same HTML and limiting the toggle function to:
// Moving the list of elements outside the function, because the list doesn't change
const contentReference = document.querySelectorAll('.content');

function toggle(el) {
  for (div of contentReference) { div.classList.remove("selected"); }
  el.classList.add("selected");
}

and following CSS:
.content:not(.selected) > .selectedContent,
.content.selected > .notselectedContent {
   display: none;
}

And as I mentioned at the beginning it is possible to do this without JavaScript. HTML has such a toggling feature built in: radio buttons. And CSS can be used to style elements depending on if a radio button is selected (:checked) or not, even if the radio button isn't visible.
https://jsfiddle.net/27kw8qe1/


Codewars kata - "Repetitive Sequence" I am trying to solve the following Codewars kata.
We are given a list as
seq = [0, 1, 2, 2]
We will have to write a function that will, firstly, add elements in the list using the following logic.
if n = 3 and as seq[n]=2, the new list will be seq = [0, 1, 2, 2, 3, 3]
if n = 4 and as seq[n]=3, the new list will be seq = [0, 1, 2, 2, 3, 3, 4, 4, 4]
if n = 5 and as seq[n]=3, the new list will be seq = [0, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5] and so on.
Then the function will return the n-th element of the list.
Some elements of the list:
[0, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13,
14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16,
17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19,
20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21]
Constraint for Python:
0 <= n <= 2^41
My code runs successfully in my system for any value of n, including n=2^41 (within 2.2s). But it times out in Codewars. Can anyone help me in optimizing my code? Thanks in advance.
My code:
def find(n):
    arr = [0, 1, 2, 2]
    if n <= 3:
        return arr[n]
    else:
        arr_sum = 5
        for i in range(3, n+1):
            arr_sum += i * arr[i]
            if arr_sum >= n:
                x = (arr_sum - n) // i
                return len(arr) + arr[i] - (x+1)
            else:
                arr += [i] * arr[i]

Building the list takes a lot of time. Note that your  arr += [i] * arr[i] repeats the same value i over and over again. This can be much compressed by just storing repeat(i, arr[i]) instead. This succeeds in about 6 seconds, well under their 12 seconds limit:
from itertools import chain, repeat

def find(n):
    if n <= 3:
        return [0, 1, 2, 2][n]
    arr = [[2]]
    arr_sum = 5
    arr_len = 4
    for i, arr_i in enumerate(chain.from_iterable(arr), 3):
        arr_sum += i * arr_i
        if arr_sum >= n:
            x = (arr_sum - n) // i
            return arr_len + arr_i - (x+1)
        arr.append(repeat(i, arr_i))
        arr_len += arr_i

Note that in the n > 3 case, we start already with the number 3, appending it twice to the list. Thus of the sequence start [0, 1, 2, 2] we only need [2], so I start with arr = [[2]] (which is shorter than [repeat(2, 1)], and chain doesn't mind).

Alternatively... note that you're extending arr much faster than you're consuming it. For n=241, you grow it to over 51 million elements, but you're actually reading fewer than the first 70 thousand. So you could stop truly extending the list at that point. This succeeds in about 4.7 seconds:
def find(n):
    arr = [0, 1, 2, 2]
    if n <= 3:
        return arr[n]
    arr_sum = 5
    arr_len = 4
    for i in range(3, n+1):
        arr_sum += i * arr[i]
        if arr_sum >= n:
            x = (arr_sum - n) // i
            return arr_len + arr[i] - (x+1)
        arr_len += arr[i]
        if arr_len < 70_000:
            arr += [i] * arr[i]

And... you can combine the above two improvements, i.e., apply that if arr_len < 70_000: to the repeat-version. That then succeeds in about 4.5 seconds.
Benchmark results on my PC for n=241:
Your original:   1.795 seconds
My first one:    0.043 seconds (42 times faster)
My second one:   0.041 seconds (44 times faster)
The combination: 0.026 seconds (69 times faster)

Oh and a style comment: You twice do this:
if ...:
    return ...
else:
    ...

The else and the indentation of all the remaining code are unnecessary and I'd avoid it. I've done so in the above solutions.


Summer camp cost calculation using Google Sheets I am making a sheet that adds up the total cost for a summer camp after registration. Each parent can register up to five children. I have already made my code and it works, but there must be a simpler way.

The code looks at the cell, and determines the cost of the program depending on whether the parent chooses after school, before school or both. The prices varies if it is a 4 day week or 5 day week (week 5 of 7 is a short week). The prices are called from another sheet. This process is repeated 35 times (the program is 7 weeks, plus 5 children can be registered).

Here is the code for one child:

=SUM(IF(AA2=Frais!$B$17;Frais!$C$9;IF(AA2=Frais!$B$18;Frais!$C$10;IF(AA2=Frais!$B$19;Frais!$C$11;0)));IF(AB2=Frais!$B$17;Frais!$C$9;IF(AB2=Frais!$B$18;Frais!$C$10;IF(AB2=Frais!$B$19;Frais!$C$11;0)));IF(AC2=Frais!$B$17;Frais!$C$9;IF(AC2=Frais!$B$18;Frais!$C$10;IF(AC2=Frais!$B$19;Frais!$C$11;0)));IF(AD2=Frais!$B$17;Frais!$C$9;IF(AD2=Frais!$B$18;Frais!$C$10;IF(AD2=Frais!$B$19;Frais!$C$11;0)));IF(AE2=Frais!$B$17;Frais!$D$9;IF(AE2=Frais!$B$18;Frais!$D$10;IF(AE2=Frais!$B$19;Frais!$D$11;0)));IF(AF2=Frais!$B$17;Frais!$C$9;IF(AF2=Frais!$B$18;Frais!$C$10;IF(AF2=Frais!$B$19;Frais!$C$11;0)));IF(AG2=Frais!$B$17;Frais!$C$9;IF(AG2=Frais!$B$18;Frais!$C$10;IF(AG2=Frais!$B$19;Frais!$C$11;0))))

This process is repeated 5 times.

Here is a link to the sheet (the cell with the formula is the last one).

Here are some pictures of the sheet:

The data prices are on a separate sheet:

Short and partial answer

Instead of the use nested IF() use INDEX(), MATCH() and IFERROR()

Notes for a complete answer

It could be possible to do a further refinement of the formula by using arrays but the patterns should be understood deeply before to proceed on the implementation of such tools.

EDIT: An array formula was added to the bottom.

Explanation of the short and partial answer

The formula has 34 outer IF(), each of them:

having a cell reference as the value to return when the test returns true. The three values are in the same one column range.
having a nested IF() with another IF()  as the value to return when the test returns false
The last IF returns 0 in when the test returns false.

In cases like the above, using lookup functions will help to have concise formulas that also are usually easy to read and debug.

Formula pattern

IF(AA2=Frais!$B$17,Frais!$C$9,IF(AA2=Frais!$B$18,Frais!$C$10,IF(AA2=Frais!$B$19,Frais!$C$11,0)))

IFERROR(Index(Frais!$C$9:$C$11,Match(AA2,Frais!$B$17:$B$19,0)),0)

Resulting formula

Remark: Google Sheets allow the insertion of breaklines in formula. This could be helpful in complex formulas like the discussed in this Q&A.

=SUM(
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( AA2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( AB2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( AC2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( AD2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$D$9:$D$11, MATCH( AE2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( AF2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( AG2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( CC2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( CD2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( CE2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( CF2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$D$9:$D$11, MATCH( CG2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( CH2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( CI2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( DI2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( DJ2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( DK2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( DL2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$D$9:$D$11, MATCH( DM2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( DN2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( DO2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( EO2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( EP2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( EQ2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( ER2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$D$9:$D$11, MATCH( ES2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( ET2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( EU2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( FU2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( FV2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( FW2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( FX2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$D$9:$D$11, MATCH( FY2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( FZ2, Frais!$B$17:$B$19, 0))),
    IFERROR(INDEX( Frais!$C$9:$C$11, MATCH( GA2, Frais!$B$17:$B$19, 0)))
)

Array formula

The following formula makes use of the array notation and capability of SUM() and VLOOKUP() to work with array formulas.

=ArrayFormula(
    SUM(
        IFERROR(
        VLOOKUP({
            AA2,AB2,AC2,AD2,AF2,AG2,
            CC2,CD2,CE2,CF2,CH2,CI2,
            DI2,DJ2,DK2,DL2,DN2,DO2,
            EO2,EP2,EQ2,ER2,ET2,EU2,
            FU2,FV2,FW2,FX2,FZ2,GA2
        },
        {Frais!$B$17:$B$19, Frais!$C$9:$C$11},2,0),0),
        IFERROR(
            VLOOKUP({
                AE2,
                CG2,
                DM2,
                ES2,
                FY2
            },
            {Frais!$B$17:$B$19,Frais!$D$9:$D$11},2,0),0)
    )
)


Hexadecimal command line file viewer I have been working on a project for several days. It is a command line program for viewing files in hexadecimal. It is usually very fast, but is there any way I could make it more efficient?

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]){
    if(argc == 2){
        FILE *in = fopen(argv[1], "rb");
        if(in == NULL){
            printf("Could not open %s\n", argv[1]);
        }else{
            int i = 0, j, br, ln[8];
            char l[16];
            while((br = fread(&l, 1, 16, in)) > 0){
                printf("%08x ", i);
                i += br;
                for(j = 0; j < br; j++){
                    if(l[j] > 0){
                        printf("%02x ", l[j]);
                    }else{
                        printf("?? ");
                    }
                }
                for(j = 0; j < 16 - br; j++){
                    printf("   ");
                }
                for(j = 0; j < br; j++){
                    if(l[j] > 31 && l[j] < 127){
                        printf("%c", l[j]);
                    }else{
                        printf(".");
                    }
                }
                printf("\n");
            }
            fclose(in);
        }
    }else{
        printf("Please use the syntax 'hex [file]'\n");
    }
    return 0;
}

If a program fails for some reason then it should

Write a diagnostic message to standard error (not standard output),
so that it can not be mistaken for normal output, e.g. when
the program runs in a pipe. strerror(errno) gives you an error
message string corresponding to the last error, e.g.
"No such file or directory" or "Permission denied".
Terminate with a non-zero status code. You can use predefined
exit codes from <sysexits.h> if that is available on your system,
or make up your own.

Combining this with the "Avoiding deep nesting" advice from
Caridorc's answer, the overall structure would be

int main(int argc, char *argv[]) {

    if (argc != 2) {
        fprintf(stderr, "Usage: hex [file]\n");
        exit(EX_USAGE);
    }

    FILE *in = fopen(argv[1], "rb");
    if (in == NULL) {
        fprintf(stderr, "Cannot not open %s: %s\n", argv[1], strerror(errno));
        exit(EX_NOINPUT);
    }

    // ... print hex dump ...

    fclose(in);

    exit(EXIT_SUCCESS); // EXIT_SUCCESS == 0
}

Your variable names are too short and non-descriptive.

i is the current offset into the file. The correct type for
a file offset is off_t.
br is the amount of bytes read. The correct type would
be size_t (which is what fread() returns, so this avoids
a warning when compiling on a 64-bit architecture).
l is a line buffer.

j is OK as a iteration variable, but the scope should be limited to the
for-loop.

The main loop would then start like this:

off_t offset = 0;
size_t bytesRead;
char line[16];

while ((bytesRead = fread(&line, 1, 16, in)) > 0){
    printf("%08llx ", offset);
    offset += bytesRead;
    for (size_t j = 0; j < bytesRead; j++){
        printf("%02x ", line[j]);
    }

I don't know why you want to print a NUL-byte as ??, therefore
I have removed that part.

The padding can be done by printing an empty string
with a field width:

    printf("%*.s", 3*(16 - (int)bytesRead), "");

The remaining part of the main loop is OK, only that I would
generally use more space, at least around parentheses and keywords:

    for (int j = 0; j < bytesRead; j++) {
        if (line[j] > 31 && line[j] < 127) {
            printf("%c", line[j]);
        } else {
            printf(".");
        }
    }
    printf("\n");
}


Spending a target sum, preferably split equally I have a strange programming prompt. I managed to complete an algorithm to solve smaller test entries (which i'll post). One of my test cases has to complete a 200,000 int input and my algorithm isn't practical. I'll post the prompt and my algorithm. How should I go about optimizing the performance to handle large input sizes?

Prompt:

  You and your friend combine your prize tickets at a carnival. You plan
  to get 2 prizes whose total price is exactly M, M-1, or M-2 tickets
  (in that order) if possible. M is how many tickets you decide to
  spend. If there are several prizes that satisfy this condition, you
  want to minimize the difference between ticket cost.

  For example, say you're given M = 5, and prize values of [2,1,4,3]..
  the output would be 2+3=5.

My SLOW solution:

#sequence actually has +2 values. [0] is how many prizes and [last] is M
#ignore the setting
def checkForPrizes(seq):
    M = seq[len(seq)-1] #priori
#    print("M:",M)
    n = seq[0] #number of inputs

    seq = strip2(seq) #removes the +2 from the "n+2" inputs
    quick_sort(seq) #sorts the prize values
#    print("seq:",seq)
    returnList = []
    leftList = seq[0:int(len(seq)/2)]
    rightList = seq[int(len(seq)/2):len(seq)]

    current = seq[int(len(seq)/2)]
    print("current=",current)

#    print("left half:",leftList)
#    print("right half:",rightList)

    s1 = 0 #prize1
    s2 = 0 #prize2

    flag = False #checks the conditions in order

    if (flag is False):
        for i in range(len(leftList)):
            s1 = leftList[i]
            for j in range(len(rightList)):
                s2 = rightList[j]
                if(s1 + s2 == M):
                    returnList = [s1,s2]
 #                   print("[",s1,",",s2,"] ","is exactly M!",sep="")
                    flag = True

    if(flag is False): #try M-1
        for i in range(len(leftList)):
            s1 = leftList[i]
            for j in range(len(rightList)):
                s2 = rightList[j]
                if(s1 + s2 == (M-1)):
                    returnList = [s1,s2]
#                    print("[",s1,",",s2,"] ","is exactly M-1!",sep="")
                    flag = True

    if(flag is False): #try M-2
        for i in range(len(leftList)):
            s1 = leftList[i]
            for j in range(len(rightList)):
                s2 = rightList[j]
                if(s1 + s2 == (M-2)):
                    returnList = [s1,s2]
#                    print("[",s1,",",s2,"] ","is exactly M-2!",sep="")
                    flag = True

    if(flag is False):
        print("NO")
    else:
#        print("sol:",returnList)
        dispVal(returnList[0],returnList[1])

You have still some work to do to get correct results in all cases. Consider M=3 and prizes [2,1,4,3]. Your algorithm sorts the list, splits it in two and considers pairs where one item is from the left half and the other from the right. You will not find the sum 1+2 because both numbers will be in the left half.


Inserting an element into a linked list This program adds an element to the end of a linked list of integers, which is previously keyed in by the user. This works fine on my computer, but I am wondering:

If there is a simpler way to do this (three procedures seems a lot for this)
If any of the code could potentially become problematic during future usage

program InserElement(input, output);
{Has the user type in integers and forms a linked list out of them,
then inserts an element at the end of that linked list and prints the
linked list with the added new element}

{$mode objfpc}{$H+}

uses
  {$IFDEF UNIX}{$IFDEF UseCThreads}
  cthreads,
  {$ENDIF}{$ENDIF}
  Classes;

type
  tRefList = ^tList;
  tList = record
             info : integer;
             next : tRefList
            end;
var
 RefBeginning: tRefList;
 RefEnd : tRefList;
 Number : integer;

   procedure CreateList(var outRefBeginning: tRefList; var OutRefEnd: tRefList);
   { Creates a linear list through user input }
  var
   RefNew : tRefList;

  begin
   writeln('Please key in natural numbers. Key in 0 once you are done. ');
   readln(Number);
   while Number <> 0 do
   begin
     new (RefNew);
     RefNew^.info := Number;
     RefNew^.next := nil;
     if outRefBeginning = nil then
      begin
      outRefBeginning := RefNew;
      OutRefEnd := RefNew;
      end
     else
     begin
       outRefEnd^.next := RefNew;
       outRefEnd := RefNew
     end;
     readln (Number)
   end; { while-loop }
  end; {CreateList}

procedure InsertElement(inNumber : integer; var outRefBeginning : tRefList; var outRefEnd : tRefList);
  { Inserts a new element at the end of the list. outRefBeginning points to the first
  element of that list, outRefEnd points to the last element of it. The Value of inNumber is
  assigned to the record component info of the new element}

  var
   RefNew : tRefList;

  begin
  { Create and initialise new element }
  new(RefNew);
  RefNew^.info := inNumber;
  RefNew^.next := nil;
  { Insert element at the end of the linear list }
  if outRefBeginning = nil then
     begin
     outRefBeginning := RefNew;
     outRefEnd := RefNew
     end
     else
         begin
           outRefEnd^.next := RefNew;
           outRefEnd := RefNew;
         end;
  end;{ InsertElement }

  procedure PrintList;
  { Prints all elements of the linked list }

  var
   RefNew : tRefList;

  begin
   RefNew := RefBeginning;
   while RefNew <>  nil do
   begin
     writeln (RefNew^.info);
     RefNew := RefNew^.next
   end;
  end;

begin
  RefBeginning := nil;
  RefEnd := nil;
  CreateList(RefBeginning, RefEnd);
  InsertElement(5,RefBeginning,RefEnd);
  PrintList;
  readln;
end.

Overall, this is a great start. It's easy to read and understand. Personally, I don't think that 3 procedures is a lot. You have 3 things you need to do: create the initial list, add an element to it, and print out the results. If you didn't have at least 3 procedures, I'd say you were doing something wrong. Anyway, here are some things that could be improved.
Naming
I found the naming a little confusing. Why is it a "ref" list? To what does it refer? (Or what does ref mean in this context if not "reference"?) I think that I would name the list node type a tNode instead of a tList, and I would name the thing that points to it a tList.
I notice also hat some of your variable and argument names begin with lowercase letters and some with uppercase. While Pascal is not typically a case-sensitive language, it's generally considered good practice to be consistent. Often variable names start with a lowercase letter, and types start with an uppercase letter, but it's up to you. It just makes it easier to read when it's consistent.
Types
Better yet, if you're going to keep track of the head and tail separately, I would make another record type, like this:
type
    tNodePtr = ^tNode;
    tNode = record
        info : integer;
        next : tNodePtr;
    end;

    tList = record
        head : tNodePtr;
        tail : tNodePtr;
    end;

Now you can pass a single variable around instead of passing both the head and tail to each procedure. This makes it easier to read the code and less likely that a caller of one of the procedures will accidentally pass the wrong thing for one of the arguments.
Check Your Allocations
There are 2 places where you call new(). You don't ever check the result, though, to see if the allocation succeeded. You need to make sure that the memory was actually allocated before you start writing to it. Otherwise, you'll end up writing over some other data causing a hard-to-find bug, or writing to data you don't have access to and causing a crash.
Delete Stuff When You're Done With It
The other thing you need to do with memory that you allocate from the heap is delete it when you're no longer using it. In this case, that would be at the end of the program. I would write a procedure to delete the nodes in the list. Something like this (and I'm assuming you're using the types I recommended above):
procedure DeleteList(var list : tList)
    var
        nextNode : tNodePtr;
        currNode : tNodePtr;
    begin
        nextNode = list.head;
        currNode = list.head;
        while nextNode <> nil do
        begin
            nextNode = currNode^.next;
            delete(currNode);
            currNode = nextNode;
        end;
        list.head = nil;
        list.tail = nil;
    end;

(Note: It's been a few years since I've written Pascal, so forgive me if I've made any obvious mistakes here!)
Formatting
While this won't affect the running of your program, the formatting of the code can affect how easy it is to read and understand. I would suggest adopting a consistent indentation amount. I see that you sometimes use 1 space, sometimes 2. I would recommend always using 2 or more (my preference is 4, personally), as a single space is not as easy to distinguish as 2 or more.
Also, it looks like in CreateList() the if class has one type of indenting, and the else clause has a different one. I would be consistent about what level of indentation you use for the begin and end keywords.


Best way to handle tap gestures I'm building a small web app primarily for mobile use. I have some widgets that need to handle tap gestures in the expected way, and I don't feel this one feature is reason enough to include JQuery mobile.

I've written the following function for making an element respond to "tap" events:

function bind_tap(el, cb) {
  (function(){
    var touchStarted = false;
    el.addEventListener("click", cb, false);
    el.addEventListener("touchstart", function(){
      touchStarted = true;
    }, false);
    el.addEventListener("touchcancel", function(){
      touchStarted = false;
    }, false);
    el.addEventListener("touchleave", function(){
      touchStarted = false;
    }, false);
    el.addEventListener("touchend", function(){
      touchStarted = false;
      if (touchStarted) cb();
    }, false);
  })();
};

It seems to work fine, but I'm wondering if it could/should be improved in any way, either in that parts of it are redundant (I'm not sure what touchcancel really means) or to handle some edge case I haven't thought of.

Solution so far:

function bindTap(element, callback, useCapture) {
  var touchStarted = false, touchFinished = null;
  useCapture = !!useCapture;
  function startTap() {
      touchStarted = true;
      touchFinished = false;
  }
  function cancelTap() {
      touchStarted = false;
  }
  function completeTap() {
      if (touchStarted && !touchFinished) {
          callback.apply(this, arguments);
          touchFinished = true;
      }
  }
  function handleClick() {
      touchStarted = true;
      completeTap.apply(this, arguments);
  }
  element.addEventListener("click", handleClick, useCapture);
  element.addEventListener("touchstart", startTap, useCapture);
  element.addEventListener("touchcancel", cancelTap, useCapture);
  element.addEventListener("touchleave", cancelTap, useCapture);
  element.addEventListener("touchend", completeTap, useCapture);
}

For your purposes, you can treat touchleave and touchcancel the same way. The difference is touchleave happens when the touch point leaves the element and moves somewhere else in the document, and touchcancel happens when the touch point leaves the document entirely, like moving outside the browser window's content area or onto a plugin.

Minor stuff:

The functions you use to handle touchleave and touchcancel are exactly the same, so you could eliminate redundancy by reusing the same function for both.
The third argument to addEventListner, useCapture, defaults to false, so you don't need to explicitly pass it in.
The IIFE inside of bind_tap serves no purpose, it can be removed.
JavaScript identifiers should use camelCase; bind_tap is not an appropriate name for an identifier.
Variables named like el and cb aren't a big deal for internal stuff, but for code that's exposed as part of your API (function parameters) they should probably have fully descriptive names.
You have an extra semicolon at the end of your code. Function declarations are not separated by (or terminated with) semicolons.

Major stuff:

In your touchend handler you set touchStarted to false and then check it for a truthy value on the next line; if (touchStarted) cb();. The callback will never fire there. The code is only working because you have the callback handling the click event. When you fix this, you'll need to make sure that the callback only fires once. I added touchFinished in the example below to address that.
You probably want to pass the this binding and any arguments on to the callback.

Something like this should work (not tested).

function bindTap(element, callback) {
    var touchStarted = false,
        touchFinished = false;

    function startTap() {
        touchStarted = true;
    }

    function cancelTap() {
        touchStarted = false;
    }

    function endTap() {
        if (touchStarted && !touchFinished) {
            callback.apply(this, arguments);
            touchFinished = true;
        }
    }

    function handleClick() {
        touchStarted = true;
        endTap.apply(this, arguments);
    }

    element.addEventListener("click", handleClick);
    element.addEventListener("touchstart", startTap);
    element.addEventListener("touchcancel", cancelTap);
    element.addEventListener("touchleave", cancelTap);
    element.addEventListener("touchend", endTap);
}


Searching for column-indices of a multi-dimensional array that match multiple conditions (one condition per row) I have written a script that I believe works and covers all edge-cases. I am curious about ways to improve upon speed. While the given example below covers a multi-dimensional array of 3 rows x 10 columns, my actual use case will be n rows x ~70,000 columns (where n depends upon the number of data parameters being searched).

Given individual arrays of data points, the goal is to combine them into a multi-dimensional array and find the columns in which all conditions are satisfied. If the same column of each row satisfies a given condition, the index that corresponds to that column is output; otherwise, an error is raised.

I have included a small class named MaskOps() because it has many other functions relevant in my main code, though I've only included the parts relevant to the goal in this question.

import numpy as np

class MaskOps():

    @staticmethod
    def get_base(shape, value, dtype=int):
        """ This function produces a base-mask, the values of which may be overwritten. """
        if isinstance(value, (float, int)):
            res = np.ones(shape, dtype=dtype) * value
        elif isinstance(value, str):
            res = np.array([value for idx in range(np.prod(shape))]).reshape(shape)
        return res

    @staticmethod
    def alternate_base(shape, key):
        """ This function creates base-masks that consist of one of two value; the value depends on the index input as the parameter key. """
        if key % 2 == 0:
            value = 0.25
        else:
            value = 0.5
        return MaskOps().get_base(shape, value, dtype=float)

MO = MaskOps()

Sample Data

row_a = np.linspace(1, 10, 10)
row_b = row_a * 10
row_c = row_a + 20
data = np.array([row_a, row_b, row_c])

Main Search Function

def core_algorithm(ndata, search_value):
    """
    This function prints values and indices that match the search condition.

    An index mask of non-zero values is created per row of the input data,
    and the values of the index mask are overwritten to be a zero at each
    column at which the condition is satisfied - per condition and row of data.
    Then, the columns of the index masks that sum to zero are the column-indices
    that satisfy all input conditions.
    """

    print("\nSEARCH VALUES:\n{}\n".format(search_value))
    print("NDATA:\n{}\n".format(ndata))

    bases = np.array([MO.alternate_base(len(ndata.T), idx) for idx in range(len(ndata))])
    print("ORIGINAL BASES:\n{}\n".format(bases))

    locs = np.array([np.where(ndata[idx] == search_value[idx])[0] for idx in range(len(search_value))])
    print("LOCS:\n{}\n".format(locs))

    for idx in range(len(bases)):
        bases[idx][locs[idx]] = 0
    print("UPDATED BASES:\n{}\n".format(bases))

    res_idx = np.where(np.sum(bases, axis=0) == 0)[0]
    print("RES COLUMN:\n{}\n".format(res_idx))

    if len(res_idx) == 0:
        raise ValueError("match could not be found")

    res_val = np.array([ndata[idx][res_idx] for idx in range(len(ndata))])
    print("VALUES FROM COL-INDICES\n{}\n".format(res_val))

core_algorithm(data, search_value=(3, 30, 23)) # works successfully
# core_algorithm(data, search_value=(3, 30, 24)) # throws an error

One alternative method I have yet to explore is using set intersection/unions to find the same indices, though I'm not sure if that would necessarily improve performance. I posted a similar example some time ago, though I later realized the code had bugs and could have been improved upon as an example.

Python is not Java

Not everything needs to be in a class

class MaskOps():

    @staticmethod
    def get_base(shape, value, dtype=int):
        """ This function produces a base-mask, the values of which may be overwritten. """
        if isinstance(value, (float, int)):
            res = np.ones(shape, dtype=dtype) * value
        elif isinstance(value, str):
            res = np.array([value for idx in range(np.prod(shape))]).reshape(shape)
        return res

    @staticmethod
    def alternate_base(shape, key):
        """ This function creates base-masks that consist of one of two value; the value depends on the index input as the parameter key. """
        if key % 2 == 0:
            value = 0.25
        else:
            value = 0.5
        return MaskOps().get_base(shape, value, dtype=float)

MO = MaskOps()

can just be

def get_base(..):
    ...
def alternate_base(...):
    ...

looping

Python has a lot of elegant looping constructs

for idx in range(len(bases)):
    bases[idx][locs[idx]] = 0

for example is not one of them. This can be done with zip

for base, loc in zip(bases, locs):
     base[loc] = 0

Check out this talk (slides) for tips on enumerate, zip, generators etc.

return values, don't print them

When you print the value, it makes it harder to reuse this part of the code in another place. Better would be to split the core_algorithm in different functions all doing their part of the calculation, so you can test each of these parts individually, and decide how to print the result

use numpy  (#1)

You have a lot of numpy arrays that you make from list comprehensions. It would be a lot easier and clearer to vectorize this, and use numpy's large arsenal of native methods

def get_base(shape, value, dtype=int):
    """ This function produces a base-mask, the values of which may be overwritten. """
    if isinstance(value, (float, int)):
        res = np.ones(shape, dtype=dtype) * value
    elif isinstance(value, str):
        res = np.array([value for idx in range(np.prod(shape))]).reshape(shape)
    return res

can be more easily written as

def get_base(shape, value, dtype=int):
    dtypes = {int: int, float: float}
    if not dtype:
        dtype = dtypes.get(type(value), object)
    return np.ones(shape, dtype=dtype) * value

use numpy (#2)

Instead of making this boolean mask yourself, why not just do:

mask = data == [[i] for i in search_value]
collapsed_mask = mask.all(axis=0)
result = data[:, collapsed_mask]


Function to check that a Python list contains only True and then only False I would like to only allow lists where the first n elements are True and then all of the remaining elements are False. I want lists like these examples to return True:

[]
[True]
[False]
[False, False]
[True, False]
[True, False, False]
[True, True, True, False]

And lists like these to return False:

[False, True]
[True, False, True]

That is, any list that can we written as [True] * n + [False] * m for n, m integers in the interval [0, infty).

I am currently using a function called check_true_then_false, but I feel like there is probably a neater way of doing this. The code doesn't need to be fast, as this will only be run once (not inside a loop) and the lists will short (single digit lengths).

def check_true_then_false(x):
    n_trues = sum(x)
    should_be_true = x[:n_trues]  # get the first n items
    should_be_false = x[n_trues:len(x)]  # get the remaining items
    # return True only if all of the first n elements are True and the remaining
    # elements are all False
    return all(should_be_true) and not any(should_be_false)

Testing shows that it produces the correct output:

test_cases = [[True],
              [False],
              [True, False],
              [True, False, False],
              [True, True, True, False],
              [False, True],
              [True, False, True]]
print([check_true_then_false(test_case) for test_case in test_cases])
# expected output: [True, True, True, True, True, False, False]

You can just use x[n_trues:] rather than x[n_trues:len(x)].
Your comments don't really say more than the code. And so I'd recommend removing the comments.
If you want to keep your code documented use docstrings, which can be exported to your documentation via tools like Sphinx.
As commented by Konrad Rudolph, you can remove the and not any(should_be_false) as this will always fail if the all fails.

def check_true_then_false(x):
    """Check first n values are True and the rest are False."""
    return all(x[:sum(x)])

If you want your code to work with iterators, not just sequences then you can instead use:

def check_true_then_false(it):
    """Check first n values are True and the rest are False."""
    it = iter(it)
    # Takes advantage of the iterating side effect, where it consumes the iterator.
    # This allows `all` to simultaneously checks `it` starts with trues and advances `it`.
    return all(it) or not any(it)

For the following two inputs all will result in:

>>> all([True] * n)
True
>>> all([True] * n + [False, ...])
False

However it will mean that it is still [...] as all and any are lazy. Meaning that we just need to check the rest are false. Meaning all slices the iterator for you without you having to. Leaving any with:

>>> any([False] * n)
False
>>> any([False] * n + [True, ...])
True


Project Euler 348: Sum of a square and a cube Many numbers can be expressed as the sum of a square and a cube. Some of them in more than one way.

  Consider the palindromic numbers that can be expressed as the sum of a
  square and a cube, both greater than 1, in exactly 4 different ways.
  For example, 5229225 is a palindromic number and it can be expressed
  in exactly 4 different ways:

  22852 + 203

  22232 + 663

  18102 + 1253

  11972 + 1563

  Find the sum of the five smallest such palindromic numbers.

I used brute force; it solves in around 11 seconds. I thought about it for some time but couldn't come up with any obvious optimizations, the problem seems built for brute force. Any suggestions?

Note that I'm using PyPy which makes math code run much faster...

"""Find the sum of the five smallest palindromic numbers
that can be expressed as the sum of a square and a cube."""

from math import log10
from collections import Counter
from timeit import default_timer as timer

def is_palindrome(n):
    length = int(log10(n))
    while length > 0:
        right = n % 10
        left = n / 10**length
        if right != left:
            return False
        n %= 10**length
        n /=10
        length -= 2
    return True

start = timer()
palindromes = Counter()

for square in xrange(1, 30000):
    squared = square**2
    for cube in xrange(1, 3000):
        cubed = cube**3
        total = squared + cubed
        if is_palindrome(total): palindromes[total] += 1

ans = sum(x[0] for x in palindromes.most_common(5))
elapsed_time = timer() - start
print "Found %d in %d s." % (ans, elapsed_time)

@Kevin Brown is correct, your programme runs in 18 seconds on my PC, if I write:

def is_palindrome(n):
    return str(n) == str(n)[::-1]

it takes only 16 seconds.


Action to transmit queued messages over a socket I have this action and it works but looks rather clunky to me. Is there any way I could improve that?

transMit :: Serialize a => Socket -> POSIXTime -> KEY -> a -> TPSQ -> TMap a -> IO ()
transMit s time key newmsgs q m = do
     loopAction <- atomically $ do
                       mT <- readTVar m
                       qT <- readTVar q
                       let (a, b) = key  -- extract IPv4 address a and protocolID b from KEY
                       let mT' = Map.delete key mT
                       let qT' = PSQ.delete key qT
                       writeTVar q (PSQ.insert key time qT')
                       writeTVar m (Map.insert key [newmsgs] mT')
                       case b of
                              11 -> return $ case Map.lookup key mT of
                                                  Nothing -> return ()
                                                  Just messages -> sendq s (B.snoc (S.encode messages) b ) (show a) 4711
                              72 -> return $ case Map.lookup key mT of
                                                  Nothing -> return ()
                                                  Just messages -> sendqr s (B.snoc (S.encode messages) b ) (show a) 4711

     loopAction

I'm not familiar with the libraries and types you're using here, but I see a few general Haskell things:

Instead of loopAction <- atomically $ ...; loopAction, you can use join $ atomically $ .... This removes the need for the entire outer do block, simplifying the blocks/indentation.
You're doing nearly-identical operations on m and q, just with different collection types. I would attempt to extract these to a higher-order function (e.g. one possible abstraction is modifyTVar, which doesn't exist in the library, but you can see how to write it analogously to modifyMVar), and perhaps define an ad-hoc typeclass to make Map and PSQ look the same.
Your case b of ... has two nearly identical branches! Unless there's some non-obvious polymorphism, then just combine them:

let send = case b of
    11 -> sendq
    72 -> sendqr
return $ case Map.lookup key mT of
    Nothing -> return ()
    Just messages -> send s (B.snoc (S.encode messages) b) (show a) 4711

let mT' = Map.delete key mT is redundant because the following insert will always overwrite that key anyway; just use Map.insert key [newmsgs] mT and never define mT'.
Assuming you're using Data.PSQueue, and the key already exists in the queue, you can use PSQ.adjust instead of a delete followed by an insert.

Taking all of my own advice except the last:

transMit :: Serialize a => Socket -> POSIXTime -> KEY -> a -> TPSQ -> TMap a -> IO ()
transMit s time key newmsgs q m =
    join $ atomically $ do
        modifyTVar_ q $ (PSQ.insert key time . PSQ.delete key)
        foo <- modifyTVar m $ \mT -> (Map.insert key [newmsgs] mT, Map.lookup key mT)
        let (address, protocol) = key
        let send = case protocol of
            11 -> sendq
            72 -> sendqr
        return $ case foo of
            Nothing -> return ()
            Just messages -> send s (B.snoc (S.encode messages) protocol) (show address) 4711

modifyTVar :: TVar a -> (a -> IO (a, b)) -> IO b
modifyTVar var f = do
    x <- readTVar var
    (x', r) <- f x
    writeTVar var x'
    return r
modifyTVar_ :: TVar a -> (a -> IO a) -> IO ()
modifyTVar_ var f = do
    x <- readTVar var
    writeTVar var (f x)

Further points about what I did:

Note I called a variable foo because I don't know what it makes sense to name it in your application, not because that's a good name.
I went and defined both modifyTVar and modifyTVar_; the latter is not needed but allows the action on q to be defined as a simple function composition. This is perhaps an excess of specialized utility functions, but I feel it is reasonable because the experienced Haskell programmer will understand what they do simply from seeing their names.
I renamed a and b so the variable names actually communicate what they are; this is better than writing a comment to explain them, and so I removed the comment.
I put join $ atomically $ do on a separate line so as to catch the reader's eye that this is not just a plain do block.


Printing permutations of a given string I want some feedback on the program I developed in C for printing the permutations of a given string.

#include <stdio.h>
bool isUnique(char x[], int y)
{
   int i, j;
   for (i = 0; i < (y-1); i++)
     for (j = i+1; j < y; j++)
       if (x[i] == x[j])
          return false;
   return true;
}
void perm(char a[], char b[], int x, int y)
{
   if ((y == x) && isUnique(b,x))
   {
     b[y] = '\0';
     printf("%s\n", b);
   }
   else
     for (int i = 0; i < x; i++)
     {
        b[y] = a[i];
        if (y < x)
          perm(a,b,x,y+1);
     }
}
int main()
{
   char a[] = {'1','2','3','4'}, b[] = {'\0','\0','\0','\0','\0'};
   perm(a,b,4,0);
   return 0;
}

Also, please tell me where I'm making blunders as far as conventions and good practice are concerned.

Do not use single-character names for variables.  This will make your code harder to understand.  Give them names based on their significance to the program.
Put your two arrays on separate lines for clarity:

char a[] = {'1','2','3','4'};
char b[] = {'\0','\0','\0','\0','\0'};

Arguments to a function that aren't modified within the function should be const.

This applies to a[] in main():

const char a[] = {'1','2','3','4'};

Parameters that aren't modified within a function could be const in order to prevent any accidental modifications.

This applies to all parameters in this program except for b[].
Since you declare your for loop counters inside the loop statement, and you're using bools, then it appears you're using C99.

Two things you should be doing here:

Consistently declare your loop counters inside the statements.  You're doing it the pre-C99 way in isUnique().
Your code does not compile with the bools.  To use them, you must include <stdbool.h>.

You're inconsistently declaring your loop counters inside and outside the for loop statements.  Since you initialize them inside in one instance, you must be using C99.  If so, then this should be consistent for each of these loops.
In perm(), you should have curly braces for the else, just as you have them for the if.  Make sure to maintain such consistencies throughout your program.

You should also do this for the for loops and ifs in isUnique().  It is especially important here as it helps with maintenance and will allow you to add additional lines if needed.
Functions in C that have no parameters should have a void parameter:

int main(void) {}

The return 0 at the end of main() is unneeded; the compiler will do this automatically.

With these changes, I've come up with the following code (also tested on Ideone):

#include <stdbool.h>
#include <stdio.h>

bool isUnique(const char x[], const int y)
{
    for (int i = 0; i < (y-1); i++)
    {
        for (int j = i+1; j < y; j++)
        {
            if (x[i] == x[j])
            {
                return false;
            }
        }
    }

    return true;
}

void perm(const char a[], char b[], const int x, const int y)
{
    if ((y == x) && isUnique(b, x))
    {
        b[y] = '\0';
        printf("%s\n", b);
    }
    else
    {
        for (int i = 0; i < x; i++)
        {
            b[y] = a[i];

            if (y < x)
            {
                perm(a, b, x, y+1);
            }
        }
    }
}

int main(void)
{
    const char a[] = { '1', '2', '3', '4' };
    char b[] = { '\0', '\0', '\0', '\0', '\0' };

    perm(a, b, 4, 0);
}


Matching element of arrays on a condition if node[i] and node[i+1] are present in the neighbor[i], then store the 'i' position of node and print the 'i' value of node.

this is also done by reversing the node array(only) and same type of check and print is done with the neighbor[i].

This code is written by me and works well, is there any other efficient method to perform this.

#include <stdio.h>
int main()
{
    int node[5] = {44,5,4,6,40};
    int neighbor[4]= {40,3,4,6};
    int i=0,j=0,k=0;
    int found_indices[5]; // array used to store indices of found entries..
    int count = 0; //n entries found;
    int fwd_count=0;
    int postn;
    int find;
    // to find in forward direction
     for (i=0; i<4; i++) {
        for (j=0; j<4; j++) {
            if (node[i]==neighbor[j]) {
                postn=node[i];
                for (k=0; k<4; k++) {
                    if (node[i+1]==neighbor[k]) {
                      found_indices[fwd_count ++] = postn; // storing the index of found entry

                    }
                }
            }
        }
    }

   if (fwd_count!=0) {
       for (i=0; i<fwd_count; i++)
           printf("forward relay for ==%d\n", found_indices[i]);

   } else{
     printf("Relay not found in forward\n");
  }

 // to find in backward direction
    for (i=4; i>0; i--) {
        for (j=0; j<4; j++) {
            if (node[i]==neighbor[j]) {
                postn=node[i];
                for (k=0; k<4; k++) {
                    if (node[i-1]==neighbor[k]) {
                      found_indices[count ++] = postn; // storing the index of found entry

                    }
                }
            }
        }
    }

   if (count!=0) {
       for (i=0; i<count; i++)
           printf("backward relayy for ==%d\n", found_indices[i]);

   }else{
      printf("Relay not found in backward \n");
   }

}

They key here is to to be able to abstract common functionality away. You're not expressing "node[i] is in the neighbor array" nicely. Simply write a function which does it for you:

int node_in_neighbors(int node, int neighbor[], int length) {
    int i;

    for(i = 0; i < length; i++) {
        if (neighbor[i] == node) {
            return 1;
        }
    }
    return 0;
}

In a more "high-level" language, you wouldn't have to write this function, and it would be in the library. You can now rewrite your forward/backward loops easily:

// to find in forward direction
for (i = 0; i < 4; i++) {
    // keep a node if his successor and him are in the neighbors array
    if (node_in_neighbors(node[i], neighbor, 4)
            && node_in_neighbors(node[i+1], neighbor, 4)) {
        found_indices[fwd_count ++] = node[i];
    }
}

// to find in backward direction
for (i = 4; i > 0; i--) {
    // keep a node if his predecessor and him are in the neighbors array
    if (node_in_neighbors(node[i], neighbor, 4)
            && node_in_neighbors(node[i-1], neighbor, 4)) {
        found_indices[count ++] = node[i];
    }
}

This makes the code clearer, since it's way easier to understand the logic now.

One issue is that you still have lots of 4 around. You should replace those in the loop with node_length - 1 and those in the node_in_neighbors call by neighbor_length, otherwise you could confuse them.

Define those lengths like this:

int node_length = sizeof(node) / sizeof(node[0])
int neighbor_length = sizeof(neighbor) / sizeof(neighbor[0])

This trick only works on static arrays, be careful.


Calculate quote volumes (for a financial instrument) within numeric constraints The function below is part of a trading system. Its purpose is to assign a volume (order size) to a bid (buy) quote and and ask (sell) quote, depending on the value of the position_size argument.

This trading system strictly cannot exceed a position limit of 100 in either direction, so our order volumes need to never exceed 100 when combined with the absolute value of current position.

However there is one caveat. Occasionally, for uncontrollable external reasons, a bid or ask (buy or sell order) will be executed twice before its price can be re-adjusted.

So any bid_volume or ask_volume returned by this function needs to be at most, half the value of 100 - position_size, in order to account for the occasional double execution.

Thats why at any step of the if-else blocks below, doubling the ask_volume or bid_volume plus current_position will not exceed 100.

What is the fastest way to achieve this with Python, other than the below code?

def adjust_volume(position_size):

    # Long.
    if position_size > 0:

        if position_size < 45:
            bid_volume = 45 - position_size
            ask_volume = 50

        elif position_size >= 45 and position_size < 65:
            bid_volume = 65 - position_size
            ask_volume = 50

        elif position_size >= 65 and position_size < 82:
            bid_volume = 82 - position_size
            ask_volume = 50

        elif position_size >= 82 and position_size < 100:
            bid_volume = 91 - position_size
            ask_volume = 85

    # Short.
    elif position_size < 0:

        abs_position_size = abs(position_size)

        if position_size > -45:
            bid_volume = 10
            ask_volume = 45 - abs_position_size

        elif position_size <= -45 and position_size > -65:
            bid_volume = 50
            ask_volume = 65 - abs_position_size

        elif position_size <= -65 and position_size > -82:
            bid_volume = 50
            ask_volume = 82 - abs_position_size

        elif position_size <= -82 and position_size > -100:
            bid_volume = 75
            ask_volume = 85 - abs_position_size

        elif position_size == 0:

            bid_volume = 30
            ask_volume = 30

    return position_size, bid_volume, ask_volume

position_size, bid_volume, ask_volume = adjust_volume(-76)

print("bid_volume:", bid_volume)
print("ask_volume:", ask_volume)

Bug

adjust_volume(0) presently results in:

  UnboundLocalError: local variable 'bid_volume' referenced before assignment

since if position_size == 0: is currently indented inside the elif position_size < 0: statement, so is unreachable.  (This could be a result of poor formatting when copying the code into the question post.)

Possible Bug

Some volume calculations result in negative volumes.  (adjust_volume(99) gives bid_volume == -8, and adjust_volume(-99) gives ask_volume == -14, which seem like invalid results.)

Possible Bug

If adjust_volume() is given an argument >= 100 or <= -100, it also fails with an UnboundLocalError.  Limits should be checked and a ValueError be raised instead.

  This trading system strictly cannot exceed a position limit of 100 in either direction, so our order volumes need to never exceed 100 when combined with the absolute value of current position.

100 does not exceed 100, so it is likely the original implementation should have allowed +100 and -100 as well.  But these currently result in UnboundLocalError.

Chained comparisons

I have to say, this condition makes my brain hurt:

    elif position_size <= -65 and position_size > -82:

It took me several moments to unwind what the range was, and I had to triple check that I got it right.  It would be much clearer to express as:

    elif -82 < position_size and position_size <= -65:

or using the chaining comparison operations:

    elif -82 < position_size <= -65:

Bisect

You have 9 ranges:

-100 < position_size <= -82
-82 < position_size <= -65
-65 < position_size <= -45
-45 < position_size < 0
0 <= position_size <= 0
0 < position_size < 45
45 <= position_size < 65
65 <= position_size < 82
82 <= position_size < 100

Instead of using a tree of if-elif-else statements to locate the correct range, you could bisect the list -81, -64, -44, 0, 1, 45, 65, 82 to determine the correct range bucket.

Note: Negative bucket limits have been increased by 1 to account for the difference in whether the lower limit or the upper limit is included as position_size goes from negative values to positive values.

from bisect import bisect

POSITION = (-81, -64, -44, 0, 1, 45, 65, 82,)
BID_ASK = (
    (75, 85), # -100 < pos <= -82
    (50, 82), # -82 < pos <= -65
    (50, 65), # -65 < pos <= -45
    (10, 45), # -45 < pos < 0
    (30, 30), # 0 <= pos <= 0
    (45, 50), # 0 < pos < 45
    (65, 50), # 45 <= pos < 65
    (82, 50), # 65 <= pos < 82
    (91, 85), # 82 <= pos < 100
)

def adjust_volume(position_size):

    if not(-100 < position_size < 100):
        raise ValueError("position size out of range")

    bucket = bisect(POSITION, position_size)

    bid_volume, ask_volume = BID_ASK[bucket]
    if position >= 0:
        bid_volume -= position_size
    else:
        ask_volume -= abs(position_size)

    return position_size, bid_volume, ask_volume


C++ Socket Part-2 A (Utilities) This is the code I use to dynamically build error messages.
Utility.h
#ifndef THORSANVIL_SOCKET_UTILITY_H
#define THORSANVIL_SOCKET_UTILITY_H

#include <string>
#include <vector>
#include <sstream>

namespace ThorsAnvil
{
    namespace Socket
    {

template<std::size_t I = 0, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type
print(std::ostream&, std::tuple<Tp...> const&)
{ }

template<std::size_t I = 0, typename... Tp>
inline typename std::enable_if<I < sizeof...(Tp), void>::type
print(std::ostream& s, std::tuple<Tp...> const& t)
{
    s << std::get<I>(t);
    print<I + 1, Tp...>(s, t);
}

template<typename... Args>
std::string buildStringFromParts(Args const&... args)
{
    std::stringstream msg;
    print(msg, std::make_tuple(args...));
    return msg.str();
}

template<typename... Args>
std::string buildErrorMessage(Args const&... args)
{
    return buildStringFromParts(args...);
}

    }
}

#endif

The code works for all types that can be streamed. Including io manipulators.
std::time_t t = std::time(nullptr);
std::tm tm = *std::localtime(&t);

buildStringFromParts("Date: ", std::put_time(&tm, "%c %Z"), "\r\n");

This generates the string:
Date: Sun Jun  5 01:55:19 2016 PDT

I've only got a minor amount of suggestions to offer. Your code already does what it needs to do the proper way.
Missing headers
Consider including the specific header of the types you use instead of depending on other headers including them.

Requires <cstddef> for std::size_t.
Requires <type_traits> for std::enable_if<>
Requires <tuple> for std::tuple<> and std::get<>. This one  is actually needed, otherwise you get an undefined reference to std::get<>.

Printing
Consider...

Changing your condition to I == sizeof...( Tp ) - 1 instead of I == sizeof...( Tp ). Will the compiler optimize away the last extra empty function call? Probably, but there's no reason to have it to begin with.
Using the _t post-fix type traits for conciseness: std::enable_if_t<> over typename std::enable_if<>::type.
The default type alias of std::enable_if<> is already void, there's no need to explicitly write it.

By applying those suggestions, we go from this:
template<std::size_t I = 0, typename... Tp>
inline typename std::enable_if<I == sizeof...(Tp), void>::type
print(std::ostream&, std::tuple<Tp...> const&)
{ }

template<std::size_t I = 0, typename... Tp>
inline typename std::enable_if<I < sizeof...(Tp), void>::type
print(std::ostream& s, std::tuple<Tp...> const& t)
{
    s << std::get<I>(t);
    print<I + 1, Tp...>(s, t);
}

To this:
template<std::size_t I = 0, typename... Tp>
inline std::enable_if_t<I == sizeof...( Tp ) - 1>
print( std::ostream& s, std::tuple<Tp...> const& t )
{
    s << std::get<I>( t );
}

template<std::size_t I = 0, typename... Tp>
inline std::enable_if_t<I < sizeof...( Tp ) - 1>
print( std::ostream& s, std::tuple<Tp...> const& t )
{
    s << std::get<I>( t );
    print<I + 1, Tp...>( s, t );
}

Using the array pack-expansion trick to avoid recursion, the use of std::tuple<> and indexing.

By using that trick, the print() function can be simplified into:
template <class OutputStream, class... Args>
void print( OutputStream& os, Args&&... args )
{
    using expander = int[];
    expander{ ( (void) ( os << std::forward<Args>( args ) ), 0 )... };
}

You can apply the same trick to the buildStringFromParts() function. This will allow you to separate printing from building the string.
To compensate for some standard warning flags that most people have turned on by default (-Werror -Wunused-value) we need to force a use of the temporary. So extract the first element as a return value:
template<typename... Args>
int print(std::ostream& s, Args&... args)
{
    using Expander = int[];
    return Expander{ 0, ((s << std::forward<Args>(args)), 0)...}[0];
}


Seeding MongoDB using Mongoose models I'm using mongoose to seed a mongodb database based on my mongoose models.
I'm particular interested in improving the seed code.

I have two models, an article and a category.
The relationship between the models are as follows:

A category has many articles
An article has a parent category

The model schemas I'm using are listed below:

The category schema

var mongoose = require('mongoose');

var categorySchema = mongoose.Schema({
    title: String,
    articles : [{ type: mongoose.Schema.Types.ObjectId, ref: 'Article' }]
});

mongoose.model('Category', categorySchema);

The article schema

var mongoose = require('mongoose');

var articleSchema = mongoose.Schema({
    category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category' },
    title: String
});

mongoose.model('Article', articleSchema);

I'm using the following code to seed:

Seeding the category

var CategoryModel = require('mongoose').model('Category');

exports.seedCategories = function seedCategories() {
    CategoryModel.find({}).exec(function (err, collection) {
        if (collection.length === 0) {
            CategoryModel.create({ title: 'Category One' });
            CategoryModel.create({ title: 'Category Two' });
        }
    });
}

Seeding the article

var CategoryModel = require('mongoose').model('Category');
var ArticleModel = require('mongoose').model('Article');

exports.seedArticles = function seedArticles() {

    ArticleModel.find({}).exec(function (err, collection) {
        if (collection.length === 0) {
            seedArticle('Category One', 'Article One');
            seedArticle('Category One', 'Article Two');
            seedArticle('Category Two', 'Article Three');
            seedArticle('Category Two', 'Article Four');
        }
    });

    function seedArticle(categoryTitle, articleTitle) {
        var parentCategory;
        CategoryModel.findOne({ title: categoryTitle }).exec()
            .then(function (category) {
                parentCategory = category;
                return ArticleModel.create({ title: articleTitle, _category: parentCategory._id });
            }).then(function (article) {
                parentCategory.articles.push(article._id);
                parentCategory.save(function (saveError) {
                    if (!saveError) {
                        console.log("Seeded article");
                    } else {
                        console.log(saveError);
                    }
                });
            });
    }
}

I'm particularly interested in methods for preventing the Christmas tree of doom, and removing the obstruent error handling. Any recommendations are welcome, and thanks in advance for the help. I hope this code helps others.

Mongoose have just implemented promises returned from saves, so that should help. It will be available in mongoose 3.10.

It seems that you are storing the data with double links (article -> category AND category -> articles).

I assume that you need to report on articles for a category.  I would simple create an index on Category like this:

var articleSchema = mongoose.Schema({
    category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category', index: true },
    title: String
});

This way you can simplify your code a ton by keeping it KISS:

function seedArticle(categoryTitle, articleTitle) {
  CategoryModel.findOne({ title: categoryTitle }).exec()
    .then(function (category) {
      return ArticleModel.create({ title: articleTitle, category: category._id });
    });
}

Other than that, I like your code.


Can I improve this progressive enhancement? I'm attempting to make a nice-looking UI where a user views current items in a list and can add/edit/delete.

For each item, i've included an edit and delete link, but I'm trying to do so in such a way as to gracefully degrade/progressively enhance:

My Course Name

    ✎ Edit
    ✕ Remove

The idea is that for accessibility users/css-haters/lynx-users/really-really old browsers, the link displays as "✎ Edit" - clear and obvious as to the meaning:

Then, with CSS, I tweak it so only the ✎ and ✕ is visible, in a sort of iconic format:

My Question: is this a good approach to graceful degradation and progressive enhancement, and/or could it be improved?

P.S: I have a tiny feeling this might not be 100% appropriate for Code Review - so apologies if its not; we can always migrate/close, right?

Also, CSS:

.tools {
        float:right;
        clear:both;
        height:1em;
        overflow:hidden;
        margin:0;
        width:auto;
        border:none;
    }
    .tool {
        float:left;
        width:1em;
        height:1em;
        overflow:hidden;
        color:black;
        text-decoration:none;
    }

I believe this is more trouble than it is worth. You may be shooting yourself in the foot since your complicated solution might not work as you expect for the different configurations you want to support. Designing for accessibility is not only "turn off CSS and JS and see how it works out", but "test that my code works for all these settings". I believe you're doing it wrong here.

A simple proposal

Did you consider the simplest approach?

My Course Name
  ✎ ✕

CSS:

.tools { float: right }

This is going to work for CSS haters (?), old browsers and lynx. As for "accessibility users", most of them use real browsers, but need bigger fonts or high contrast designs. This means that my solution will not work only for speech synthesis (the speech synthesis of Google Translate skips complicated Unicode characters) but will work on any normal browser (even if the old-old browsers doesn't understand "float", the Unicode symbols will be displayed next to the course title).
The title attribute (thanks to ANeves) will help confused users hovering on the icons! I do this all the time for StackOverflow icons. This is great accessibility for normal users, but probably won't help for speech synthesis and the like.
Extra bonus: the CSS is simple to understand

I don't know how well your width:1em trick is going to work on browsers. It might be perfect, but it might not work as you expect at all.

If you really care about speech synthesis and make sure that your website really supports it (eg. do you follow the Web Content Accessibility Guidelines?), then go on with your solution as long as it doesn't hurt other users.

(Also note that you're using a multiplication mark, why not using something like "BALLOT X" which I feel has better semantics and might be rendered in a way that might make it look better http://en.wikipedia.org/wiki/X_mark ?)

Update: added a title attribute, as ANeves proposed in comments.


Abstract factory pattern for implementing AdNetworks on multiple platforms Here's the link to the github project.

I want to implement abstract factory instead of adding platform-dependent compilation flags in just one file and make it ugly, hence decoupled code. Moreover, I have to implement different AdNetworks on different platforms.

This is the interface:

public interface IAds
{
    void ShowVideoAd();
    void PreLoadVideoAd();
    bool IsAdAvailable();

}

And all the PlatformAdController (Android, IOS, Amazon, Windows) will implement this interface:

    public class AmazonAdsController : IAds
    {
// Code Goes here
    }

Then in someFactoryClass I'll do:

public IAds GetObject()
{
    #if UNITY_Android
    if(platform == Amazon)
    return new AmazonAdsController
    else
    return new AndroidAdsController
    #elif UNITY_IOS
    return new IOSAdsController
    #elif UNITY_WP10
    return new WindowsAdsController
}

This method will be called from AdManager a singleton MonoBehaviour. My current AdManager state is:

namespace MS.Ads
{
    [RequireComponent(typeof(KeyGenerator))]
    public class AdManager : MonoBehaviour
    {
        #region Fields & Properties
        [SerializeField]
        private KeysSource _keysSource;
        [SerializeField]
        [HideInInspector]
        private string _fileName;
        [SerializeField]
        [HideInInspector]
        private string _url;

        // Source from where to get keys
        public KeysSource Source
        {
            get { return _keysSource; }
            set { _keysSource = value; }
        }

        // Web URL from where to get AdKeys
        public string URL
        {
            get { return _url; }
            set { _url = value; }
        }

        // FileName from where to get Adkeys e.g adc.json
        public string FileName
        {
            get { return _fileName; }
            set { _fileName = value; }
        }

        // To be replaced by a FactoryObject.
        private FyberController _fyberController;
        #endregion

        #region Message Methods
        void Start()
        {
            GetComponent<KeyGenerator>().GenerateKeys(Source, URL, FileName);
            _fyberController = new FyberController();
            _fyberController.RequestVideoAd();
        }
        #endregion

        #region Methods
        public void ShowAd()
        {
            if (_fyberController.IsVideoAdAvailable)
                _fyberController.ShowVideoAd();
        }

        public bool IsVideoAdAvailable()
        {
            return _fyberController.IsVideoAdAvailable ? true : false;
        }
        #endregion
    }
}

What I would like to know:

Is factory pattern the right choice here?
If yes, should I go with an interface or an abstract base class or a base class with virtual methods?

It looks a lot like some service with platform dependent implementation. You might use a dependency injection pattern or service locator pattern.

I think factory is not quite great as a solution cause you will not create different implementations in a single application run. Also that is not great if you need this Controller to be created only once.

While it depends directly on your implementations and functionality of this service I will go with some interface. Further if implementations share same code then you might use an abstract base class to put that part of logic in it.


Check words in documents Suppose you have two lists:

One is a "dictionary", a list of words
The other is "documents", a list of documents (which in turn, are strings)

I would check whether a dictionary's word is within a document.

# DOCUMENTS
doc1 = "My sister likes to have sugar, but not my father."
doc2 = "Doctors suggest that driving may cause increased stress."

documents = [doc1, doc2]

# DICTIONARY
dictionary = ["doctors", "sister", "like"]

# CHECK DOCUMENT WORDS WITHIN DICTIONARY
for word in dictionary:
    for doc in documents:
        if word in doc:
            print "\n\n\nWord:",
            print word,
            print "in document:",
            print doc

What's a more "pythonic" way?

If your documents were actually lists of words, like your description said at one point, this would be way more efficient. But we can of course just make them, by using:

doc1 = "My sister likes to have sugar, but not my father.".split()
doc2 = "Doctors suggest that driving may cause increased stress.".split()

This has the problem that the punctuation gets in the way, so we need to remove it first, with one of the approaches from here (I chose the fastest one):

import string
doc1 = "My sister likes to have sugar, but not my father.".translate(None, string.punctuation).split()
doc2 = "Doctors suggest that driving may cause increased stress.".translate(None, string.punctuation).split()

Ok, now that they are lists, we make them into sets, so word in doc becomes \$\mathcal{O}(1)\$ instead of \$\mathcal{O}(n)\$:

documents = map(set, [doc1, doc2])

# DICTIONARY
dictionary = ["doctors", "sister", "like"]

for word in dictionary:
    for doc in documents:
        if word in doc:
            print "\n\n\nWord:",
            print word,
            print "in document:",
            print doc

This should speed this up considerable. The most speed-up will be gained if the document strings are quite long.

The output of this is now not really understandable anymore:

Word: sister in document: set(['sister', 'my', 'father', 'but', 'sugar', 'to', 'likes', 'have', 'not', 'My'])

We can get around that by carrying around both the set and the string. I also made the splitting into words a function and used a if __name__ == "__main__" guard to ensure this code is only run when calling it via e.g. python script.py, but not when doing from script import get_words.

import string

def get_words(text):
    return set(text.translate(None, string.punctuation).split())

if __name__ == "__main__":
    documents = ["My sister likes to have sugar, but not my father.",
                 "Doctors suggest that driving may cause increased stress."]

    words_in_documents = map(get_words, documents)

    for word in ["doctors", "sister", "like"]:
        for doc, words in zip(documents, words_in_documents):
            if word in words:
                print "\n\n\nWord: {} in document: {}".format(word, doc)


Validate that a given email address has a whitelisted domain and the address has not already been registered This is a remote validation method for a registration form, fired when the user enters an email address. It checks that the domain portion exists in a given list of valid domains, and then also checks the email address has not already been registered.

    [AllowAnonymous]
    [AcceptVerbs("Get", "Post")]
    public async Task<JsonResult> CheckEmail(string Email)
    {
        bool validDomain = false;
        string s = Email; //e.g. myname@my.org
        int idx = s.LastIndexOf('@');
        Console.WriteLine(s.Substring(0, idx)); //local half (not needed) e.g myname
        string domain = s.Substring(idx + 1).ToLower();    //domain half e.g. my.org

        IEnumerable<Organisation> organisations = _context.Organisations.ToList();

        foreach (var organisation in organisations)
        {
            if (domain == organisation.EmailDomain)
            {
                validDomain = true;
                break;
            }
        }

        if (validDomain == false)
        {
            return Json(
                data: "" + domain + " accounts cannot be used");
        }

        var result = await _userManager.FindByEmailAsync(Email);
        if (result == null)
        {
            return Json(data: true);
        }
        return Json(data: $"Email address already registered</a>");

    }

I also tried to use this line instead of the foreach loop but wouldn't get it to work:

//string result = organisations.FirstOrDefault(o => o.Contains(domain));

I got "symbol Contains cannot be resolved."

Would appreciate feedback on improving the rest of the code if possible.

There are a few things that jump out at me in your code:

public async Task<JsonResult> CheckEmail(string Email)

Email should be email because it is conventional for parameters to be camelCase in C#.

Why are you making a copy of the email address?

string s = Email;

Strings are immutable, you can just use your parameter directly.

This line:

Console.WriteLine(s.Substring(0, idx)); //local half (not needed) e.g myname

First, you should never be using Console.WriteLine in a action method of a controller. Generally, you shouldn't be using it in a web app at all. If you want to debug it, add a log or just step through with an actual debugger using breakpoints.

Second, if you don't need the local half, why do you compute it at all?

Third, you haven't validated that the email address even contains an @. If it doesn't, this line will throw an exception.

Validate your index:

var atCharPosition = email.LastIndexOf('@');
if (atCharPosition == -1)
{
   return Json(data: "Invalid email address");
}

This line is the most worrying:

IEnumerable<Organisation> organisations =  _context.Organisations.ToList();

Is that _context an Entity Framework Data Context? If it is, you're getting all of the organisations back from the database to see whether the domain exists. Let the database do it:

// requires a using System.Linq;
var isValidDomain =  _context.Organisations.Any(o => o.EmailDomain == domain);

Finally, why are you returning a closing anchor tag in this line?

return Json(data: $"Email address already registered</a>");

I can't see any reason why you'd want to return malformed html here.


Monte Carlo AI in 21 game I am very interested in the Monte Carlo AI.

I tried my best, still, this AI plays very badly.

This code "works" in the meaning that it does not crash, but the quality of play is extremely low.

Have I completly misunderstood the Monte Carlo AI or is there just a nasty bug in my code preventing it from playing correctly?

Can you understand every detail of code?

Creating an AI is quite complex a task so I would like to have the better style possible in order to keep the code understandable by everyone.

"""
TITLE: Monte Carlo AI that plays the 21 game
AUTHOR: Caridorc Tergilti
LICENSE: Creative Commons 3.0
CURRENT_STATE: The AI is currently very weak, I have no clue why.

General explanation:
This game is very,very easy, an AI can be disigned in
much simpler ways than this.

I designed a Monte Carlo AI because I want to learn about Monte Carlo AI-s
(You can find out more about Monte Carlo here:
https://en.wikipedia.org/wiki/Monte_Carlo_method)
and I want to discover if such an AI can actually be powerful in a game.

(Yes, there are many articles and papers on the internet that say that
Monte Carlo AI works but I want to prove it myself).

This programme is also Creative Commons so I hope that many people will enjoy
reading this programme to understand Monte Carlo AI better.

I will now explain my understanding of Monte Carlo AI.

1) The computer, knowing the rules, must decide what move is better.
2) FOREACH move the computer is going to simulate the move.
3) It will than play a big number of random games starting from the position after he made
the move.
4) Each move will be awarded a score equals to: wins / total_games.
5) The move with the highest score will be played.
"""

import random

WELCOME = """
21 game.
The total starts at 0.
Each player can chose 1, 2, or 3,
the number is than added to the total.
If when a player adds his number,
he makes the total equals or more than 21, he loses.
"""
DEPTH = 1000

def play_random_game(state):
    """
    This function plays a random game starting
    from a state.
    The opponent moves first.
    Returns 1 if you win,
    0 if you lose
    """
    if state >= 21:
        return 0 # You previously played a move that made you lose
    while 1:
        state += random.randint(0,3) # Opponent
        if state >= 21:
            return 1   # YOU WIN
        state += random.randint(0,3)
        if state >= 21:
            return 0   # YOU LOSE

def play_n_games(state,number):
    """
    Plays a certain number of random games,
    all starting from the state.
    Return the wins/total ratio.
    """
    outcomes = []
    for _ in range(number):
        outcomes.append(play_random_game(state))
    return sum(outcomes) / len(outcomes)

def AI(total):
    """
    This artificial intelligence uses Monte Carlo
    to make the best move.
    """
    list_of_outcomes = []
    possible_moves = [1,2,3]
    for move in possible_moves:
        list_of_outcomes.append(play_n_games(total,DEPTH))

    # Chose the move with the better score
    if max(list_of_outcomes) == list_of_outcomes[0]:
        return 1
    elif max(list_of_outcomes) == list_of_outcomes[1]:
        return 2
    elif max(list_of_outcomes) == list_of_outcomes[2]:
        return 3

def interface():
    """
    Allows the user to play the game
    against the AI.
    """
    total = 0
    print(WELCOME)
    while 1:
        user_number = int(input("Enter your number: "))
        assert (user_number in [1,2,3]),"Each player can chose 1, 2, or 3"
        total += user_number
        print("The total is " + str(total))
        print()
        if total >= 21:
            print("You lost")
            break
        total += AI(total)
        print("After the AI added a number")
        print("The total is " + str(total))
        print()
        if total >= 21:
            print("You won")
            break

if __name__ == "__main__":
    interface()

Your simulation assumes the human is playing randomly. This is not realistic. Consider the case when it's the human's turn at 19. A sensible player will certainly play 1 to force a win, but a random player has only 1/3 probability of doing the same. The simulation teaches the AI that the computer has an advantage in that situation, which is wrong.

If the rules of the game were changed so that every move must be made at random, your algorithm should be able to predict each player's probability of winning at any point. However, that would be a different game: a game of chance.

There's also a simple bug: you generate random moves by randint(0,3). This should of course be randint(1,3) because 0 is not a valid move.


Determine number of even, odd, and zero digits of a given integer I have been programming in C++ for around a month now, just long enough, I figure, to develop bad habits. Can anyone point out where I'm making mistakes and offer topics I should investigate to understand why?

#include <iostream>
#include <cassert>
#include <sstream>
#include <string>

using namespace std;
string get_line();
int long get_integer();
int* flex(long int num);
void test_flex();

int main()
{
    //flex(get_integer());
    test_flex();
}

/*
 * ===  FUNCTION  =============================================================
 *         Name:  flex
 *  Description:  flex takes one integer argument and returns an then number
 *  of odd, even and zero digits.
 *  flex(111022) -> [3,2,1] i.e [odd,even,zero's]
 * ============================================================================
 */
    int*
flex (long int num)
{
    int res;
    int even = 0;
    int odd = 0;
    int zero = 0;

    while(num != 0){
        res = num % 10;
        if(res == 0){
            zero++;
        }
        else if(res % 2 == 0){
            even++;
        }
        else{
            odd++;
        }
        num = (num - (num % 10))/10;
    }
    int oez[3] = {odd,even,zero};
    return oez;
}       /* -----  end of function flex  ----- */

/*
 * ===  FUNCTION  =============================================================
 *         Name:  test_flex
 *  Description:  test suite for flex function
 * ============================================================================
 */
    void
test_flex ( )
{
    assert(flex(1)[0] == 1);
    assert(flex(1)[1] == 0);
    assert(flex(1)[2] == 0);

    assert(flex(112220)[0] == 2);
    assert(flex(112220)[1] == 3);
    assert(flex(112220)[2] == 1);

}       /* -----  end of function test_flex  ----- */

/*
 * ===  FUNCTION  ======================================================================
 *         Name:  get_integer
 *  Description:  checks if input is integer
 * =====================================================================================
 */
    long int
get_integer ()
{
    while(true){
        stringstream converter;
        converter << get_line();

        int long result;
        if(converter >> result){
            char remaining;
            if(converter >> remaining)
                cout << "Unexpected character: " << remaining << endl;
            else{
                return result;
            }
        } else
            cout << "Please enter an integer." << endl;

        cout << "Retry:" << endl;
    }
}       /* -----  end of function get_integer  ----- */

/*
 * ===  FUNCTION  ======================================================================
 *         Name:  get_line
 *  Description:  wraps getline
 * =====================================================================================
 */
    string
get_line()
{
    string result;
    getline(cin,result);
    return result;
}       /* -----  end of function get_line  ----- */

Do not see the point in: get_line()

get_line(line);

// Vs

std::getline(std::cin, line);

Get Integer is well done. Most people forget to test if there is anything else remaining on the line.

A simple enhancement is:

        char remaining;
        if(converter >> remaining)

        // easier to rewrite as:
        if (!converter.str().empty())

Also there is already a boost function that does something similar:

long value = boost::lexical_cast<long>(line); // Will throw if anything left on line.

Over complicating this:

    num = (num - (num % 10))/10;

You can simplify it too:

    num /= 10;  // Integer division truncates.

I think this is a logical error:

    if(res == 0){
        zero++;
    }
    else if(res % 2 == 0){ // zero is an even number
                           // do you really want that else?

Your one major error is:

int oez[3] = {odd,even,zero};
return oez;

You are returning a pointer to an array that has gone out of scope. Personally I would return a std::vector<int>. Don't worry on a simple returning like this the copy back of the array will be optimized out (look up RVO and NVRO).

std::vector<int> oez = {odd,even,zero};
return oez;