text:
Self-Identifying Coordinates
Write a program or function that, given an integer n, construct an array with n dimensions of n length, where each element is an identifier of its own coordinates. That is, starting with one array, populate it with n arrays, where each of those contain n more arrays, up to a depth of n-1. The elements of the deepest arrays are the coordinates describing where they are in the full array.
Some examples in case my explanation was confusing.
n = 1
["1"]

n = 2
[
 ["11", "12"],
 ["21", "22"]
]

n = 3
[
  [
    ["111","112","113"],
    ["121","122","123"],
    ["131","132","133"]
  ],
  [
    ["211","212","213"],
    ["221","222","223"],
    ["231","232","233"]
  ],
  [
    ["311","312","313"],
    ["321","322","323"],
    ["331","332","333"]
  ]
]

Here, "321" means it is the 1st element of the 2nd element of the 3rd array.
Rules:

Coordinates and dimension (n) can be either 0 or 1 indexed
You may assume n is single digit, below 10 for both indexing options to prevent ambiguous outputs
IO is flexible.

In particular, coordinates can be arrays, strings etc. as long as they are clear. "321" => [3,2,1]
Output can be integers in base 10 with or without leading zeroes.
Coordinates can be in reverse order if you wish, as long as it is consistent. "321" => "123"
Output doesn't necessarily have to be an array structure in your language. As long as there's clear distinct markers for the start of an array, end of an array and for separating elements.
The output for n=1 can just be 1
If your output is atypical, make sure to explain the format.

This is code-golf so the shortest solution in each language wins!

Sandbox (deleted)

I was having trouble writing this in Haskell, before I realized that the type system makes it impossible.

@CatWizard: You could always define a new data structure to get around that, eg. data L a = L [L a] | E a.

@BMO Yeah, there are ways around it, but I was mostly interested in using monad properties of lists and new structures will lack those properties or need them implemented.

Related.

@CatWizard I'm interested, why is that? Can't you have lists of lists of lists of strings in Haskell?

How is this self referential? The output refers to themselves, not the answers.

@user202729 I was making reference to the self-referential nature of the elements of the matrix, but I guess you're right that it should be referring to the program itself. Removed the tag

So, if I'm understanding this correctly, you don't actually have to create an array at any time as long as the output format is maintained?

@amphibiological Yup! I like having the output for my challenges be super flexible to encourage creative answers. If you can shave off a few bytes by encoding your array differently than that's great!

Can there be a trailing element separator in each output list?

@Jakob Sure!...

@ToddSewell You can, the problem is that ["1"] is a different type from [["1"]].

@flawr Sure, but as far as I can tell there's no mixing of types going on in this challenge?

@ToddSewell You can't have a function whose type depends on the input. This function could have type Int -> [String] or Int -> [[String]] and so on, depending on what the input is

Dyalog APL, 5 3 bytes
⍳⍴⍨

-2 bytes thanks to FrownyFrog
Try it online!
⍳ gives all the indices given the shape of an array. e.g. 2 3.
⍴ reshapes the right arg to be the size of the left arg. ⍨ makes both be the right arg.

Python 3, 56 bytes
f=lambda n,*l:len(l)//n*l or[f(n,*l,k)for k in range(n)]

Try it online!
Mr. Xcoder saved 2 bytes switching to Python 3 for starred unpacking.

If you switch to Python ≥3.5, f=lambda n,*l:len(l)//n*l or[f(n,*l,k)for k in range(n)] works for 56 bytes.

Wolfram Language (Mathematica), 32 22 bytes
-10 bytes thanks to @alephalpha
Array[List,#~Table~#]&

Try it online!

Jelly, 8 7 bytes
ṗ³s³$³¡

Try it online!
Explanation
Use argument 2 as an example.
ṗ³s³$³¡
ṗ        Cartesian power with power
 ³       2 (the argument). Autoranges the left arg.
         Yields [[1,1],[1,2],[2,1],[2,2]]
    $³¡  Do 2 times:
  s³     Split into segments of length 2.
         This last step molds the array of indices into the proper shape.

If ¡ didn't vary it's right argument over iterations for dyads then this would be 4 bytes: ṗs³¡

This looks like a full program to me. Are you sure the output (STDOUT) for 1 is valid?

@EriktheOutgolfer I'm okay with the output for 1

@JoKing But, in this case, there aren't "clear distinct markers for the start of an array, end of an array". Do you want to edit the question? (a lot of answers don't actually contain them)

J, 18 bytes
,"1/^:(]{:)~@,.@i.

Try it online!
Iterative solution, no built-in cartesian product. This is what peak J looks like.
                       input                                    2
                i.     range                                 0, 1
             ,.@       reshape each element
                       into a one-dimensional array        [0],[1]   (A)
    ^:(]{:)            (input−1) times...             (1 iteration)
,"1/       ~@             prepend the contents of each 1d array in A    |
                          to every 1d array from the previous iteration,|
                          assembling the results for each A[n] into     |!CANTEXPLAINTHIS!
                          a larger array                                |
                                                         [ [0,0],       |
                                                           [0,1] ],     |
                                                         [ [1,0],       |
                                                           [1,1] ]      |

At first the higher byte count put me off, but this truly is beautiful J

Rust, 201 176 167 166 154 bytes
enum L{S(String),L(Vec<L>)}fn
h(n:u8,d:u8,s:&str)->L{if
d<1{L::S(s.into())}else{L::L((0..n).map(|i|h(n,d-1,&format!("{}{}",s,i))).collect())}}|n|h(n,n,"")

Try it online!
The output type is a sum type with two variants as the language is strictly typed. It can be either L, which is a list type containing this sum type or S which is a result type (a string). The result can look like this.
L::L([
 L::L([ L::S("00"), L::S("01") ]),
 L::L([ L::S("10"), L::S("11") ]),
])

Also, reformatted using rustfmt:
enum L {
    S(String),
    L(Vec<L>),
}
fn h(n: u8, d: u8, s: &str) -> L {
    if d < 1 {
        L::S(s.into())
    } else {
        L::L(
            (0..n)
                .map(|i| h(n, d - 1, &format!("{}{}", s, i)))
                .collect(),
        )
    }
}
|n| h(n, n, "")

