## python – Vigenère Cipher problem in competitive programming

I’ve just started doing programming problems.

https://icpcarchive.ecs.baylor.edu/external/58/p5880.pdf

The code below works fine, but my run time is 2.715 seconds and the time limit is 3 seconds.

How can I improve speed of this code?

I’ve already started to use `sys.stdin` instead of `input()`.

``````import string
import sys

while True:
key = int(key) if key.isdigit() else key
if key == 0: break

decrypted_msg = int(decrypted_msg) if decrypted_msg.isdigit() else decrypted_msg
if decrypted_msg == 0: break

key = (len(decrypted_msg)//len(key) + 1) * key
key = key(0:len(decrypted_msg))

encrypted_msg = ""

for i in range(len(decrypted_msg)):
key_idx = string.ascii_uppercase.index(key(i))
deciphered_idx = string.ascii_uppercase.index(decrypted_msg(i))

enciphered_idx = (deciphered_idx + key_idx + 1) % len(string.ascii_uppercase)
encrypted_msg += string.ascii_uppercase(enciphered_idx)

print(encrypted_msg)
``````

## continuous integration – How to address a common problem with automated testing on remote machine

CI/CD options such as bitbucket pipelines and github actions make use of virtual machines called runners. Changes in source code trigger the runners, which in turn trigger a set of commands. The commands may include instructions to run a test suite. The test suite checks whether source code changes break existing functionality.

Contributors often develop tests on their local machines. Tests that succeed on one platform do not necessarily succeed on another platform. This means that tests running on a remote machine can (and often do) behave unpredictably as compared with how they behave under local machine conditions. For example, a test that relies on Windows-style line returns may fail if it runs under a Linux operating system.

There are a few ways to circumvent this problem:

• Make test assertions platform-independent. In the above example, this might mean replacing every newline character with an empty string.
• Replicate the runner conditions on the local machine using containerization.
• Accept failing tests in the local machine

Only the second option seems viable, however I have seen very little to no support for this in the documentation of most CI/CD tools. This leads me to believe that I might be missing something. For the professional software developers/testers out there, has anyone run into this problem? What is the correct way to address it?

## Could the halting problem in theory be solved for any finite set of Turing Machines?

Your logic is somewhat correct. I will start by discussing the new definition you tried to give for the halting problem, and then move on to explain the finite set of TMs.

## Halting problem, with size less than the TM that solves it

This idea is certainly interesting, but it has some inherent problems with it.

First is a syntax problem. What language is here? Since $$N$$ is not bounded, this cannot be expressed as a usual computational problem with TMs. In order to formalize this you might want to create a new definition.

The second problem, is a bit more subtle: How do you define the “size” of a TM?
For example, if you decide to define it as the running time of the algorithm, then obviously is such a $$B$$ for every $$N$$ (just do a loop that does nothing for $$N-1$$ steps and after that accept). But if you define it as the length of the code plus the length of the inputs, then you can show that there is no such $$B$$ for big enough $$N$$. (the formal halting problem gets two inputs $$A,X$$ where $$A$$ is a program code and $$X$$ is some string, and you create a new TM that simulates it with only one input instead of two, reducing the size)

Those examples are obviously two opposite sides of a wide spectrum. You want to formally define the problem and the definition of the size of a TM before you can think of whether or not its possible.

## Finite set of TM

The formalization of the halting problem $$H$$ is as follows: $$H={langle M, x rangle : M text{ is a TM }land M(x)text{ halts}}$$

With this definition, even if you restrict it so $$M$$ would be in a predefined finite set of TMs, and even if this set contains only one TM, this is an undecidable problem! The counterexample, is $$U$$ – the universal TM. We will use a slightly different version of it, since we dont need its full power. $$U$$ (in this context) gets one input, which is a string representing a TM, and $$U$$ simulates this TM with the input $$epsilon$$. Then solving whether $$U$$ halts on some input or not, is undecidable, since its equivalent to the problem called $$H_epsilon$$ which is known to be undecidable.

However, if you would restrict the $$H_epsilon$$ problem itself for only a finite set of TMs, the problem becomes decidable, and even more! It becomes a regular language. This is because for each $$TM$$ in this finite set we know beforehand whether or not it halts, and we dont have to actually do any computation apart from assigning each of those $$TM$$ the correct label we already know.

## permutation – How to solve this problem by the way of saving memory?

Eight different boys and five different girls are in a row. Girls are required to be next to each other. How many ways are there (the answer is $$9!times5!$$)?

``````Cases(Permutations(Array(boy, 8)~Join~Array(girl, 5)), {___, girl(_),
girl(_), ___}) // Length
``````
``````General::nomem: The current computation was aborted because there was insufficient memory available to complete the computation.
``````

However, the above code indicates that there is not enough memory. What is the memory saving way to solve this problem? Feel free to correct the grammar mistakes and unidiomatic expressions in my posts, please.

## The Eigenvalue Problem: Perturbation Theory

Let $$mathbf{K}$$ be a square matrix and $$rho(mathbf{K})$$
is the spectral radius of $$mathbf{K}$$. Then, If $$mathbf{M}= mathbf{K}+delta mathbf{A}$$ for very small $$delta$$, I want to prove that

1. $$label{asrr1} rho(mathbf{M})=rho(mathbf{K})+delta langle mathbf{u}, mathbf{A}mathbf{v} rangle + O(delta^{2})$$
where $$mathbf{u}$$ and $$mathbf{v}$$ are respectively the left and right eigenvector of $$mathbf{K}$$.

2. Additionally, by using 1, can we prove that
$$rho(mathbf{M})=rho(mathbf{K})+delta rho^{prime} (mathbf{K})+ O(delta^{2}) ;?$$
That means, can we show $$delta rho^{prime} (mathbf{K})=delta langle mathbf{u}, mathbf{A} mathbf{v} rangle$$?

where $$prime$$ is a notation for derivative.

I am very grateful if someone shows me the sketch of the proof. Also, I am very happy if you forward me a reference related to this, and I can read and understand more.

Thank you very much for your cooperation!

## backtracking – Farmer, Wolf, Goat and Cabbage Problem: full decision tree in C

I put a backtracking algorithm around the Farmer, Wolf, Goat and Cabbage problem – to see if there are any interesting branches, besides the (two) 7-step solutions.

On first view it seems a dilemma. Then you realize it can be solved (by taking the goat back at step 4). Then you realize: it can almost not be not solved: every choice is compulsory, except silly direct repetitions.

You have to look closely to find a way to prolong the procedure, by constantly rotating the 3 passengers. Instead of going back empty at the end to fetch the lone goat, you can take back the wolf or salad, whichever you did not carry last. (if you do choose the other, it is not the start of a cycle, but a (silly) direct repetition)

Here is the output. Farmer(=empty ferry), Salad, Goat and Wolf are 0, 1, 2 and 3 resp.

``````ALL CROSSED - Level= 7  2012302
ALL CROSSED - Level=13  2012312312302
ALL CROSSED - Level=19  2012312312312312302
ALL CROSSED - Level=25  2012312312312312312312302
ALL CROSSED - Level=31  2012312312312312312312312312302
MAXLEVEL reached - backtracking to escape cycle: ...12312312
ALL CROSSED - Level= 7  2032102
ALL CROSSED - Level=13  2032132132102
ALL CROSSED - Level=19  2032132132132132102
ALL CROSSED - Level=25  2032132132132132132132102
ALL CROSSED - Level=31  2032132132132132132132132132102
MAXLEVEL reached - backtracking to escape cycle: ...32132132
``````

It goes on of course finding “solutions” if not stopped by a maxlevel. It is a kind of benign, non-branching cycle. WITH silly reps included, you get an enormous number of boring branches.

This is the filtered output lines (both kinds).

The full output displays the “state of the riversides”. Here the lines 20-70 with the first solution.

``````...

( 5 LEVEL)  cur:(-1) parent: 2
0: *.**
1: .*..
--> new node:(3) and state:
0: ..*.
1: **.*

( 6 LEVEL)  cur:(-1) parent: 3
0: ..*.
1: **.*
--> new node:(0) and state:
0: *.*.
1: .*.*

( 7 LEVEL)  cur:(-1) parent: 0
0: *.*.
1: .*.*
--> new node:(2) and state:
0: ....
1: ****

ALL CROSSED - Level= 7  2012302
( 6 LEVEL)  cur:(0) parent: 3
0: ..*.
1: **.*
--> new node:(1) and state:
0: ***.
1: ...*

...
``````

This quite sums up what the program does.

To my surprise I ended up with a 3D-array via `typedef`. With `int **sh` I had to use it like `(*sh)(fside)`. Plus other pointer-is-not-array related warnings and errors. Now it is:

`````` next_node(Shores_t sh, ...
...
ferry(sh, anim, fside);
if (is_unsafe(sh(fside)))
``````

Questions:

I guess if you want arrays, this is one of many right ways to do it. Might even work with variable/runtime stack size.

Would a `struct shores` be more flexible for passing, for putting in an array and for accessing?

What to put inside that struct? I don’t think `sh.goat` works if enum item `Goat` is integer `2`. Maybe the way to go if you use pure logic.

Or do I just wrap a `struct`around the existing typedef ?

`struct shores { Shores_t sht };`

and then `sh->sht(Dest)(Farmer)` ?

This is even worse than `(*sh)(Dest)(Farmer)`.

Do I have to make an array of pointers? Like usual with dynamic 2D arrays?

Eight or even just four bits would be enough to hold a complete state. But I don’t want it small and fast.

Any general ideas for this specific case ?

``````/*  Farmer, Wolf, Goat and Cabbage
River Crossing Problem/Puzzle/Dilemma

Here the cabbage is a salad - "fsgw" instead of FWGC (or FCGW).

The 'none' option (or 'Alone') was renamed 'Farmer' to use it better
(see all_on_side() and ferry()).  These four items (symbols) are numerically represented
as 'Animals' (as living beings) via enum.

The first Shores_t (both Sides_t of the river) looks like:
{ {1,1,1,1}, {0,0,0,0} }
This is a bit redundant, but robust/clear (see is_unsafe()).
Alternative: only 4 bools e.g. "1010" as "FcGw"; the other side then is virtual/the inverse.

By avoiding simple node/move repeats (ferry *directly* back what you just ferried),
there is only a 3-cycle pattern (rotating the items after 6 cycles) amd it can easily be broken.
An alternative would be to check for *state* repetitions in the *whole* stack.  */

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

/* For different backtrack patterns (and for testing) the sequence can be changed */
enum {Farmer, Salad, Goat, Wolf, Animals};
//enum {Salad, Wolf, Goat, Farmer, Animals};
enum {Start, Dest, Sides};

typedef int     Side_t   (Animals);                   /* For real 2D array without 'int...(2)(4)' everywhere */
typedef Side_t  Shores_t (Sides);

int
is_unsafe(Side_t b) {                                       /* b: where the farmer is NOT */
return b(Goat) && ( b(Salad) || b(Wolf) );
}
int
all_on_side(Side_t d) {                                     /* d: 'Dest' side to test for success */
return d(Farmer) && d(Salad) && d(Goat) && d(Wolf);
}

/* Visualize a "shore(2)(4)" (Two sides with four slots).
A bit of Conway life, just as jumpy on small scale */
/* The enum determines which of f,s,g and w is 0,1,2 or 3  */
void
show_state(Shores_t sh) {
for (int s = 0; s < Sides; s++) {
printf("%d: ",  s);
for (int i = 0; i < Animals; i++)
printf(sh(s)(i) ? "*" : ".");
putchar('n');
}
}
/* Show chain of nodes up to level 'end', for solutions. One-based. */
void
show_nodes(int *n, int end) {
for (int i = 1; i <= end; i++)
printf("%d", n(i));
putchar('n');
}
/* Cross the river alone or with an 'anim' =
Check-out at 'from' and check-in at NOT-'from' */
void
ferry(Shores_t sh, int anim, int from) {
int to = !from;
sh(from)(anim) = 0;
sh(to)  (anim) = 1;
if (anim != Farmer) {           /* (or just repeat with same value) */
sh(from)(Farmer) = 0;
sh(to)  (Farmer) = 1;
}
}
/* Returns next valid node, above current, and different from lower node (no direct repetition!). */
/* Or -1 if none left.  Also updates the state stack by reference 'Shores_t sh'. */
int
next_node(Shores_t sh, Shores_t sh_0, int anim, int anim_0) {

memcpy(sh, sh_0, sizeof(Shores_t));         /* Work on last state in new level on stack */
const int fside = sh(1)(Farmer);            /* Where is the farmer at all? (note (1), not (Dest), makes that trick (?) less confusing)*/

while (++anim < Animals) {

if (sh(fside)(anim) && anim != anim_0) {

ferry(sh, anim, fside);                     /* Test crossing... */
if (is_unsafe(sh(fside)))
ferry(sh, anim, !fside);                /* ...undone by ferry() in reverse */
else
return anim;                            /* ...confirmed, done */
}
}
return -1;
}

/* Backtrack FWGC (fsgw) using next_node() */
/* With indep. tests for max. level (cycle breaker) and for end state */
void
backtrack_fsgw(int *nodes, Shores_t *states, int MAX) {

int LVL = 1;
while (LVL > 0) {

/* Display I: current level, old vars */
printf("(%2.d LEVEL)  cur:(%d) parent: %dn", LVL, nodes(LVL), nodes(LVL-1));
show_state(states(LVL-1));

nodes(LVL) = next_node(states(LVL), states(LVL-1),
nodes(LVL),  nodes(LVL-1));

if (nodes(LVL) == -1)
LVL--;

else {
/* Display II: after successful next_node() */
printf("    --> new node:(%d) and state: n",  nodes(LVL));
show_state(states(LVL));
putchar('n');

if (all_on_side(states(LVL)(Dest))) {
printf("ALL CROSSED - Level=%2.d  ", LVL);
show_nodes(nodes, LVL);
nodes(LVL--) = -1;
continue;
}
if (LVL == MAX) {
printf("MAXLEVEL reached - backtracking to escape cycle: ...");
show_nodes(&nodes(LVL-8), 8);  /* not too much back, if MAX is very low...todo; but then again it only shows 123... or 321... */
nodes(LVL--) = -1;
continue;
}
LVL++;
}
}
return;
}

/* Stacks for (i.e. Arrays of) the nodes (moves) and the states (Shores_t, int(2)(4)) */
int main(void) {

/* Maximum level:
- 32 is enough to give solution pairs at levels 7, 13, 19, 25 and 31. Also enough crossings to give up.
-  8 is enough for the first/best solution pair */
#define    MAXLEV 32
int      nodes (MAXLEV);
Shores_t states(MAXLEV);

int i;
/* Unvisited nodes have -1 */
for (i = 0; i < MAXLEV; i++)
nodes(i) = -1;

/* Starting position of F,S,G,W on Shore Zero */
for (i = 0; i < Animals; i++) {
states(0)(Start)(i) = 1;
states(0)(Dest) (i) = 0;
}

backtrack_fsgw(nodes, states, MAXLEV-1);

return 0;
}
``````

## can you help me with same problem? [closed]

I just don’t know where to set the chmod u+x /path/to/file.command"

## problem in view->result – Drupal Answers

iam using drupal 8.9
i have two blocks same design with 4 items for each , so i used same view with same view mode and change the filter of section by arguments as
`{{ drupal_view('homepage_blocks', 'block_5', '391') }}`
` {{ drupal_view('homepage_blocks', 'block_5', '286') }}`

the block has custom design( with one big image and 4 small) , so i write this code in hook_preprocess_node inorder to get the row index
`if(!empty(\$variables('view'))){ \$view = \$variables('view'); \$node = \$variables('node'); foreach(\$view->result as \$key => \$row){ if(\$row->nid == \$node->id()){ \$variables('_total') =count(\$view->result); \$variables('row_index') = \$row->index; \$variables('argg')= \$view->args(0); } } }`

Because one of the items in block 2 is in block 1 too ;
the problem appears that
the same node in block 2 take the argument for the first block (391).
so the view result array become different and the row index is changed .
the result as debugging was argg=286 for 3 items and the fourth is argg=391

please can any body help in this issue, how to make row index return correct and view result is independent for each view block.

## differential equations – Multiplicity in Laplace’s Eigenvalue Problem

I am computing Laplacian on a unit square $$textbf{numerically}$$.

Consider the eigenvalue problem on $$Omega = (0 , 1)^2$$ $$-Lu = lambda u$$ where $$L = frac{partial^2}{partial x^2} + frac{partial^2}{partial y^2}$$

The Dirichlet’s boundary condition is $$u = 0$$ on $$partial Omega$$.

I have written the following for first $$100$$ eigenvalues.

``````{ℒ, ℬ} = {-Laplacian(u(x, y), {x, y}),
DirichletCondition(u(x, y) == 0, True)};

{vals, funs} =
DEigensystem({ℒ, ℬ},
u(x, y), {x, 0, 1}, {y, 0, 1},100);

vals
``````

Now I am interested in computing multiplicity of eigenvalues. I already know that `Tally` can certainly count the occurrances of eigenvalues in the list called `vals`.

I know that $$textbf{analytically}$$ the eigenvalues are $$lambda _{mn} = (m^2 + n^2) pi^2$$ where $$m,n =1, 2, 3cdots$$. Moreover, calculating multiplicity of a specific eigenvalue is same as the number theory problem namely how many ways $$frac{lambda_{mn}}{pi ^2}$$ can be written as $$m^2 +n^2$$. For example, consider the eigenvalue $$5pi^2$$, the multiplicity of this eigenvalue is $$2$$ since $$5$$ can be written as $$5 = 1^2 +2^2 = 2^2+ 1^2$$. Similarly, Similarly, if we consider the eigenvalue $$50 pi^2$$, we can write $$50 = m^2 + n^2$$ in three ways, i.e. $$50 = 1^2 + 7^2 = 7^2 + 1^2 = 5^2 + 5^2$$. Therefore the multiplicity of the eigenvalue is $$3$$. Therefore, computing multiplicity (occurrances of eigenvalues in the list) of a eigenvalue $$textbf{analytically}$$ is equivalent to the above said number theory problem.

But I want to compute multiplicity without getting into analytic solution since most of the time analytic solutions are unavailable.

Also, the eigenvalue problem has infinite numbers of eigenvalue. So `Tally(vals)` in the following

``````{ℒ, ℬ} = {-Laplacian(u(x, y), {x, y}),
DirichletCondition(u(x, y) == 0, True)};

{vals, funs} =
DEigensystem({ℒ, ℬ},
u(x, y), {x, 0, 1}, {y, 0, 1},100);

Tally(vals)
``````

does not work properly. Therefore, since there are infinite numbers of eigenvalues and we can not list all of them, I am looking to compute the multiplicity of a eigenvalue (occurrances of eigenvalues in the list) without any specification on ‘numbers of eigenvalues’ and that would give me the complete multiplicity of that particular eigenvalue.

But it may be that I did not write the question properly. If you please improve my question, it’ll be appricitable.