J, 13 bytes
[:{[;/@$,:@i.

Try it online!
Interesting this is so much longer than the APL answer (though that may be my inability to see a better translation)
explanation
[: { [ ;/@$ ,:@i.

     [                NB. the argument
            ,:@i.     NB. range 0..arg, considered as one item: ,: is "itemize"
          $           NB. repeat the right range the left number of times
       ;/@            NB. and then put boxes around them. so, eg, if we had
                      NB. an arg of 3, now we have the list of boxes
                      NB. [0 1 2][0 1 2][0 1 2]
[: {                  NB. { is "Catalog", it creates the cartesian product
                      NB. in exactly the format we desire.

A better(?) translation

@FrownyFrog Using a hook to avoid #.inv is very clever, +1.

@FrownyFrog Now that I've looked at your "count up in different bases" solution, I think the approach is different enough that you should add it as another post yourself.  It's a very nice solution.

Jonah, @cole thank you

MATLAB, 92 89 55 bytes
I have a different answer having re-read the rules of the challenge, but I'll leave the previous attempt below as it's different and still fun to look at.
reshape(string(dec2base(0:n^n-1,n+(n<2))),[~(1:n)+n 1])

Explanation

                        0:n^n-1                        % [0,1,...,n^n-1]
               dec2base(       ,n+(n<2))               % Put into base n (base 2 if n=1)
        string(                         )              % Convert to strings
                                          [~(1:n)+n 1] % Dimension array [n,n,...,n] (length n)
reshape(                                 ,            )% Use dim array to reshape

This outputs an n-dimensional array of strings which are 0 indexed.
Previous Answer (89 bytes)
My first golf! This can likely be reduced more but I thought I'd post what I've got.
x=(1:n)';for d=2:n;y=((1:n)*10^(d-1));o=[];for p=1:nnz(y);o=cat(d,o,(x+y(p)));end;x=o end

Explanation
x=(1:n)';                       % Create array x=[1,2,...n]'
for d=2:n                       % d for dimension
    y=((1:n)*10^(d-1));         % Creates an array for each d where
                                %   y=[10,20,30,...] for n=2
                                %   y=[100,200,...] for n=3 etc.
    o=[];                       % o for output
    for p=1:nnz(y)              % For each value of y
        o=cat(d,...             % Concatenate in the dth dimension:
            o,...               % - The current output
            x+y(p));            % - The sum of
                                %   - The array from the last dimension
                                %   - The current value in y (e.g. 100)
    end
    x=o                         % Send the output to x for the next loop
end

Outputs x at the end to give solution
Similar to the other MATLAB post, the output is an n-dimensional array, except it uses numbers to display the coordinates. It works for any value, although because loops are bad in MATLAB it begins to slow down significantly around n = 8.
Edit: -2 bytes thanks to Luis Mendo. Also removed final semicolon to print the output.

Welcome to PPCG!

I think you can replace length by nnz to save a few bytes. Also, as per PPCG rules, the code has to produce some actual output, typically by displaying it in STDOUT (it's not enough to have the output stored in a variable), or it has to be a function that returns the output

R, 102 bytes
function(n,m=array(T,rep(n,n)))`if`(n<2,'1',{m[]=apply(which(m,T)[,`[<-`(1:n,1:2,2:1)],1,toString);m})

Try it online!

1-indexed, reversed
unfortunately R stores matrix by column, otherwise we could go down to 73 bytes
-9 bytes saved thanks to @Giuseppe suggestion to use which array
indexing

your 76 byte answer could be 73 bytes which is how I implemented it before checking to see if there was already an R answer. You might be able to change some of the approach, though? Not entirely sure.

@Giuseppe: array indexing of which is what I was looking for, thanks ! Saved 9 bytes

Java 10, 144 bytes
The solution is method f. It produces a string representation of the array.
String h(int n,int d,String s){if(d<1)return s;var r="[";for(int i=0;i++<n;)r+=h(n,d-1,s+i)+",";return r+"]";}String f(int n){return h(n,n,"");}

Try It Online
Ungolfed
String h(int n, int d, String s) {
    if (d < 1)
        return s;
    var r = "[";
    for (int i = 0; i++ < n;)
        r += h(n, d - 1, s + i) + ",";
    return r + "]";
}
String f(int n) {
    return h(n, n, "");
}

Acknowledgments

byte savings thanks to Konrad Borowski

In Java 10, you could replace Object[] with var. Also, I think this else block is unnecessary, as you have return in if block.

JavaScript (Node.js), 62 60 58 bytes
f=(n,i=n,s='')=>i?[...Array(n)].map((_,j)=>f(n,i-1,s+j)):s

Try it online!  Output is 0-indexed. Edit: Saved 2 bytes thanks to @JoKing and a further 2 bytes thanks to @Arnauld.

05AB1E, 7 bytes
LsãsGsô

Try it online!
Explanation
L          # push range [1 ... input]
 sã        # input repeated cartesian products of the list
   sG      # input - 1 times do:
     sô    # split into input parts

MATLAB, 116 108 104 bytes
I feel like there must be a shorter way to do this, given MATLAB's affinity toward multi-dimensional matrices... Thanks to Luis for the 4 bytes from some short-handing
a=~(1:n)+n;c=cell(1,n);[c{:}]=ind2sub(a,1:n^n);reshape(arrayfun(@(varargin)[varargin{:}],c{:},'un',0),a)

Explanation
% For using twice, define the array of dimension sizes [n, n, .., n]
a=~(1:n)+n;
% To group variable number of outputs from ind2sub into a cell array
c=cell(1,n);
% Convert linear indices to self-describing coordinates
[c{:}]=ind2sub(a,1:n^n);
% reshape to make it the n-dimensional array
% arrayfun to loop over the numerous ind2sub outputs simultaneously
% varargin and {:} usage to account for various numbers of inputs
reshape(arrayfun(@(varargin)[varargin{:}],c{:},'uni',0),a)

The output is an n-dimensional cell array, where each element is an array of the coordinate values. Works for any n without ambiguity because of the numeric array output, so long as an n^(n+1) element array can be stored in RAM!

Charcoal, 26 bytes
Ｎθ≔ＥＸθθ⪫⪪◧⍘ιθθ ¦0υＦθ≔⪪υθυυ

Try it online! Link is to verbose version of code. Explanation:
Ｎθ

Input n.
≔ＥＸθθ⪫⪪◧⍘ιθθ ¦0υ

Generate all nⁿ n-digit numbers in base n.
Ｆθ≔⪪υθυ

Split them n times into an n-dimensional array where each dimension is of size n.
υ

Print the array. The default output format is each element on its own line, then each block of n lines is terminated by a blank line, then each block of n blocks of n lines is terminated by a second blank line, and so on up to n-1 blank lines at the top level.

Jelly, 7 bytes
ṗṁẋ`ŒṬ$

Try it online!


text:
COBOL Y2K redux
In the 1990s, COBOL computer engineers worked out a way to extend six-digit date fields by converting them to YYYDDD where YYY is the year - 1900 and DDD is the day of the year [001 to 366]. This scheme could extend the maximum date to 2899-12-31.
In the year 2898, the engineers started panicking because their 900 year old code bases were going to fail. Being from the year 2898, they just used their time machine to send a lone Codeinator to the year 1998 with this algorithm and the task of getting it implemented as widely as possible:

Use a scheme PPQQRR where if 01 ≤ QQ ≤ 12 then it's a standard YYMMDD date in the 1900s, but if QQ > 12 then it represents the days after 2000-01-01 in base 100 for PP and RR but base 87 for QQ - 13.

This scheme extends far beyond year 2899 and is also backwards compatible with standard dates, so no modifications of existing archives are required.
Some examples:
PPQQRR  YYYY-MM-DD
000101  1900-01-01  -- minimum conventional date suggested by J. Allen
010101  1901-01-01  -- edge case suggested by J. Allen
681231  1968-12-31  -- as above
991231  1999-12-31  -- maximum conventional date
001300  2000-01-01  -- zero days after 2000-01-01
008059  2018-07-04  -- current date
378118  2899-12-31  -- maximum date using YYYDDD scheme
999999  4381-12-23  -- maximum date using PPQQRR scheme

Your challenge is to write a program or function to accept input as PPQQRR and output as an ISO date YYYY-MM-DD. Input method can be parameter, console or command line, whatever is easiest.
For your amusement, here is a noncompeting solution in COBOL-85:
IDENTIFICATION DIVISION.
    PROGRAM-ID. DATE-CONVERSION.
DATA DIVISION.
    WORKING-STORAGE SECTION.
    01 T PIC 9(8).
    01 U PIC 9(8).
    01 D VALUE '999999'.
        05 P PIC 9(2).
        05 Q PIC 9(2).
        05 R PIC 9(2).
    01 F.
        05 Y PIC 9(4).
        05 M PIC 9(2).
        05 D PIC 9(2).
PROCEDURE DIVISION.
    IF Q OF D > 12 THEN
        MOVE FUNCTION INTEGER-OF-DATE(20000101) TO T
        COMPUTE U = R OF D + 100 * ((Q OF D - 13) + 87 * P OF D) + T
        MOVE FUNCTION DATE-OF-INTEGER(U) TO F
        DISPLAY "Date: " Y OF F "-" M OF F "-" D OF F
    ELSE
        DISPLAY "Date: 19" P OF D "-" Q OF D "-" R OF D
    END-IF.
STOP RUN.

May output be a [Y,M,D] numeric list? Does it make a difference if that is my language's normal date format?

"But do not program in COBOL if you can avoid it." -- The Tao of Programming

Related HNQ: How to attract people to work on very old and outdated technologies?

Why from year 2000 and not 2900?

@user202729 because yymmdd doesn't work for for years >=2000, that's the entire point of the Y2K debacle.

@Adám -- In the spirit of COBOL which is very fussy w.r.t. I/O, I'll have to say it needs to be in ISO yyyy-mm-dd format.

Can we take input as an integer rather than as a string?

@Giuseppe -- In the spirit of COBOL which doesn't really differentiate strings and numbers, yes! Provided you can input leading zeros, e.g. 001300.

Suggested test cases: 000101 and 010101.

Additional suggested test cases: 010367, 000000, -99101, RABBIT

@Jay -- CodeGolf usually assumes input is valid. BTW 000000 is often used as an empty date in COBOL (akin to null). You can crash many a system by forcing a date field to all zeroes in a record!

@JonathanAllan -- Thank you, have added them including 681231. I was thinking the conventional dates were too trivial to bother with but your comments below have convinced me otherwise!

Do we ignore leap years?

@AlexanderRevo - No, leap years are important.

T-SQL, 99 98 bytes
SELECT CONVERT(DATE,IIF(ISDATE(i)=1,'19'+i,
       DATEADD(d,8700*LEFT(i,2)+RIGHT(i,4)-935,'1999')))FROM t

Line break is for readability only. Thank goodness for implicit casting.
Input is via a pre-existing table t with CHAR column i, per our IO rules.
Goes through the following steps:

Initial check is via the SQL function ISDATE(). (The behavior of this function changes based on language settings, it works as expected on my english-us server). Note this this is just a check for validity, if we tried to parse it directly, it would map 250101 as 2025-01-01, not 1925-01-01.
If the string parses correctly as a date, tack 19 on the front (rather than change the server-level year cutoff setting). Final date conversion will come at the end.
If the string does not parse as a date, convert it to a number instead. The shortest math I could find was 8700*PP + QQRR - 1300, which avoids the (very long) SQL SUBSTRING() function. This math checks out for the provided samples, I'm pretty sure it is right.
Use DATEADD to add that many days to 2000-01-01, which can be shorted to  2000.
Take that final result (either a string from step 2, or a DATETIME from step 4), and CONVERT() it to a pure DATE.

I thought at one point that I found a problematic date: 000229. This is the only date which parses differently for 19xx vs 20xx (since 2000 was a leap year, but 1900 was not, due to weird leap-year exceptions). Because of that, though, 000229 isn't even a valid input (since, as mentioned, 1900 was not a leap year), so doesn't have to be accounted for.

Good stuff. It's too bad ISDATE doesn't return a boolean, or that integers can't be implicitly converted to boolean in IIF otherwise you could save two bytes.

@YiminRong Yep, implicit casting in SQL is very trial-and-error, and works differently in some functions that are otherwise very similar. I'm lucky I didn't have to explicitly cast my LEFT() and RIGHT() function results to integers before multiplying them, that would really have messed up my byte count

I think you can remove an extra character by replacing -1300,'2000' with -935,'1999'.

Cool idea, @RazvanSocol. I tried going back further multiples of 365 days, but unfortunately couldn't find anything shorter than that.

R, 126 bytes
function(x,a=x%/%100^(2:0)%%100,d=as.Date)'if'(a[2]<13,d(paste(19e6+x),'%Y%m%d'),d(a[3]+100*((a[2]-13)+87*a[1]),'2000-01-01'))

Try it online!

-5 bytes thanks to @Giuseppe suggestion to take a numeric input instead of string

Fails for inputs representing dates prior to January the first 1969 (e.g. 000101 or 681231)

@JonathanAllan: well spotted, thanks. Now it should be fixed (unfortunately requiring 5 more bytes...)

JavaScript (SpiderMonkey), 103 bytes
s=>new Date(...([a,b,c]=s.match(/../g),b>12?[2e3,0,(b-13+a*87)*100-~c]:[a,b-1,c])).toJSON().split`T`[0]

Try it online!

.toJSON will failed on a UTC+X timezone. This code works, but longer (+11bytes):
s=>Intl.DateTimeFormat`ii`.format(new Date(...([a,b,c]=s.match(/../g),b>12?[2e3,0,(b-13+a*87)*100-~c]:[a,b-1,c])))

You can save 13 bytes with .toJSON().

And you can save 9 more bytes by splitting the input string into three 2-char substrings.

@Arnauld I was originally trying this on my machine. But it does not work since my timezone is UTC+8. But it at least works on TIO.

Since we define languages by their implementation (here 'Node.js running on TIO'), is it really invalid?

For the bullet-proof version, you can do it that way to save 1 byte.

@Arnauld updated. just never tested this on tio, and don't know its working.

TIO has a timezone offset of exactly 0. Thanks, Dennis! ;)

Python 2, 159 bytes
from datetime import*
def f(s):D=datetime;p,q,r=map(int,(s[:2],s[2:4],s[4:]));return str(q>12and D(2000,1,1)+timedelta(100*(q-13+87*p)+r)or D(1900+p,q,r))[:10]

Try it online!

Nice trick using ... and ... or ... instead of ... if ... else ....

ABAP, 173 171 bytes
Saved 2 bytes by further optimizing the output
According to the legends, an SAP customer in the early 21st century once said:

After a nuclear war of total destruction, the one thing remaining will be SAPGUI.

He was right. Today, in 2980, there is no more C++, no more COBOL. After the war everyone had to rewrite their code in SAP ABAP. To provide backwards compatibility to the leftovers of the 2800's COBOL programs, our scientists rebuilt it as a subroutine in ABAP.
FORM x USING s.DATA d TYPE d.IF s+2 < 1300.d ='19'&& s.ELSE.d ='20000101'.d = d + s+4 + 100 * ( ( s+2(2) - 13 ) + 87 * s(2) ).ENDIF.WRITE:d(4),d+4,9 d+6,8'-',5'-'.ENDFORM.

It can be called by a program like this:
REPORT z.
  PARAMETERS date(6) TYPE c. "Text input parameter
  PERFORM x USING date.      "Calls the subroutine

Explanation of my code:
FORM x USING s.     "Subroutine with input s
  DATA d TYPE d.    "Declare a date variable (internal format: YYYYMMDD)
  IF s+2 < 1300.    "If substring s from index 2 to end is less than 1300
    d ='19'&& s.    "the date is 19YYMMDD
  ELSE.             "a date past 2000
    d ='20000101'.  "Initial d = 2000 01 01 (yyyy mm dd)

    "The true magic. Uses ABAPs implicit chars to number cast
    "and the ability to add days to a date by simple addition.
    "Using PPQQRR as input:
    " s+4 = RR, s+2(2) = QQ, s(2) = PP
    d = d + s+4 + 100 * ( ( s+2(2) - 13 ) + 87 * s(2) ).
  ENDIF.
    "Make it an ISO date by splitting, concatenating and positioning the substrings of our date.
    WRITE:             "Explanation:
      d(4),            "d(4) = YYYY portion. WRITE adds a space after each parameter, so...
      5 '-' && d+4,    "place dash at absolute position 5. Concatenate '-' with MMDD...
      8 '-' && d+6.    "place dash at absolute position 8, overwriting DD. Concatenate with DD again.
ENDFORM.

ABAP's Date type has the odd property to be formatted as DDMMYYYY when using WRITE - might be locale dependent even - despite the internal format being YYYYMMDD. But when we use a substring selector like d(4) it selects the first 4 characters of the internal format, hence giving us YYYY.
Update: The output formatting in the explanation is now outdated, I optimized it by 2 bytes in the golfed version:
WRITE:  "Write to screen, example for 2000-10-29
 d(4),   "YYYY[space]                =>  2000
 d+4,    "MMDD[space]                =>  2000 1029
 9 d+6,  "Overwrites at position 9   =>  2000 10229
 8'-',   "Place dash at position 8   =>  2000 10-29
 5'-'.   "Place dash at position 5   =>  2000-10-29

Excellent, I like it. Now all we need is a version in MUMPS and we'll survive anything!

@YiminRong Thanks! Your COBOL-based question basically asked for something like this, I had no choice.

Kotlin, 222 bytes
Hard coded Calendar field names constants to save 49 bytes.
{d:Int->val p=d/10000
val q=d/100%100
val r=d%100
if(q<13)"19%02d-%02d-%02d".format(p,q,r)
else{val c=Calendar.getInstance()
c.set(2000,0,1)
c.add(5,(p*87+q-13)*100+r)
"%4d-%02d-%02d".format(c.get(1),c.get(2)+1,c.get(5))}}

Try it online!

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Make a Radiation Hardened Quine
Your task is to make a quine, that is a non-empty computer program that prints it's own source without reading it.  In addition if you remove any one byte from your original program the new program should print the source of your original program.
This is code-golf so answers are scored in bytes with fewer bytes being better.

Related

Also related (duplication instead of deletion)

Surely this is just an n=1 subset/version of https://codegolf.stackexchange.com/q/57257/42963 ?

@AdmBorkBork Any answer there is valid here and vice versa however the scoring is drastically different.  This question is straight code-golf and that is a code-challenge.

@AdmBorkBork, that's the one I was thinking of and assumed was the one Cat was referring to.

@MagicOctopusUrn Can't find any.

No Compile Error allowed if one char removed?

@l4m2 As long as the compiled program works as intended, compiler errors are fine.

@CatWizard Are you sure this question has an answer

@Agile_Eagle Yes here is one..

I think the radiation hardened quine question used to have an answer in A Pear Tree with the question being a code challenge based on how many bytes could be changed with the program still working.

Gol><>, 49 45 bytes
<<H~Kla}\`q%2l}}ss2"<\
<<H~Kla}\`q%2l}}ss2"<\

Try it online!
Verification!
I did this in Gol><> rather than ><> because the former has the handy K operator that copies the top n items on the stack, which makes duplicating the clean copy of the source code easier.
Explanation:
This works by having two copies of the executing code, and redirecting to the second one if the first is damaged. This fails when the last \ or the middle newline is removed, both of which are compensated for later.
<<                       Redirect left
                    <\  Switch to other source code if this line is irradiated
                   "     Push source with wrapping string literal
                ss2      Push quote
              }}         Move "< to end
          q%2l           If the length of the stack is not right
        \`               Push an extra \
       }                 Move the \ to the end
      a                  Newline
    Kl                   Duplicate the stack
   ~                     Pop the extra newline
  H                      Halt and print stack

Vyxal D, 73 51 bytes
`#Ėß₂:ṘQ,…+ṘẎ7:Ṙq`Ṙ:₂ßĖ#`
`#Ėß₂:ṘQ,…+ṘẎ7:Ṙq`Ṙ:₂ßĖ#`

Try it Online!
`#Ėß₂:ṘQ,…+ṘẎ7:Ṙq`        # push this string to the stack
                  Ṙ:      # reverse the string and push a copy
                    ₂ßĖ   # execute the top if the length is even

# EXECUTION at this point the stack is [ qṘ:7ẎṘ+…,QṘ:₂ßĖ# ]

               Ṙq         # quote and revert => [ `#Ėß₂:ṘQ,…+ṘẎ7:Ṙq` ]
            Ẏ7:           # get the 7 first char => [ `#Ėß₂:ṘQ,…+ṘẎ7:Ṙq` , `#Ėß₂:Ṙ ]
          +Ṙ              # revert and add => [`#Ėß₂:ṘQ,…+ṘẎ7:Ṙq`Ṙ:₂ßĖ#`]
       Q,…                # print, reprint and quit
 #Ėß₂:Ṙ                   # does nothing since the program ended

# END OF EXECUTION

                       #` # comment

When any char of the string is removed ₂ß prevents the execution

if a `` is removed, no code of the line will execute because the line will be either comented, either one single string either a mix of both and no execute fire

if ₂ is removed, the code will execute normally (as the deletion is not in the string)

if any of Ṙ:ßĖ is removed, the code will be either equal to 0, 1, a commented code or there will be no execution. This has no incidence and the code will executein the second line

In any case the first execute will either have the string untouched or a string without incidence, in wich case, the second execute will have the string untouched.
The program ends at the first sucessful execute since there is a quit instruction in the string

Klein 000, 196 190 176 144 138 bytes
<<+55.?.?.?(48*2+56*2*59*!(2+)?!@!?)+2(!*95*2*65+2*84(?.?.?.55+<<"</
<<+55.?.?.?(48*2+56*2*59*!(2+)?!@!?)+2(!*95*2*65+2*84(?.?.?.55+<<"</

Try it online!

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Fastest way to perform the equivalent of an if-statement in x86 assembly
The task is simple: Create an if-statement from scratch in x86 assembly that runs in as few clock-cycles as possible.

Must be x86 assembly.
Can't use any of the conditional jump/branch instructions (e.g. je, jne, jz, jg, jge, jl, jle).
Can use jmp to jump to existing blocks of code.
Can use cmp if necessary.
Can't call any external libraries or functions.
Can't use call.
Free to use any of the other available instructions in the Intel docs.
No C.
Any of the ~7 Intel Core architectures are acceptable (listed on page 10). Ideally Nehalem (Intel Core i7).
The if statement needs to check arbitrary conditions. Basically replicating the functionality of any one of the je, jge, etc. conditional jumps.

The winning answer is one that uses the fewest clock cycles possible. That is, it can have the most operations per second. Approximate clock cycle summaries are here: http://www.agner.org/optimize/instruction_tables.pdf. Calculating clock cycles can happen after the answer is posted.

, [tag:fastest-algorithm] is about asymptotic complexity, which can't apply here because everything is O(1).

Now... what exactly does "equivalent to an if-statement" mean? Would something like jmp [eax] be ok?

The if statement needs to check arbitrary conditions. Basically replicating the functionality of any one of the je, jge, etc. conditional jumps.

And then I realised that we can be faster, and use no additional registers:
cmp eax, ebx
mov eax, offset false_case
mov ebx, offset true_case
cmove eax, ebx ;or cmovb, etc.
jmp eax

xor ecx, ecx
mov edx, 1
cmp eax, ebx
cmove ecx, edx ;or cmovb, etc.
jmp [false + ecx*4]

false dd offset false_case
true  dd offset true_case
Accepts eax and ebx for the comparison.
Replace the cmov with the corresponding check to perform.

Wonderful, thank you so much for this bit.


text:
Shortest code in your language to persist a string across a reboot
Your Programs:
You'll write two programs (both in the same language). The storage program takes a string from STDIN and stores it somewhere persistent (see below) and then exits without error. The retrieval program takes no input, retrieves the string that was stored, and prints it to STDOUT.
Objective test of Persistence:
You should be able to run the storage program on your local machine, then power-cycle your local machine, then call the retrieval program on your local machine. You can stash the string however you want (even on the web) as long as you pass this reboot test.
Test Cases:
Storage then retrieval:
echo foo | Store
Retrieve
foo

Repeated Stores should overwrite (like a set() method):
echo foo | Store
echo bar | Store
Retrieve
bar

Repeated Retrieval is non-destructive (like a get() method):
echo foo | Store
Retrieve
foo
Retrieve
foo

Retrieval before any invocation of Storage:
You don't need to worry about this. Your retrieval program can assume that the storage program has been run at some point in the past.
Input/Output flexibility.
People have asked me to expand this from strict STDIN/STDOUT to the standard IO rules. I can't because it would introduce too many loopholes. Some standard IO options already have the input stored in a persistent way, eg "programs may take input from a file". I'd like to be more flexible than just strict STDIN and STDOUT, but without opening the floodgates.
From the standard IO rules thread I'm cherry-picking the ones that don't break the challenge:

Programs may take input via GUI prompts and command-line prompts if you want
Programs may output by displaying it on screen This includes GUI dialogs
Programs may take input via command-line arguments
Programs may output to STDERR but still can't actually throw errors.

If you use an alternate it must be user-interactive. The user shouldn't have to do any other work besides piping their input to your program, typing it into a prompt your program provides, or typing input as a command-line-arg of your program. The user shouldn't have to do anything other than running your retrieve program to see the output displayed on screen or sent to STDOUT or STDERR.
Allowed assumptions:

Your two programs will be run in the same directory
Your programs have read-write permissions for that directory
Files you create will survive the reboot (not in a temp dir)
One trailing newline that wasn't part of the string is allowed. No other trailing whitespace

This is code-golf, and your score is the sum of bytes from both programs.

You can stash the string however you want (even on the web) I'm not pretty sure that this should be valid.

so just echo $@>x and cat x is valid?

Your spec doesn't mention the ability to store multiple times, but you do have an example case that does so. May we assume a clean environment for each invocation of Store?

@Adám I believe you can assume that no attempt by the system will be made to stop storing the string.

@EriktheOutgolfer Why would it not be valid? Even if there is a loophole discussed on meta that doesn't prevent a challenge from specifically allowing it.

Web restrictions are usually about pulling stuff from the web as a loophole to get out of doing the work of creating that stuff. In this case, if it's on the web it's because you did the work of putting it there.

@Adám I'm not sure what you mean by clean environment. Store should be able to be called multiple times in the same session, and new Stores will simply overwrite previous ones. Only one string ever needs to be stored.

@JaredK Then you should specify so. May we return the first stored string rather than the last stored string?

The "multiple stores" example case specs that out. "foo" is stored first, then "bar" stored second. "bar" is then the expected behavior of a Retrieve. Perhaps I should have named these Get and Set. Store is slightly ambiguous because it could mean append instead of overwrite. But I'm looking for overwrite.

@JaredK Not too late to edit in order to make your question clearer.

Can the storage program modify the retrieve program?

@dylnan I just recommended against it. ;-)

@Bromind What if you set fire to your computer after running store but before running retrieve? You can do a lot of silly things to break it, I don't see the need to specify all these things.

@ovs yes, as long as it passes the example cases.

@pipe thanks for pointing that out. Example cases have been fixed

Somebody needs to write an answer for a computer with magnetic-core memory.

@Mark or the modern equivalents, microcontrollers with integrated flash/EEPROM/FeRAM/MRAM

@user71659: Or for a computer where resetting the CPU doesn't clear the RAM, just makes the CPU jump to an init routine at a pre-defined address.  (i.e. a normal embedded system where you have total control of the firmware.)

What about "print out that you require this string as a password at login after rebooting - and then use the string given as a password"?

The requirement to survive reboots and not just process restarts only eliminates overly elaborate solutions that involve storing things in places like shared memory or daemons.

@Kaz From what I've seen of this community so far, "overly elaborate" doesn't seem to be a common stumbling block. When it's between them and a juicy hack like that it kinda just gets them going even more.

zsh, 4 bytes
Store: >f (reads from STDIN and writes to a file called f)
Retrieve: <f (writes the contents of f to STDOUT)

I think we have a winner.

@Adám unless there is a token to write input to file in 1 byte :P

@FreezePhoenix There is probably none unless you write a new language now which is not allowed...

@Chromium check Z80 answer: some existing languages can write from a 0 bytes program.

TI-BASIC (Z80), 1 byte?
Store:  (just enter the string)
Retrieve: Ans (byte 27)
But if that isn't valid:
TI-BASIC (Z80), 7 6 bytes
-1 thanks to Jakob.
Store: Prompt Str0 (bytes DD AA 09)
Retrieve: disp Str0 (bytes ED AA 09)

Are you sure that's 5 bytes?

"->".length == 2

Oh... Is this the same thing I see on my calculators.

@FreezePhoenix TI-Basic uses tokens.

Aha... much better.

Hmm...Why not take input through Ans and persist it in the same variable? An empty store program and just Ans for retrieve should work: 1 byte!

@Jakob I'm not too familiar with TI calculators. Does Ans persist through a power cycle?

@Adám Z80 Maybe TI-BASIC does. I'm shocked by the number of people who don't even know 68k calculators (like the TI-89T) exist!

@Arthur Yep, Ans persists. In fact, a lot of state persists, including (I think) all user variables, equations, and history. From the user's perspective, powered off is basically the TI calculator equivalent of a sleep state for a PC, so it doesn't disrupt much.

whispering because I'm so tickled by your one-byte solution I don't actually want you to change it: Your zero-byte Store doesn't 'exit'. I think a reasonable definition of a program exiting is that other programs can then be run. But if I do anything else between your 1-byte store and 1-byte retrieve, it doesn't seem like it would work. Two excellent answers though. +1. Your 6 byte solution I find no flaws with.

@JaredK I definitely agree that the 1-byte solution smells of rule abuse (even though I was the one who suggested it). However, I would say the store program exits, since other programs can be run after it (though they interfere with the operation of the solution). My interpretation of your "objective test of persistence" was that the programs would be run directly before and after the power cycle. If that is incorrect, perhaps you could require the 1-byte solution to be marked noncompeting?

Does it persist if you remove the batteries? Because arguably the "power" button on the calculator is really just a sleep button that keeps the SRAM powered up. I had a TI-83 which used a second button cell so you could change the main batteries without losing everything.

@user Right, some of the older calculators use a backup battery, but newer ones like TI-83 Plus use non-volatile Flash memory.

@Adám but even for things like Ans? Because Ans changes every time you make a calculation so storing it in flash memory would quickly wear that memory out.

The only things stored in Flash memory are FlashApps, OS image, and ARCHIVE'd variables. It's been a while but I don't think there's a way to ARCHIVE something programatically.

Browser JS, 44 bytes
Store:
localStorage.a=prompt()

Retrieve:
alert(localStorage.a)

Will prompt() read from STDIN?

Does a graphical web browser have an STDIN? No. prompt() pops up an alert that asks for you to enter text, and returns the result.

@Dev Of course a graphical web browser have a STDIN, just like every other process. If you can't use it from a specific language is another question and if the answer is "No", then I maybe it can be used in this challenge.

@Dev The default I/O methods include input via GUI prompt and output via GUI display. Unless OP meant to override the standard, this should be valid. I'll clarify.

I've edited the challenge to allow more IO, but I'm only expanding it to a limited subset of the default IO methods. This answer is within my subset though. I like it.

@Dev every modern browser has a developer console which I would consider as stdin and out

@EsolangingFruit I never once said prompt() did not count as input?

No, Armin was not being condescending

@Dev Did my comment come across as condescending? If so, I'm sorry; I did not mean it that way.

Why is this my highest voted answer...

POSIX shell sh/bash/... 8 bytes
store:
dd>f

get:
dd<f

Nice one, beats even cat...

Python 3, 46 bytes
store, 45 bytes:
open(*'fw').write('print(%r)'%open(0).read())

The retrieve program is built by the store command, a file named f. (1 byte for the file name)

Surely you can use input()?

@ArtemisFowl input() only receives up to the first newline. open(0).read reads all of STDIN

You probably posted when things were still ambiguous, but as-is this answer doesn't meet the current spec. I originally intended the STDIN/STDOUT requirement to be strict, with defaults not allowed. I've expanded it, but only to a subset of the defaults. Your retrieve program, if it doesn't use STDOUT, still needs to display the output on screen. If I allowed the full defaults, the solution for every language would be 'takes input in a file' , 'gives output in a file', zero bytes.

@JaredK I don't think you quite get how this works. The store-program reads the input from STDIN and then stores a Python program that prints this input in f. Example: STORE is called with an input of abc. It then writes print('abc') to f. If you now call f (RETRIEVE), it prints abc to STDOUT.

@JaredK I asked you in a comment whether it was allowed to for STORE to modify RETRIEVE.

OH! that's clever. Nicely done.

Batch, 16 bytes
COPY CON A
TYPE A

Rust, 136 bytes
Store (84 bytes)
use std::{fs::*,io::*};

||{let mut v=vec![];stdin().read_to_end(&mut v);write("a",v)}

Retrieve (52 bytes)
||print!("{}",std::fs::read_to_string("a").unwrap())

Acknowledgments

-1 byte thanks to Esolanging Fruit

You can save a byte by changing the import to use std::{io::*,fs::*} and then using write instead of std::fs::write.

How about write("a",String::from_iter(stdin().chars()))?

@Bergi Nice. But chars triggers error[E0658]: use of unstable library feature 'io' in stable Rust.

Hm, it seems chars() is deprecated in favour of String::from_utf8(stdin().bytes()). (Also I used the nightly docs, not sure whether that's the culprit)

@Bergi I tried a few variations with bytes() or chars() but none of them were very short because the iterator item is wrapped in io::Result.

Bash, 12 11 10 bytes
store, 7 6 5 bytes
cat ->f # no need for -, stdin is default
cat >f # no need for space, > separates as well
cat>f

retrieve, 5 bytes
cat f

No need for - in the store program.

No need for the space between "cat" and ">", either!

You should be able to do the same as in the zsh post for writing and use >f. I am not sure if <f is valid for reading, though.

@allo At least on Cygwin, >f works like echo '' > f (emptying the file if it exists, creating if it doesn't), while <f seems to be a no-op.

Powershell - 4 Bytes
Storage:
ac

(alternative also sc)
Retrieval
gc

Edit: I just noticed the output is not allowed any user input... so it jumps from 4 to either 6 or 8 bytes
Storage:
ac f

(alternative also sc f) for the 8 byte version
ac

(and specify f as path) for the 6 byte Version
Retrieval
gc f

HP 49G RPL, 48 bytes
To save: :2: A DUP PURGE STO, 26.5 bytes
To restore: :2: A RCL, 21.5 bytes
If we can leave in the backup battery, we get:
HP 49G RPL, 0 bytes
To save: , 0 bytes
To restore: , 0 bytes, since the HP 49G leaves the stack untouched across reboots.

The zero-byte solution should work for a variety of caluclators. I'll bust out my 42s when I get home.

I think your zero-byte solution, and the others being run on calculators that reboot non-destructively, are failing to meet two parts of the question: "You will make two programs." What you've got is a single program that survives the reboot. And "Store reads from STDIN and then exits without error." Your program is still waiting for the user to press a key. Your program's stack and execution state are still mutable. I think that means it is still running, and hasn't exited.

@JaredK The question never stipulated that the two programs couldn't be identical. As for the exiting part: traditionally in RPL input to programs is given on the stack. That is the standard input.

Would the stack survive a power cycle? Maybe a soft power-off via the calculator's buttons, but I'm guess not removing the battery. So maybe it depends what a power cycle is.

@user No, stack doesn't survive soft (ON+C) or hard reset (ON+A+F) (distinct from soft-power off, Right Shift+ON), unlike storing in port 2, which is flash memory (and survives soft and hard reset). Since the TI-BASIC answer seemed to use that definition I included the stack answer for completeness.

@JaredK accidentally submitted my comment. About exiting: the program is not waiting for user input because standard input is the stack, so the string is assumed to be already entered. A 0 length program terminates instantly. You can verify it's not running because the busy annunciator is off, and that it's not waiting for user input by the lack of a cursor. (If the program was still running on either an HP calculator or a TI, doing Shift+ON to turn the calculator off would instead interrupt the program and leave the calculator on. Since this doesn't happen, a program is not running.)

APL (APLX), 5 bytes
Store: ⍞⍈1
Retrieve: ⍇1
⍞ get line from stdin
⍈1 write to next available component of file number 1
⍇1 read the first* last component of file number 1

* Documentation says first but experimentation shows last.

bash, 10 bytes (non-competing)
touch $@
ls

Unix filenames can contain any character except NUL and /, and their names can be upto 255 bytes long so this will be able to store only strings up to that length (consider that a limitation of the storage medium), and that don't contain '/' in them. That's one reason this is non-competing, another is that this assumes the directory it's run on is empty (or that extraneous output from ls is allowed). I still wanted to post this because it just seemed a cool and non-obvious way to store information.
Another on a similar vein, which wouldn't have the same length and character limitations would be:
35 33 bytes
mkdir -p $@
find|sed '$!d;s/..//'

This allows the / character in the string, and supports many more characters (exactly how many depends on implementation).
(-2 bytes on this thanks to @Cows quack)

IIRC, I believe that a group at Berkeley once created a database system back in the 1990s that stored table column data as filenames (up to 255 chars). I think the rows and tables were parent directories.

In your 35 byte answer, you can change the second statement to s/..//. The $ is not required because all other lines are deleted so this can only apply to the last line, and the ^ can be dropped because the substitution is only applied on the first match.

@Cowsquack Done. Thanks for explaining why the change works, too.

You need to use "$@", not $@, to avoid getting burned by whitespace, *, ?, or ~ characters.

Python 3, 56 bytes
Store (33 bytes)
open(*'aw').write(open(0).read())

Retrieve (23 bytes)
print(open('a').read())

Prints with a trailing newline.

why not input() instead of open(0).read() and omit end= from print?

@MoxieBall Not sure about why input wasn't used, but omitting end= would result in a new line being added to the end of the string (i.e., not the original string) (maybe)

@NickA It looks like a newline gets printed in the question, anyways, so I don't think that should matter...

Have I gone crazy or does 23+33=56 (not 54)? Also why not  use input()?

@ArtemisFowl Good catch. As for input, I assume that the string to persist may contain newlines.

Japt, 46 30 bytes
-16 bytes thanks to Shaggy.
One of the first times I've tried using Japt. The JS eval can be fidgety sometimes. Uses the browser's window.localStorage.
Store (16 bytes)
Ox`lo¯lSÈSge.P=U

Retrieve (14 bytes)
Ox`lo¯lSÈSge.P

+1 for being the first to use something other than standard file IO I like it.

Welcome to Japt! :)

By the way, you can bypass setItem and getItem completely with localStorage.key. Set value, retrieve value

@Shaggy Thanks! Yours also avoids the weirder control characters.

Haskell, 46 bytes
Store (26 bytes):
getContents>>=writeFile"t"

Retrieve (20 bytes):
readFile"t">>=putStr

C (GCC), 98 bytes
Store (46 bytes)
Input is via first command line argument.
main(c,v)char**v;{fputs(v[1],fopen("a","w"));}

Retrieve (52 bytes)
c,d;r(){for(d=open("a",0);read(d,&c,1);)putchar(c);}

Unportability

Requires that several pointer types fit in int.

Acknowledgments

-2 bytes thanks to ceilingcat
-10 bytes thanks to Peter Cordes

This requires a C implementation where int can hold a pointer, for the implicit declaration of int fopen() to work.  (e.g. most 32-bit systems, or use gcc -m32 if you're on x86-64 to make a 32-bit executable.)  And BTW, I tried using Linux's sendfile and copy_file_range(2) system calls, but they don't work to/from a TTY.

Since you're writing functions, not programs, perhaps you could justify taking the input string as a function arg allowing fputs(fopen()), and read(open(),buf,-1).  (The question now allows a command-line arg as input.)

The Linux 'splice' function copies from a pipe to a file (and vice-versa). If stdin/out are pipes, then it will save a function call, at the expense of more parameters.

Ruby (26 Bytes)
Set (16 Bytes)
IO.write'a',gets

Get (10 Bytes)
IO.read'a'

MATLAB (30 Bytes)
Set (22 Bytes)
a=input('','s');save a

Can shave off 4 bytes by changing to input(''), but this will require input to be in single quotes: 'input string'
Get (8 Bytes)
load a;a

APL (Dyalog Unicode), 18 bytes
Store: ⍞⎕NPUT⎕A 1 Try it online!
Retrieve: ⊃⎕NGET⎕A Try it online!
⍞ get line from stdin
⎕NPUT put it in a native file called
⎕A the uppercase alphabet
1 and overwrite if the file exists
⊃ the first part (the data, the next parts are encoding and line ending type) of
⎕NGET get the native file
⎕A the uppercase alphabet

R (27 bytes)
store (21 bytes)
x=readLines('stdin')

load (6 bytes)
cat(x)

For this to work, the first script needs to be invoked with the command line option --save, and the second one with --restore (though in interactive mode this isn’t necessary: these options are the default).
This could be shortened by 7 bytes were it not for the fact that a bug in R prevents the default argument of readLine from working in non-interactive mode. In interactive mode, it is not necessary, and the solution therefore only uses 20 bytes.

I think it would be much more efficient to use q directly, with the first program being x=scan(); q("y") and the second either x or cat(x) depending on how strict we want to be about how strings are printed. By the usual code golf rules you must also count command line arguments, so add bytes for --save and --restore (which my formulation doesn't need)

@JDL scan doesn’t work for arbitrary contents, and scan(w='character') is longer than readLines(). q is unnecessary (but q('y') wouldn’t work, you have to spell it yes). I thought about just using x in the second program but this would violate the requirements, as far as I understand them.

you can use scan(w=""), you don't need to spell out the type, scan will infer it from the type of argument specified. For me, q("y") works as a save-inducing quit but perhaps that depends on your version of R, and possibly whether you are using Rstudio or not.

@JDL scan: Oh, neat, the documentation doesn’t mention this! Unfortunately scan will still perform some parsing so this won’t work with all input. Anyway, scan('stdin',w='') happens to be the exact same length as readLines('stdin'). q: R 3.4.4 says “Error in q("y") : unrecognized value of 'save'”.

Ah, it's an Rstudio thing — I tried it in Rstudio and separately at the terminal and it only worked in Rstudio.

Perl 5, 48 26 23 bytes
Write, 20+1(-n) bytes
-3 bytes thanks to mob

open f,">>f";print f

I'm actually not certain about this one points-wise, but it meets the criteria. For past entries, only the cli options were counted, so that's what I'm going with.
Read, 0+2 bytes
perl -pe "" f

Why did you score -ne with 1 (it should have an e too), but -pe with 2? You could use -E and say instead of print.

Thank you for letting me know about -E, I wasn't familiar with that one. As for why I didn't go with -ne, it is because for that one, I'm actually running from a file. So, it would look like perl -n w.pl If this goes against PCG community standards though, I can edit my answer accordingly.

No, it's fine. We add a malus for extra command line arguments, so it's fine.

">>","f" --> ">>f" saves 3 char

Java (JDK 10), 204 Bytes
Warning: Overwrites any preferences that any java programs have stored for your username!
Store, 94 Bytes:
interface S{static void main(String[]a){java.util.prefs.Preferences.userRoot().put("",a[0]);}}

Try it online!
Retrieve 110 Bytes:
interface R{static void main(String[]a){System.out.print(java.util.prefs.Preferences.userRoot().get("",""));}}

Try it online!
java S foo
java R
foo

This works by taking input as an arg and storing it in the user preferences backing-store provided by java.util.prefs. It overwrites the user's root node to save one byte on naming a node. If you want to test it non-deestructively, either run it from a throwaway username or change the key from "" to a node name.

Good idea! Since you're using Java 10 you can shorten these by making them lambda expressions. Also if your byte count doesn't include z you should remove it from the programs and the TIO. Consider putting a warning at the top of the submission instead to warn people. For sure the TIO should have your 94- and 110-byte solutions.

Thanks! I made your suggested edits. I'm not certain but I don't think lambda expressions can fulfill the custom IO rules for this question.

D'oh. You're right, I forgot about that.

C#, 157 Bytes
Set, 74 Bytes:
class P{static void Main(string[]a){System.IO.File.WriteAllLines("a",a);}}

Get, 83 Bytes:
class P{static void Main(){System.Console.Write(System.IO.File.ReadAllText("a"));}}

-1 Bytes thanks to VisualMelon
-2 Bytes thanks to LiefdeWen

Remove that space after "a",, and I doubt this will be beaten :)

You can save another byte by using WriteAllLines and the second param a

Sed, 2+2 bytes:
Stores to file f:
wf

Reads from file f:
rf

Try a demo online!

Attache, 23 + 16 = 39 bytes
Simply writes STDIN to file A, then reads file A.
store.@:
$A&FileWrite!AllInput[]

retrieve.@:
Echo!FileRead!$A

Testing
C:\Users\conorob\Programming\attache (master -> origin)
λ echo testing | attache store.@

C:\Users\conorob\Programming\attache (master -> origin)
λ attache retrieve.@
testing

Lua, 57 53 51 bytes
Store, 27 bytes
io.open("x","w"):write(...)

Retrieve, 24 bytes
print(io.open"x":read())

RUBY
Store (24 bytes)
File.write('a', ARGV[0])

Retrieve (16 bytes)
p File.read('a')

The question asks for storing input from STDIN, not the arguments

I've since edited to allow IO alternates including arguments.

File.write'a',gets and p File.read'a' are a bit shorter ;)

C (Unix/GNU), 23+23 = 46 bytes
Store, 2723 bytes
main(){system("dd>f");}

Retrieve, 2723 bytes
main(){system("dd<f");}

This basically wraps jofel's answer into a C program.
Note: The dd commands outputs some statistics to stderr, so you will see some additional output when you naively run it in the shell. However, since the challenge only says that the stored string must be presented on stdout, not stderr, I take it that it is allowed to have additional output on stderr... Anyway, suppressing stderr output is as easy as replacing dd with cat, increasing the byte counts of the two programs by one, each.

Depending on your compiler you may also be able to remove the int return type from main. In old ANSI C style int is the default return type.

@Jakob Ah, yes, of course. I relied conciously on the implicit declaration of system() and forgot about that of main() - ouch. Thanks for pointing that out :-)

C (gcc), 77 67 + 25 = 92 bytes
Compiles with only a few warnings on my gcc.
store.c
#include<stdio.h>
main(int c,char**v){fputs(v[1],fopen("f","w"));}

Can probably golf out the include, but I couldn't figure out how.
Segfaults if you don't pass it anything, but whatever.
Peter Cordes: -1
read.c
main(){system("cat f");}

int*f=fopen should work, i.e. lie to your compiler about the pointer type.  But only if you compile for a 32-bit system (i.e. one where int can hold a pointer, like gcc -m32, or just gcc on a fully 32-bit system).  You can also declare main as main(int c,char**v), or maybe int**v because you're not dereferencing.

The main(int c,char**v) works. I also realized I can do fputs(v[1],fopen("f","w"), although it still needs stdio for some reason.

It should work if you compile a 32-bit executable.  For x86-64, the compiler will truncate the int return value to 32 bits, then sign-extend that as a pointer.  If the returned FILE* is in the low 32 bits, it would work, but that's not the case on x86-64 Linux.

If you are on a system where all pointers are equal in size (rather likely), you can avoid the include by declaring fopen manually. Going old school with the arguments saves some bytes too: *fopen();main(c,v)int**v;{fputs(v[1],fopen("f","w"));}.

PHP, 26+1 + 21 = 48 bytes
Store.php:
<?fputs(fopen(s,w),$argn);

Run with echo <input> | php -nF Store.php.
Retrieve.php:
<?=fgets(fopen(s,r));

Run with php -n Retrieve.php.

JavaScript (Node.js), 129 bytes
Store, 78 bytes
(p=process).stdin.resume().on('data',t=>require('fs').writeFile('_',t,p.exit))
Retrieve, 51 bytes
console.log(require('fs').readFileSync('_','utf8'))

Batch - 11 Bytes
%12>f
type f

The input is received as a command-line argument and persists (with the error message created upon execution attempt, since CMD attempts to execute the parameter) in f.

Batch - 7 Bytes (non-competitive)
'>%1
dir

There are a plethora of invalid characters in a file name, so this wouldn't work for some strings, but this essentially saves an arbitrary character to the filename given by the parameter. To read it, it just lists all files in the directory, including our string.

Your solution appears to output on STDOUT, which is valid. STDERR is just another option, not required. The quotes around the input don't stop it from competing. The only question is whether they should be counted in your byte count. I think not, since they aren't specific to the question. They seem like standard boilerplate for Batch to take a command line arg, which isn't so different from languages that need standard command line flags. Maybe someone else with Batch knowledge will chime in. For now leave them out of the byte count. Welcome to Code Golf! :)

Java 8, 156 bytes
Both solutions are lambdas taking empty input and throwing java.io.IOException.
Store (93 bytes)
import java.nio.file.*;

v->Files.copy(System.in,Paths.get("a"),StandardCopyOption.values()[0])

Retrieve (63 bytes)
import java.nio.file.*;

v->Files.copy(Paths.get("a"),System.out)

SmileBASIC (v3+), 23 + 14 = 37 bytes
Simple filesystem-based answer. Works in all known SmileBASIC environments v3.x or above. Be careful, in case you happen to have an important text file named A!
Store, 23 bytes
LINPUT S$SAVE"TXT:A",S$

Retrieve, 14 bytes
?LOAD("TXT:A")

SmileBASIC (v2), 21 + 16 = 37 bytes
Adjusted to work on old SmileBASIC (Petit Computer/mkII for DSi).
Store, 21 bytes
LINPUT MEM$SAVE"MEM:A

Retrieve, 16 bytes
LOAD"MEM:A
?MEM$

I'm honestly kinda amazed both versions work out to the same total byte count.

Powershell | 26 bytes
Store (store.ps1 | 24 bytes)
"`$s='$input'">>$profile

Retrieve (retrieve.ps1 | 2 bytes)
$s

Calling
Read-Host|.\store.ps1

# close powershell, reboot
# open new Powershell

.\retrieve.ps1

The question asks for storing input from STDIN, not the arguments

@Ferrybig How's that

Wouldn't Read-Host >t and gc t be sufficient?

my bad about arguments vs STDIN. I said STDIN in the challenge description but then showed arguments in the example cases. It's fixed now.

@JaredK So now that I have revised, this is correct now right?

I'm not a powershell guy and only have linux boxes nearby at the moment, so I can't verify, but if it's taking from STDIN then yes.

Sorry to be yanking your requirements around. People wanted more IO flexibility than just strict STDIO, so now command-line arguments are legal.

Cgam, 7 bytes
Store, 4 bytes
qSow

Retrieve, 3 bytes
Sog

Unfortunately, there is not yet a web interpreter, all you can do is download the code, build it, and run it yourself...

NodeJS (REPL) v10.0.0, 57 bytes
Store: fs.writeFileSync("a",process.args)
Read: fs.readFileSync("a")+[]

Mathematica, 23 bytes
InputString[]>>"a"

Put[], abbreviated >> as an infix operator, receives an expression as its left operand, then writes that expression to the filespec given in its right operand, here the file a. InputString[] interactively (graphically or textually, depending on how the kernel is being accessed) receives a string and returns that expression.  This store program is 18 bytes.
<<"a"

Get[], abbreviated << as a prefix operator, reads the file specified by its right argument, evaluating each expression in it, then returns the last such expression.  This retrieval program is 5 bytes.
You can use Directory[] to find out where the file is stored.  The representation stored in the file is quoted, so is equivalent to an expression representing a string.

Pascal (95+92=187)
Store:
program i;var f:Text; s:string;begin Assign(f,'i');Rewrite(f);Read(s);Write(f,s);Close(f);end.

Retrive:
program o;var f:Text;s:string;begin Assign(f,'i');Reset(f);Read(f,s);Write(s);Close(f);end.

You can omit Close(f); in retrive and shorten it a little bit, but, not in a spirit of pascal!

Yabasic, 36+38=74 bytes
Two scripts that write to the file t in the current directory. TIO Link provided both the getter and setter in both cases
Setter
Input""s$
Open#1,"t","w"
?#1s$
Close#1

Getter
Open#1,"t","r"
Input#1t$
Close#1
?t$

Try it online!

HP‑41C series, 16 B
The alpha‑register (α‑register) can store up to 24 alphabetic characters.
The contents of the α‑register are persistent.
You can turn the calculator off and on again, they remain there until overwritten.
01♦LBL "S"         5 Bytes    global label requires 4 + (length of string) Bytes
02 CLA             1 Byte     clear contents of α‑register
03 AON             1 Byte     activate alpha‑keyboard
04 PROMPT          1 Byte     display α‑register and stop program execution
05 RTN             1 Byte     `RTN` does not affect local label search

The CLA (clear alpha) command clears the contents of the α‑register.
This is necessary in case of empty input.
The subsequent PROMPT command does not change the α‑register in case there is no input at all.
The PROMPT displays the contents of the alpha‑register, and stops the program.
The user can enter a string now.
Once the R/S (run/stop) key is pressed (≘ end‑of‑file indicator),  program execution resumes with the command following the PROMPT command.
01♦LBL "R"         5 Bytes    "S" like "store", "R" like "retrieve"
02 AVIEW           1 Byte     select the α‑register as the current display
03 RTN             1 Byte     this is cheaper than an `END` (3 Bytes)

Keep in mind, if in your program further calculations follow, the AVIEW (alpha view) command by itself does not stop program execution and allow the user to read the display.
The AVIEW command is therefore usually paired with other commands such as STOP.
Note, if flag 21 (printer enable) is set, but there is no printer or the printer is off, AVIEW does in fact stop program execution (so the user has a chance to manually record display contents).
To resume operations press R/S (run/stop).

Note, leading NULL Bytes cannot be stored and retrieved to and from the α‑register.
Moreover, another implementation could use text files.
Text files permit storing records of up to 254 alphabetic characters each.
See also HP‑49G RPL submission, a different pocket calculator by the Hewlett‐Packard Company.


text:
Addition-Subtraction of Numbers Within String
Take a string as an input, and perform addition/subtraction of all the digits in the string and output the sum of those operations as the result.
Rules

The digits in the string are read from left to right
If a digit (n) is odd, perform addition with the next digit (n + n1)
If a digit (n) is even, perform subtraction with the next digit (n - n1)
If you've reached the last digit in the string, perform the operation with the first digit in the string
Output will be the sum of all the resulting values
If there is only one digit in the string, perform the operation with itself (n+n or n-n)
If there are no digits in the string, output is 0

Example
Input: r5e6o9mm!/3708dvc
Process: (5+6) + (6-9) + (9+3) + (3+7) + (7+0) + (0-8) + (8-5)
Output: 32

Notes

Either function or full program is accepted
Maximum input length would depend on your language's limit for a string input
No restrictions on character input, but only half-width digits count towards the output
Fewest bytes wins

Yup, mistakes were made on the original post. Edited now to make it clearer. Thanks for pointing them out, they should be all match with the instructions now.

A couple more examples would be good too

I'd recommend to add a test case ending with an odd digit.

Suggested testcase: "", "0", "1"

Can we take input as an array of characters instead of a string? (Julia makes a distinction between those two.)

@sundar The current consensus is that a string is defined as a sequence of characters. My understanding is that arrays of characters are therefore allowed by default even if your language has a native string type.

@NoirAntares "If a digit (n) is even or 0, ..." - you could say just "If a digit (n) is even, ..."

Jelly, 17 15 12 bytes
fØDV€ḂT‘ịƲSḤ

Try it online!
Try test cases.
The program keeps only the digits that follow an odd digit then computes twice the sum.
fØDV€ḂT‘ịƲSḤ
f                   Remove anything that isn't...
 ØD                 a digit.
   V€               Cast each digit to an integer
         Ʋ          Monad:
     Ḃ              Parity of each digit.
      T             Indices of truthy elements (odd digits).
       ‘            Increment.
        ị           Index into list of digits.
                    Wraps to beginning and if there are no digits this returns 0.
          S         Sum.
           Ḥ        Double.

K (oK), 47 43 40 31 bytes
Solution:
{+/(1_x,*x)*2*2!x^:(x-:48)^!10}

Try it online!
Explanation:
Remove everything from string that isn't a number (whilst also converting), modulo 2, multiply by 2, multiply with x rotated by 1, and sum up.
{+/(1_x,*x)*2*2!x^:(x-:48)^!10} / solution
{                             } / lambda taking implicit x
                           !10  / range 0..10
                          ^     / except
                   (     )      / do this together
                    x-:48       / subtract 48 from x (type fudging char ascii value -> ints), save back into x
                x^:             / x except right, and save back to x
              2!                / modulo 2
            2*                  / multiply by 2
           *                    / multiply by
   (      )                     / do this together
        *x                      / first element of x
       ,                        / append to
      x                         / x
    1_                          / drop first (ie rotate everything by 1)
 +/                             / sum, add (+) over (/)

Naive solution:
Remove everything from string that isn't a number (whilst also converting), take 2-item sliding window, figure out whether they are odd or even, apply add/subtract as appropriate, then sum up.
{+/((-;+)2!x).'2':(1+#x)#x^:(x-:48)^!10}

Try it online!
Notes:

-4 bytes thanks to @ngn due to a smarter way of filtering the input
-3 bytes by using sliding window rather than reshape
-9 bytes porting ngn's solution (non-naive approach)

x:48!x@&x in,/$!10 -> x^:(x-:48)^!10

I wrote the solution in q/kdb+ then ported to oK... might be able to squeeze a few more bytes out of this yet!

I posted a separate answer in ngn/k, feel free to bring in ideas from there. I think oK will end up being the shortest, as my parser is rubbish at the moment - it doesn't parse modified assignment properly. By the way, I wasn't aware of ': as "sliding window" - interesting.

You seem to be well familiar with k. If you ever feel like discussing vector programming stuff with like-minded people or just watching the rest of us argue - we've got this chat room. Most of the banter is about APL, but k and J are on-topic too.

Python 2, 86 bytes
k=[int(a)for a in input()if'/'<a<':']
print sum(a-(-1)**a*b for a,b in zip(k,k[1:]+k))

Try it online!

05AB1E, 12 9 bytes
Saves 1 byte over the naive method by utilizing dylnan's parity trick
Saved 3 bytes thanks to Mr. Xcoder
þDÁ€ÉÏSO·

Try it online!
Explanation
þ              # push only digits of input
 D             # duplicate
  Á            # rotate right
   €É          # get the parity of each
     Ï         # keep only true items
      SO       # calculate digit-sum
        ·      # double

Hmm, would þÀIþ€ÉÏSO·, þÀDÁ€ÉÏSO·, þÀ¹þ€ÉÏSO· or þÀsþ€ÉÏSO· pass all test cases for -2 bytes?

@Mr.Xcoder: Ah, yes. Nice! We can even do þDÁ€ÉÏSO· for -3 :)

Perl 6, 41 bytes
{2*sum rotate($!=.comb(/\d/))Z*(@$! X%2)}

Try it online!
Uses the same logic as dylnan's Jelly answer. This sums only digits that follow an odd number and then multiplies by 2.

MATL, 18  17 bytes
t4Y2m)!Ut1YSof)sE

Try it online!
(-1 byte thanks to Luis Mendo/Giuseppe/both!)
Explanation:
     % Implicit input
 t   % duplicate input
     % stack: ['r5e6o9mm!/3708dvc' 'r5e6o9mm!/3708dvc']
 4Y2 % push inbuilt literal, characters '0':'9'
     % stack: ['r5e6o9mm!/3708dvc' 'r5e6o9mm!/3708dvc' '0123456789']
 m)  % extract only characters from input that belong to '0':'9'
     % stack: ['5693708']
 !U  % transpose and convert each value from string to number
     % stack: [5 6 9 3 7 0 8]
 t   % duplicate that
 1YS % circular shift by 1
     % stack: [[5 6 9 3 7 0 8] [8 5 6 9 3 7 0]]
 o   % parity check - 1 for odd, 0 for even
     % stack: [[5 6 9 3 7 0 8] [0 1 0 1 1 1 0]]
 f   % find non-zero value indices in last array
     % stack: [[5 6 9 3 7 0 8] [2 4 5 6]]
 )   % index at those places in the first array
 s   % sum
 E   % multiply by 2
     % (implicit) convert to string and display

The basic idea is that numbers that follow even numbers can be ignored, while those that follow odd numbers are doubled - and the final result is the sum of those doubled values.
I didn't think f after the parity check o would be necessary, but for some reason MATL doesn't see the array of 0's and 1's that result from the o as a logical array, instead takes them as numerical indices and indexes into positions 1 and end.

I think you can use !U instead of 48-. The transpose doesn't seem to do any harm here. o for double input is just mod(...,2),  so the output is double. Nice NaN input trick! If that's meant to solve the extraneous output in STDOUT, Dennis had an idea and will probably fix that soon

!U instead of 48-

@LuisMendo welp, you beat me to the punch!

@Giuseppe :-D :-D

Thank you both, edited. @LuisMendo When does o give a logical array output then - or does it not? (I must confess I've never really looked into MATLAB's numeric type system.) And yeah, I thought NaN would make for a nice sentinel since it's unlikely to be actual input anywhere, but good to know it won't be needed for much longer!

Yes, o always gives double output (unless I am missing some edge case)

@sundar Dennis already deployed the fix, so NaN won't be needed anymore

Powershell, 80 78 76 bytes
($d="$args"-split'\D*'-ne'')+$d[0]|?{$p-match'[13579]';$p=$_}|%{$s+=2*$_};$s

-2 bytes thanks Neil with Retina solution
-2 bytes thanks AdmBorkBork
Test script:
$f = {
($d="$args"-split'\D*'-ne'')+$d[0]|?{$p-match'[13579]';$p=$_}|%{$s+=2*$_};$s
}

&$f 'r5e6o9mm!/3708dvc'

Explanation
First of all: it sould add 2*n if previous digit is odd, and 0 if a previous digit is even.
($d="$args"-split'\D*'-ne'')+ # let $d is array contains digits only, each element is a digit
$d[0]|                        # apend first digit to the end of the array
?{                            # where for each digit
    $p-match'[13579]'         # predicate is 'previous digit is odd' (it is false on the first iteration because $p is null)
    $p=$_                     # let previous digit is current
}|
%{                            # for each digit matched to the predicate
    $s+=2*$_                  # add current digit multiply 2 to $s.
}
$s                            # return sum

Extra, 99 bytes
Inspired by @Neil. Regex match digits with 'previous digit is odd' only. Matches is an automatic variable.
param($d)$d+($d-match'\d')+$Matches[0]|sls '(?<=[13579]\D*)\d'-a|%{$_.Matches.Value|%{$s+=2*$_}};$s

Save a byte swapping |?{$_} for -ne''and another by moving $d="$args"-split'\D*'-ne'' into parens like ($d="$args"-split'\D*'-ne'')+$d[0].

K (ngn/k), 33 bytes
{+/(1_x,*x)*2*2!x:-48+x^x^,/$!10}

Try it online!
{ } is a function with argument x
!10 is the list 0 1 ... 9
$ convert to strings
,/ concatenate
x^ means x without what's on the right
x^x^ means x intersected with what's on the right, i.e. keep only the digits from x
-48+ subtract 48, which is the ASCII code of "0"
x: assign to x
2! mod 2
2* multiplied by 2
1_x,*x is one drop of: x followed by the first of x; i.e. x rotated to the left by one step
+/ sum

Japt (v2.0a0), 25 19 bytes
-6 bytes thanks to Shaggy.
kè\D
íÈ°*2*Y°u}Ué)x

Try it here.
It works with no digits this time! Input is a list of characters.

19 bytes, including switching to Japt v2. Not happy with the array in the xfunction, though. Ping me in chat if you've any questions.

Wait, just noticed that this won't work at all if the input doesn't contain any digits.

Also, where's the source for v2.0a0, @Shaggy? I can't find it in the repo.

This is v1 and this is v2.

In case you missed it in chat, I got this down to 12 bytes for you.

Ah, nuts! Just realised that that one will fail if there's only 1 digit in the input. There's a 16 byte version in chat, though, that does work under all conditions.

Retina, 37 bytes
(\d).*
$&$1
L$`(?<=[13579]\D*).
2**
_

Try it online! Explanation:
(\d).*
$&$1

Append a duplicate of the first digit.
L$`(?<=[13579]\D*).

Match anything whose first previous digit is odd.
2**

Convert all the matches to unary and double them. (Non-digits are treated as zero.)
_

Take the sum. If there were no matches, then this produces zero as required.
The best I could do in Retina 0.8.2 was 44 bytes:
[^\d]

(.).*
$&$1
(?<![13579]).

.
$*
.
..
.

Try it online! Explanation:
[^\d]

Delete non-digits.
(.).*
$&$1

Append a copy of the first digit.
(?<![13579]).

Delete digits that do not follow an odd digit.
.
$*

Convert to unary.
.
..

Double them.
.

Take the sum.

I'm afraid the result will be incorrect if the last digit is not odd

@mazzy When you say the last digit, do you mean before or after copying the first digit to the end?

'to the end'. the step 'Append a duplicate of the first digit' is copying to the end? ok. cool. Thanks

JavaScript (ES6), 56 bytes
Takes input as an array of characters.
s=>s.map(c=>1/c?r+=p*(p=c*2&2,n=n||c,c):0,n=p=r=0)|r+p*n

Try it online!
Commented
s =>                     // given the input array s[]
  s.map(c =>             // for each character c in s[]:
    1 / c ?              //   if c is a digit:
      r +=               //     update r:
        p * (            //       p = either 0 or 2 (always 0 on the 1st iteration)
          p = c * 2 & 2, //       p = 0 if c is even, 2 if c is odd
          n = n || c,    //       if n is still equal to 0 (as an integer), set it to c
          c              //       compute p * c
        )                //     add the result to r
    :                    //   else:
      0,                 //     do nothing
    n = p = r = 0        //   n = first digit, p = previous digit, r = result
  )                      // end of map()
  | r + p * n            // compute the last operation with the 1st digit and add it to r

R, 58 bytes
function(x,y=strtoi(x[x%in%0:9]))sum(c(y[-1],y[1])*y%%2*2)

Try it online!

using dylnan's parity trick
-8 bytes accepting vector of characters instead of strings
-3 byte thanks to @Giuseppe

67 bytes if you don't mind array output.

hmm actually you can't use the dot product because of the empty array in xxx so it's 68 bytes by using the change in indexing a to generate y.

@Giuseppe: modified, thanks :)

@Giuseppe: I ask your opinion you since you're a wiser code-golfer... from comments it seems we can use a vector of characters, in this case 61 bytes are possible : Try it online! what do you think ?

use strtoi instead of as.double, but yeah, that should be fine.

Jelly, 15 bytes
fØDV€1ịṭƊ+_Ḃ?ƝS

Try it online!

I hope you don't mind if I borrow 1ịṭƊ

JavaScript (Node.js), 85 84 83 82 bytes
-1 bytes thanks to ovs
s=>(s.match(/\d/g)||[]).reduce((r,n,i,a)=>r+(+n)+a[a[++i]!=null?i:0]*-(1-n%2*2),0)

Try it online!
Takes the string input, finds the digits as an array of characters or returns empty array if none found, and then uses type coercion to ensure the values are added/subtracted correctly. The forward lookup preincrements the index and uses a null check for brevity, and then the final part checks whether number is odd or even to then force addition or subtraction ( + and - is -, etc)

n-0 can be +n

Welcome to PPCG!

Julia 0.6, 77 69 bytes
s->(s=s.-'0';s=s[0.<=s.<=9];endof(s)>0?sum(2(s%2).*[s[2:end];s[]]):0)

Try it online!

Perl 5, 48 bytes
$;=$;[++$-%@;],$\+=$_%2?$_+$;:$_-$;for@;=/\d/g}{

Try it online!
I quite like how cryptic this looks, but it's a pretty straightforward loop around all the numbers in the string.

C Sharp 180 bytes
This isn't very good golfing, lol.
s=>{var q=new Queue<int>(s.Where(Char.IsNumber).Select(n=>n-48));q.Enqueue(q.First());int t,o=0;o=q.Dequeue();try{while(true){t+=o+(o%2==0?-1:1)*(o=q.Dequeue());}}catch{return t;}}

Ungolfed :
var q = new Queue<int>(s.Where(Char.IsNumber).Select(n=>n-48));
int t,o=0;

q.Enqueue(q.First());
o=q.Dequeue();

try{
    while(true){
        t += o + (o%2==0?-1:1) * (o=q.Dequeue());
    }
}
catch {
    return t;
}

Stax, 14 bytes
ÿ←«4é■≥B▬ê→█T♥

Run and debug it
Unpacked, ungolfed, and commented, it looks like this.
Vd|&    filter out non-digits
c|(\    zip into pairs after rotating right
F       for each digit pair
  B2%s  first-of-pair % 2, then swap top two stack elements
  eH*   eval digit as integer, double, then multiply
  +     add to running total

Run this one

JavaScript (ES6), 52 bytes
s=>s.filter(t=>1/t&&~(a+=u*t,u=t%2),a=u=0)[0]*u+a<<1

Expects input as an array of characters.
Caveat: Due to use of bit-shifting, the output has an upper bound of 2^31-1
Try it online!
Explanation
Essentially doubles the sum of the digits following odd values.
s => s.filter(             // filter to preserve the first digit
    t =>
        1/t &&             // short-circuits if NaN
        ~(                 // coerce to truthy value
            a += u * t,    // adds value only if previous digit is odd
            u = t%2        // store parity of current digit
        ),
    a = u = 0
)[0]                       // first digit
* u + a
<< 1                       // bit-shift to multiply by 2 (also coerces a NaN resulting from a string devoid of digits to 0)


text:
Find The Sum of the First n Bouncy Numbers
Terminology
An increasing number is one where each digit is greater than or equal to all the digits to the left of it (ex. 12239)
A decreasing number is one where each digit is less than or equal to all the digits to the left of it (ex. 95531)
A bouncy number is any number that is not increasing or decreasing. Since this requires at least 3 digits, the first bouncy number is 101
The task
Given an integer n greater than or equal to 1, find the sum of the first n bouncy numbers
Rules

This is code golf, so the answer with the shortest amount of bytes wins
If your language has limits on integer size (ex. 2^32-1) n will be small enough that the sum will fit in the integer
Input can be any reasonable form (stdin, file, command line parameter, integer, string, etc)
Output can be any reasonable form (stdout, file, graphical user element that displays the number, etc)

Test cases
1 > 101
10 > 1065
44701 > 1096472981

I'm not sure I understand your Restrictions. Can I sort the numbers and check if they're the same as the original number? That's using a built-in (sort), but it's not strictly a built-in to check if it's increasing. Check out Non-observable program requirements and Do X without Y on our "Things to avoid" Meta post.

Hi, Welcome to PPCG! While this is a nice first post (+1), I have some small suggestions: No builtins that check if a number is increasing may be used, No builtins that check if a string is lexicographically increasing may be used (disallowing built-ins) is a thing to avoid when writing challenges; we have a Sandbox for Proposed challenges, where you can share your post idea before submission in order to receive feedback and guidance :)

I updated the restrictions to better match the "Exceptions" category of the link you posted

I still do not see the point of having such a restriction in the first place. Of course, it is up to you whether to keep it or not, but forbidding built-ins is typically bad practice. If you feel like the challenge is trivialised by built-ins, you should note that simply restricting them doesn't make solving the task more interesting, but rather adds boilerplate. Could you consider removing that restriction? (by the way, this still falls under Do X without Y) Otherwise, I like the idea quite a lot, and I wouldn't want a slightly subjective restriction to detract from the actual task.

Maybe this is not a sentiment commonly shared on this forum, but I personally think it is much more interesting to come up with a concise algorithm for determining if a number is bouncy (like what ngn did) than the equivalent of .toString().sorted() and .toString().reverse().sorted(). And as for why it is the sum of the first n numbers instead of just "is a number bouncy?" (which is probably what adds "boilerplate" more than anything), there are some runtime optimisations one can make when you sum more than one (although maybe not golfing optimisations)

I have however removed the restriction, as it is clear that it is more enjoyable for the community that way, and will trust the guidelines and best practices here that ensure challenges are of the best quality

This challenge is non-trivial enough that you don't need to ban built-ins. When they're too easy that you need to ban built-ins, chances are it's not very good.

More test cases would be good to have, especially since the jump from the second to the third case is so large.

Jelly, 10 8 bytes
ṢeṚƬ¬µ#S

Try it online!
How it works
ṢeṚƬ¬µ#S  Main link. No arguments.

      #   Read an integer n from STDIN and call the chain to the left with argument
          k = 0, 1, 2, ... until n of them return a truthy result.
          Yield the array of successful values of k.
     µ    Monadic chain. Argument: k (integer)
Ṣ           Sort, after promoting k to its digit array.
  ṚƬ        Reverse 'til the results are no longer unique and yield unique results.
            Calling Ṛ on k promotes it to its digit array. If k = 14235, the
            result is [14235, [5,3,2,4,1], [1,4,2,3,5]].
 e          Check if the result to the left appears in the result to the right.
    ¬       Negate the resulting Boolean.
       S  Take the sum.

+1 ṚƬ is extremely neat...

Pyth, 10 bytes
s.f!SI#_B`

Try it here!
How it works?

s.f!SI#_B` – Full program. Takes an integer Q from STDIN and outputs to STDOUT.
 .f        – Find the first Q positive integers that satisfy a certain condition.
   !SI#_B  – The condition. Returns true for bouncy numbers only.
       _B` – Cast the number to a string and bifurcate (pair) it with its reverse.
      #    – Filter-keep those...
     I     – That are invariant under...
    S      – Sorting.
           – To clarify, I (invariant) is a Pyth operator that takes two inputs, a
             function and a value and checks whether function(value) == value, so
             this is technically not a built-in.
   !       – Logical not. The empty list gets mapped to true, other values to false.
s          – Sum.

K (ngn/k), 37 bytes
{+/x{{(a~&\a)|a~|\a:10\x}(1+)/x+1}\0}

Try it online!
{ } is a function with argument x
x{ }\0 applies the {} on 0 x times, preserving the intermediate results
(1+) is the successor function
{ }(1+)/x+1 applies the successor function starting from x+1 until the {} returns true
10\x are the decimal digits of x
a: assign to a
|\ is the max-scan (partial maxima) of a
&\ analogously, is the min-scan
a~|\a does a match its max-scan?
| or
a~&\a its min-scan?
+/ sum

JavaScript (ES6), 77 bytes
f=(i,n=0,k,p)=>i&&([...n+''].map(x=>k|=x<p|2*(p<(p=x)))|k>2&&i--&&n)+f(i,n+1)

Try it online!
Commented
f = (                     // f = recursive function taking:
  i,                      //   i = number of bouncy numbers to find
  n = 0,                  //   n = current value
  k,                      //   k = bitmask to flag increasing/decreasing sequences
  p                       //   p = previous value while iterating over the digits
) =>                      //
  i && (                  // if there's still at least one number to find:
    [...n + '']           //   turn n into a string and split it
    .map(x =>             //   for each digit x in n:
      k |=                //     update k:
        x < p |           //       set bit #0 if x is less than the previous digit
        2 * (p < (p = x)) //       set bit #1 if x is greater than the previous digit
                          //       and update p
    )                     //   end of map()
    | k > 2               //   if both bits are set (n is bouncy):
    && i--                //     decrement i
    && n                  //     and add n to the total
  ) + f(i, n + 1)         //   add the result of a recursive call with n + 1

Python 2, 84 bytes
i=s=0
n=input()
while n:b=`i`>`sorted(`i`)`[2::5]<`i`[::-1];n-=b;s+=b*i;i+=1
print s

Try it online! Or see a test-suite.

Python 2, 110 92 89 bytes
n=input()
x=s=0
while n:b={-1,1}<=set(map(cmp,`x`[:-1],`x`[1:]));s+=x*b;n-=b;x+=1
print s

Try it online
This function determines if a number is bouncy:
lambda x:{-1,1}<=set(map(cmp,`x`[:-1],`x`[1:]))

You can compare characters directly. In fact, your set comprehension can become set(map(cmp,\x`[:-1],`x`[1:]))`.

@Jakob Thanks. I always forget you can use map that way.

x=s=0\nwhile n:b={-1,1}<=set(map(cmp,`x`[:-1],`x`[1:]));s+=x*b;n-=b;x+=1 saves 3 bytes

Retina, 93 bytes
K`:
"$+"{/(?=.*;(_*);\1_)(?=.*_(_*);\2;)/^{`:(#*).*
:$1#;$.($1#
)`\d
*_;
)`:(#+).*
$1:$1
\G#

Try it online! Explanation:
K`:

Initialise s=i=0. (s is the number of #s before the :, i the number of #s after.)
"$+"{
...
)`

Repeat n times.
/(?=.*;(_*);\1_)(?=.*_(_*);\2;)/^{`
...
)`

Repeat while i is not bouncy.
:(#*).*
:$1#;$.($1#

Increment i and make a copy in decimal.
\d
*_;

Convert the digits of the copy to unary. The bounciness test uses the unary copy, so it only works once i has been incremented at least once.
:(#+).*
$1:$1

Add i to s and delete the copy of the unary digits, so that for the next pass of the inner loop the bounciness test fails and i gets incremented at least once.
\G#

Convert s to decimal.
121 byte version calculates in decimal, so might work for larger values of n:
K`0:0
"$+"{/(?=.*;(_*);\1_)(?=.*_(_*);\2;)/^{`:(\d+).*
:$.($1*__);$.($1*__)
)+`;\d
;$&*_;
)`\d+:(\d+).*
$.(*_$1*):$1
:.*

Try it online! Explanation:
K`0:0

Initialise s=i=0.
"$+"{
...
)`

Repeat n times.
/(?=.*;(_*);\1_)(?=.*_(_*);\2;)/^{`
...
)

Repeat while i is not bouncy.
:(\d+).*
:$.($1*__);$.($1*__)

Increment i and make a copy.
+`;\d
;$&*_;

Convert the digits of the copy to unary. The bounciness test uses the unary copy, so it only works once i has been incremented at least once.
\d+:(\d+).*
$.(*_$1*):$1

Add i to s and delete the copy of the unary digits, so that for the next pass of the inner loop the bounciness test fails and i gets incremented at least once.
:.*

Delete i.

05AB1E, 12 bytes
µN{Â‚Nå_iNO¼

Try it online!
Explanation
µ              # loop over increasing N until counter equals input
     Nå_i      # if N is not in
 N{Â‚          # the pair of N sorted and N sorted and reversed
         NO    # sum N with the rest of the stack
           ¼   # and increment the counter

Java 8, 114 112 bytes
n->{int i=0,s=0;for(;n>0;++i)s+=(""+i).matches("0*1*2*3*4*5*6*7*8*9*|9*8*7*6*5*4*3*2*1*0*")?0:--n*0+i;return s;}

Uses a regular expression to check if the number is increasing or decreasing. Try it online here.
Ungolfed:
n -> { // lambda
    int i = 0, // the next number to check for bounciness
        s = 0; // the sum of all bouncy numbers so far
    for(; n > 0; ++i) // iterate until we have summed n bouncy numbers, check a new number each iteration
        s += ("" + i) // convert to a String
             .matches("0*1*2*3*4*5*6*7*8*9*" // if it's not an increasing  number ...
             + "|9*8*7*6*5*4*3*2*1*0*") ? 0 // ... and it's not a decreasing number ...
             : --n*0 // ... we have found another bouncy number ...
               + i; // ... add it to the total.
    return s; // return the sum
}

Python 2, 250 bytes
n=input()
a=0
b=0
s=0
while a<n:
    v=str(b)
    h=len(v)
    g=[int(v[f])-int(v[0]) for f in range(1,h) if v[f]>=v[f-1]]
    d=[int(v[f])-int(v[0]) for f in range(1,h) if v[f]<=v[f-1]]
    if len(g)!=h-1 and len(d)!=h-1:
       a+=1
       s+=b
    b+=1
print s

Welcome! You may wish to view this page for Tips for Golfing in Python

I suggest using ; to put as many statements on a single line as possible, removing whitespace, and defining a function for the 2 long lines that are very similar, so you can reuse some of the code. Also, you can do a=b=s=0 and len(g)!=h-1!=len(d).

Thanks for the tips. I've got to go now. but I'll work on it later.

Nibbles, 9 bytes
+<$|,~~?`.`<;`p$\

(it would be 8.5 bytes if filesystems could store half bytes)
Similar to the Jelly answer.
+                # sum of
 <               # first n elements of
  $              # first input integer
   |  ~          # filter.not
    ,~           # range from 1 to infinity
       ?         # index of (begin of filter body)
        `.       # iterate while uniq
        `<       # sort
          ;`p$   # int to str of filter arg, also save value
              \  # reverse
                 # implicit $ (arg of iterate while uniq)
                 # implicit $ (saved value from `p)

Fractional byte counts aren't allowed, since files with fractional byte counts can't be stored on most machines. How would Nibbles' interpreter take this as input? I'd imagine it's something like a 9-byte file with padding, in which case that would be the score. (By the eay this looks like a super cool language!)

Thanks! yes, it would be need stored as 9 bytes on most computers. But if that wasn't a restriction it could be stored as 8.5 bytes. I think it is somehow worth indicating that this is "better" than a 9 byte solution though as it is "17 nibbles" which is better than "18 nibbles".

Stax, 14 bytes
Ö²àDæ▲☼Ty≡°lû↕

Run and debug it

Vyxal, 7 bytes
fÞȮ¬)ȯ∑

Try it Online!
      ∑ # Sum of...
     ȯ  # First n integers...
----)   # Where...
f       # Digits
   ¬    # Are not
 ÞȮ     # Sorted

Red, 108 bytes
func[n][i: s: 0 until[t: form i
if(t > u: sort copy t)and(t < reverse u)[s: s + i n: n - 1]i: i + 1
0 = n]s]

Try it online!
More readable:
f: func [ n ] [
    i: s: 0
    until [
       t: form i
       if ( t > u: sort copy t ) and ( t < reverse u ) [
            s: s + i
            n: n - 1
       ]
       i: i + 1
       0 = n
    ]
    s
]

A good opportunity to use form - form i is 5 bytes shorter than to-string i

R, 96 bytes
function(n){while(n){y=diff(T%/%10^(0:log10(T))%%10);g=any(y<0)&any(y>0);F=F+T*g;n=n-g;T=T+1};F}

Try it online!
Explanation :
while(n){                         # while n > 0

        T%/%10^(0:log10(T))%%10   # split T into digits(T==TRUE==1 at the 1st loop)
y=diff(                         ) # compute the diff of digits i.e. digits[i] - digits[i+1]

g=any(y<0)&any(y>0)               # if at least one of the diff is < 0 and
                                  # at least one is > 0 then T is "bouncy"

F=F+T*g                           # if bouncy increment F (F==FALSE==0 at the 1st loop)

n=n-g                             # decrement n by 1 if bouncy

T=T+1}                            # increment T by 1 and loop

F}                                # return F

MATL, 31 30 bytes
l9`tVdZS&*0<a?wQtG>?.]y]QT]xvs

Try it online!
l       % Initialize counter to 1
9       % First value to check for being bouncy
`       % Start do-while loop
  tV    % duplicate the current number and convert to string
        % (let's use the iteration where the number is 1411)
        % stack: [1, 1411, '1411']
  d     % compute differences between the characters
        %  For non-bouncy numbers, this would be either all
        %  positive values and 0, or all negative values and 0
        % stack: [1, 1411, [3 -3 0]]
  ZS    % keep only the signs of those differences
        % stack: [1, 1411, [1 -1 0]]
  &*    % multiply that array by its own transpose, so that
        %  each value is multiplied by every other value
        %  for non-bouncy numbers, all products will be >=0
        %  since it would have had only all -1s or all 1 (other than 0s)
        % stack: [1, 1411, [1 -1  0
                            -1  1 0
                            0  0  0]]
  0<a?  % if any value in the matrix is less than 0
    wQ    % switch the counter to top, increment it
          % stack: [1411, 2]
    tG>?  % duplicate it, check if it's gotten greater than the input limit
      .]    % if so, break out of loop
  y]    % else, duplicate bouncy number from inside stack,
        %  keeping a copy to be used for summing later
        % stack: [1411, 2, 1411]
  QT    % increment number, push True to continue loop
]     % loop end marker
x     % if we've broken out of loop, remove counter from stack
v     % concatenate the bouncy numbers we've collected in stack and
s     % sum them

Ruby (123 106 bytes)
o=0
x=[?0]
(z=(x=(x.join.to_i+1).to_s.chars).sort)!=x&&z!=x.reverse ? (n-=1;o+=x.join.to_i):1while n>0
p o

Looks pretty ugly to me. Bounciness is defined in this block x.sort!=x&&x.sort!=x.reverse

C (gcc), 104 bytes
f(b,o,u,n,c,y){for(o=u=0;b;u+=y?0:o+0*--b,++o)for(n=o,y=3;n/10;)c=n%10,n/=10,y&=(c-=n%10)<0?:c?2:y;b=u;}

Try it online here.
Ungolfed:
f(n, // function: return type and type of arguments defaults to int;
     // abusing extra arguments to declare variables
  i,   // number currently being checked for bounciness
  s,   // sum of the bouncy numbers
  j,   // copy of i to be used for checking bounciness in a loop
  p,   // used for investigating the last digit of j
  b) { // whether i is not bouncy; uses the two least significant bits to indicate increasing/decreasing
    for(i = s = 0; // check numbers from zero up; initial sum is zero
        n; // continue until we have n bouncy numbers
        s += b ? 0 // not bouncy, no change to the sum
        : i + 0* --n, // bouncy, add it to the sum and one less bouncy number to go
        ++i) // either way, move to the next number
        for(j = i, b = 3; j/10; ) // make a copy of the current number, and truncate it from the right until there is just one digit left
        // bounciness starts as 0b11, meaning both increasing and decreasing; a value of 0 means bouncy
            p = j % 10, // get the last digit
            j /= 10, // truncate one digit from the right
            b &= // adjust bounciness:
                 (p -= j % 10) // compare current digit to the next
                 < 0 ? // not an increasing number, clear second to least significant bit
                 : p ? 2 // not a decreasing number, clear least significant bit
                 : b; // keep it the same
    n = s; // gcc shortcut for return s
}

Suggest u+=!y?--b,o:0,++o instead of u+=y?0:o+0*--b,++o, ;y&=(c-=n%10)<0?:c?2:y)c=n%10,n/=10; instead of ;)c=n%10,n/=10,y&=(c-=n%10)<0?:c?2:y;

Ruby, 76 bytes
->n,s=i=0{[d=(i+=1).digits,d.reverse].index(d.sort)||(s+=i;n-=1);n<1?s:redo}

Try it online!