# Question
Title: Does this line pass through that square?
Divide the first quadrant (including the positive x-axis, the positive y-axis, and the origin) into 1x1 grids, with each grid labelled by the coordinates of its bottom-left corner, as demonstrated below:

Note that each grid contains its boundaries and its vertices. Using mathematical symbols, the grid labelled (m,n) would represent the square `{(x,y) | m ≤ x ≤ m+1, n ≤ y ≤ n+1}`.

---

Given a straight line in the form of `ax+by+c=0` with integers `a`, `b`, and `c`, and a grid represented by `(m,n)`, output whether the line passes through the grid, i.e. whether any point in the given grid is on the line.

---

```
a  b  c m n output
1  1  0 0 0 true
1  1  0 1 1 false
1  1  0 0 2 false
1  1 -3 0 1 true
1  1 -3 0 0 false
2 -1  0 1 1 true
2 -1  0 1 0 false
2 -1  0 0 2 true
2 -1  0 0 1 true
2 -1  0 1 2 true
2  0 -1 0 0 true
2  0 -1 0 1 true
2  0 -1 0 2 true
2  0 -1 1 0 false
2  0 -1 1 1 false
0  2 -1 0 0 true
0  2 -1 1 0 true
0  2 -1 2 0 true
0  2 -1 0 1 false
0  2 -1 1 1 false
1  0 -1 0 0 true
1  0 -1 0 1 true
1  0 -1 0 2 true
1  0 -1 1 0 true
1  0 -1 1 1 true

```

Please suggest more testcases in the comments.

---

This is . Shortest answer in bytes wins. Standard loopholes apply.

# Answer
# Python 3, 84 66 bytes

First golf, first fail (maybe).

Thanks to Rod for shaving off 18 bytes by using a function instead of direct input.

```
def f(a,b,c,m,n):f=-(a*m+c)/b;g=f-a/b;print(min(f,g)<=n<=max(f,g))

```

Try it online!

**Explanation:**

Basically we calculate the value of the line function for m and m+1, if n is inbetween the values, then the list must pass through it at some point. Would be much better if the language had some simpler way to input multiple integers.
> 5 votes

# Answer
# Jelly, 10 bytes

```
ż‘{Œpæ.ṠE¬

```

Try it online!

### Background

Like other answers before mine, this relies on the fact that a straight line divides the plane into two semi-planes. The rectangle is either contained in one of these semi-planes (no intersection with the line) or intersects both semiplanes (and thus the line that separates them.

### How it works

```
ż‘{Œpæ.ṠE¬  Main link. Left argument: [m, n]. Right argument: [a, b, c]

 ‘{         Increment left; yield [m+1, n+1].
ż           Zipwith; yield [[m, m+1], [n, n+1]].
   Œp       Cartesian product; yield [[m, n], [m, n+1], [m+1, n], [m+1, n+1]].
     æ.     Take the dot products with [a, b, c], mapping each [x, y] to ax+by+c.
       Ṡ    Take the signs.
        E   Test the signs for equality.
         ¬  Logical NOT.

```
> 5 votes

# Answer
# Python 2, 59 bytes

```
lambda a,b,c,m,n:min(0,a,b,a+b)<=-a*m-b*n-c<=max(0,a,b,a+b)

```

Try it online!

We can tell which side of the line a point is by the sign of `a*x+b*y+c`. The line passes through the square (counting touching) unless all four vertices `(m,n),(m,n+1),(m+1,n),(m+1,n+1)` are strictly on the same side of the line. We can plug these values in an extract out the constant `a*m+b*n+c` that appears in all four:

```
a*m+b*n+c
a*m+b*n+c+a
a*m+b*n+c+b
a*m+b*n+c+a+b

```

So, the line passes through the square unless these four values are all positive or all negative. So, it suffices for their minimum to be `<=0` and maximum to be `>=0`.

```
min(a*m+b*n+c,a*m+b*n+c+a,a*m+b*n+c+b,a*m+b*n+c+a+b)<=0<=max(a*m+b*n+c,a*m+b*n+c+a,a*m+b*n+c+b,a*m+b*n+c+a+b)

```

Subtracting the common `a*m+b*n+c` from each part gives the code.

A slightly longer approach is to check whether the set of signs (+,0,-) has length at least 2.

**Python 2, 62 bytes**

```
lambda a,b,c,m,n:len({cmp(a*m+b*n+c,-d)for d in(0,a,b,a+b)})>1

```

Try it online!
> 4 votes

# Answer
# Mathematica, ~~60~~ 55 bytes

```
Solve[m#+n#2==-#3&&#4<=m<=#4+1&&#5<=n<=#5+1,{m,n}]!={}&

```

*-5 bytes thanx to @MartinEnder*

input form

> \[a,b,c,m,n\]
> 3 votes

# Answer
## Batch, 66 bytes

```
@cmd/cset/a"q=%1*%4+%2*%5+%3,((-(q+%1)*(q+%2)&-q*(q+%1+%2))>>31)+1

```

Explanation: We consider the values taken by the equation at the four corners of the cell. If the line does not intersect the cell, then all four values have the same sign, but if it does intersect the cell, then at least one value will be zero or the opposite sign. The comparison is simplified by multiplying pairs of opposite corners, then if both values are positive then the line does not intersect the cell. Some bit-twiddling then converts the multiplications into an overall result.
> 3 votes

# Answer
# Python, 54 bytes

```
lambda a,b,c,m,n:abs(2*(a*m+b*n+c)+a+b)<=abs(a)+abs(b)

```

Try it online!

(Thanks to xnor for the testing script.)

### How it works

The line goes through *m* \+ 1/2 + *x*, *n* \+ 1/2 + *y* if and only if

*a*⋅(*m* \+ 1/2 + *x*) + *b*⋅(*n* \+ 1/2 + *y*) + *c* = 0
⇔ 2⋅(*a**m* \+ *b**n* \+ *c*) + *a* \+ *b* = −2⋅*a**x* − 2⋅*b**y*.

This is possible for some |*x*|, |*y*| ≤ 1/2 if and only if |2⋅(*a**m* \+ *b**n* \+ *c*) + *a* \+ *b*| ≤ |*a*| + |*b*|.
> 2 votes

# Answer
# Java (OpenJDK 8), 71 bytes

```
(a,b,c,x,y)->(0<a?0:a)+(0<b?0:b)<=(x=-a*x-b*y-c)&x<=(0>a?0:a)+(0>b?0:b)

```

Try it online!

Port of xnor's Python solution.

### Original solution, using Java's shape/line intersection built-in (108 bytes)

```
(a,b,c,x,y)->b==0?x<=-c/a&-c/a<=x+1:new java.awt.Rectangle(x,y,1,1).intersectsLine(x,c=(c+a*x)/-b,x+1,c-a/b)

```

Try it online!

## Credits
> 1 votes

# Answer
## Mathematica, 50 bytes

```
-4<Tr@Sign[Tuples@{{#,#+1},{#2,#2+1}}.{##4}+#3]<4&

```

Try it online!

Takes `m, n, c, a, b` as input in that order.

Explanation: `Tuples@{{#,#+1},{#2,#2+1}}` makes a list of the coordinates of the four corners of the square, then taking the dot product with `.{##4}` (which means `{#4, #5}`) and adding `+#3` computes `ax + by + c` for `x,y` at each corner. If the line passes through the point, this is zero; if the line is further from the origin, it's negative; and if the line is nearer to the origin, it's positive — therefore we check the `Sign`s of these four values. The line passes outside the square if and only if all four values are 1 or all four are -1, so we check that their sum is strictly between -4 and 4.

(This answer is vaguely inspired by my answer to this question.)
> 1 votes

# Answer
## Python 2, 147 110 bytes

```
def f(a,b,c,m,n):
 if b:d=sorted((-a*x-c)/float(b)for x in(m,m+1));return d[0]-1<=n<=d[1]
 return m<=-c/a<=m+1

```

And a *huge* thanks to Leaky Nun!

TIO.
> 1 votes

---
Tags: code-golf, geometry, decision-problem
---


title: Fix my Basic Orthography

text:
# Question
Title: Fix my Basic Orthography
# Fix my Basic Orthography

While I am excellent at following the English capitalisation rules when writing, when I am typing I have a habit a capitalising almost everything (as you will see from the titles of my challenges). I need a program to fix that, but because I use so many capitals, and capitals are big letters, your program must be as short as possible.

## Requirements

* Your program should take each word, and if it is the first alphanumeric set of characters after a full stop or the beginning of the input, capitalize the *first* letter. All the rest of the letters until the next full stop will be lowercase. At the full stop, capitalize the first letter and continue.
* Punctuation must be preserved.
* In a sentence without a full stop at the end, that should be added.
* Spaces, where missing, should be inserted. A space is 'missing' if there is nothing between a full stop and the character following it.

*(Note for americanish speakers: full stop = period = `.`)*

## Test Cases

```
tHIS SenteNce HAS veRy bAd GrammAr. ==> This sentence has very bad grammar.

-----

PuncTuation must-be PReserved. ==> Punctuation must-be preserved.

-----

full StOps ShoulD Be inserted ==> Full stops should be inserted.

-----

MultiPLe sEntEnceS Are possible. thEY Are, yoU KNOW. ==> Multiple sentences are possible. They are, you know.

-----

spaces. are.inserted. ==> Spaces. Are. Inserted.

```

## Rules

* Your program should take input as an argument or from `STDIN` (or the closest alternative in your language).
* Standard loopholes are forbidden.

## Scoring

When is the tag, it's the least bytes to win!

## Submissions

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

## Leaderboard

```
/* Configuration */

var QUESTION_ID = 79842; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push©;
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/<a/.test(lang)) lang = jQuery(lang).text();

    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
```

```
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
```

# Answer
## Pyke, 16 bytes

```
Q\.cFl8l5DI\.+(J

```

Try it here!

(15 bytes after a bugfix)

```
\.cFl8l5DI\.+(J

```

Explanation:

```
Q\.c             -  input().split(".")
    F            - for i in ^:
     l8l5        -  i = i.lstrip().capitalise()
          I      -  if i:
           \.+   -   i += "."
               J - " ".join(^)

```
> 2 votes

# Answer
# Vim, ~~40~~ 39 keystrokes

```
VgugUl:s/\. *\(\a\)/\. \U\1/g<cr>:s/\.$<cr>A.

```

This assumes that input will not take multiple lines.

Explanation:

```
Vgu                                            "Make the whole line lowercase
   gUl                                         "Make the first character uppercase
       :s/\. *\(\a\)/\. \U\1/g<cr>             "Replace a (.) followed by any number of
                                               "spaces, followed by a character, with
                                               "with a (.), one space, and that character
                                               "In lowercase
                                  :s/\.$<cr>   "Remove a dot, if it's at the end of this line
                                            A. "Add a dot to the end of this line.

```
> 4 votes

# Answer
## JavaScript (ES6), ~~76~~ 95 bytes

```
f=
s=>s.replace(/ +/g,' ').replace(/(\w)([^.]*)\.?/g,(_,c,r)=>c.toUpperCase()+r.toLowerCase()+'.')
```

```
input{width:100%;
```

```
<input oninput=o.value=f(this.value)><input id=o>
```
> 2 votes

# Answer
## Python 3, ~~86~~ 80 bytes

```
print('. '.join(x.strip().capitalize() for x in input().split('.') if x!='')+'.')

```

This works for all of the current test cases, but not for much beyond that.

Thanks @muddyfish for 6 bytes.

https://repl.it/CQ7h/0
> 2 votes

# Answer
# Retina, 41 bytes

```
S-`\. *
%(T`L`l
T`l`L`^.
)`(?<!\.)$
.
¶
<space>

```

Try it online!

Test suite.
> 1 votes

# Answer
# Ruby, 50 bytes

Basic split/map/join solution.

```
->s{s.split(?.).map{|e|e.strip.capitalize+?.}*' '}

```
> 1 votes

# Answer
# V, 25 bytes (non-competing)

```
guGgUló® *¨á©/® Õ±
ó®$
A.

```

Try it online!

This isn't super creative, since it's just a direct port of my vim answer. However, it's a lot shorter, so I'm happy with it.

Due to an oversight, this is one or two bytes longer than it needs to be. That should be fixed soon.
> 1 votes

# Answer
# PHP, ~~123~~ ~~103~~ ~~102~~ ~~95~~ 92 bytes

```
<?foreach(explode('.',trim(fgets(STDIN)))as$b)echo!$b?!1:ucfirst(strtolower(trim($b))).'. ';

```

Takes a newline-terminated line from STDIN and prints the fixed version to STDOUT.
> 1 votes

# Answer
# Perl, 40 + 12 (flags) = 52 bytes

```
#!perl -paF\.\s*
map{s/\s*$/. /;$\.=ucfirst lc}@F}{chop$\

```

Using:

```
echo "foo.baz. bar" | perl -paF'\.\s*' -e 'map{s/\s*$/. /;$\.=ucfirst lc}@F}{chop$\'

```

Ungolfed:

```
while (<>) {
    my @F = split(/\.\s*/, $_);
# code above added by -paF\.\s*
    # $\ has undef (or '')
    for (@F) {
        $_ =~ s/\s*$/. /;
        $\ .= ucfirst(lc($_));
    }
} {
    chop($\);
# code below added by -p
    print;  # prints $_ (undef here) and $\
}

```

Ideone.
> 0 votes

# Answer
# Lua, ~~149~~ 141 bytes

```
u=function(l)return l:upper()end print(io.read():lower():gsub("%s+"," "):gsub("%.([^%s])",". %1"):gsub("^(%w)",u):gsub("(%.[^%w]*%w)",u).."")

```

Lua lacks some common features of regular expressions, and so it had to get a little sloppier than I would have liked. I might try to fix it up later though.
> 0 votes

# Answer
## Q 78 Bytes

(76 if anonymous function)

```
f:{(". "/:{{@[(" "=*x)_x;0;"c"$-32+"i"$]}'"."\:_-1_x}x),$["."=u:*|x;u;u,"."]}

```

**Test**

```
f"tHIS SenteNce HAS veRy bAd GrammAr."                  /This sentence has very bad grammar.
f"PuncTuation must-be PReserved."                       /Punctuation must-be preserved.
f"full StOps ShoulD Be inserted"                        /Full stops should be inserted.
f"MultiPLe sEntEnceS Are possible. thEY Are, yoU KNOW." /Multiple sentences are possible. They are, you know.
f"spaces. are.inserted."                                /Spaces. Are. Inserted.

```

Q has lower and upper functions (conversion to lowercase and to uppercase), but more primitive sub-language k (concise, used in the example) only has lower (operator \_), so part of the text (12 bytes `"c"$-32+"i"$`) implements upper.

Split the original string using ". " as separator, processes each line, and join again

For each line we discard first character if is a blank (join inserts a blanck after each .), and capitalice first character.

Finally, insert a final "." if last char is not "."
> 0 votes

# Answer
# Perl 5, 42 bytes

```
say map{$_=ucfirst lc.'. '}split/\.\s*/,<>

```

Try it online!
> 0 votes

---
Tags: code-golf, word
---


title: Create a bad pixel

text:
# Question
Title: Create a bad pixel
Your task is to write a program that makes your screen appear to have a bad pixel.

You should choose exactly one pixel on the screen, and exactly one channel between red, green and blue, and make its value either always 0 or always maximum (usually 255). The values of other channels should be the same as if your program didn't run.

You can choose the pixel and channel in whatever ways, such as hardcoding it or generate it randomly on each run. But it must always be visible on fairly modern hardwares.

If the color that originally should be displayed on that pixel has changed, your program should update in less than 0.5 seconds when the system is fast enough.

You cannot make assumptions about what is currently displayed on the screen (such as a taskbar using the default theme).

Your program doesn't need to work when a screensaver, login screen, effect from a window manager, etc, are active.

Shortest code wins.

# Answer
> 21 votes
# Bash on Linux - 25 bytes of Latin-1

*+3 from @wyldstallyns* / *-2 from removing quotes* / *-1 because I forgot how this works* / *-9 from @Dennis*

```
printf ÿ>/dev/fb0;exec $0

```

Assumes that /dev/fb0 exists (it does on my Arch Linux system, and I think it should on any other Linux system). Requires root access as well. This does not work for me when X is running. On my system, this just constantly sets the blue channel of the top-left pixel to full (`ÿ` is 255).

# Answer
> 11 votes
# Visual C++, ~~102~~ ~~100~~ ~~99~~ 98 bytes

```
#include<Windows.h>
int main(){for(HDC d=GetDC(0);;Sleep(99))SetPixel(d,9,9,GetPixel(d,9,9)|255);}

```

Runs on Windows, directly using the Win32 API with Visual C++ compiler targeting the console subsystem. Uses the "screen" device context to set the red channel of the pixel at (9,9) to `0xFF`.

The sleep is necessary to allow other programs to draw in between the get/set - and 9ms was too short, leading to the pixel getting stuck1 on its initial colour.

---

1 Unfortunately, not quite the same type of stuck pixel this question is looking for...

# Answer
> 9 votes
# HolyC, 13 bytes

```
GrPlot(,9,9);

```

Puts a black dot on the persistent layer directly.

What it looks like.

# Answer
> 6 votes
# C#, ~~247~~ ~~244~~ ~~371~~ ~~366~~ ~~354~~ 352 bytes

Runs on Windows. Gets a device context for the entire screen, and repeatedly maximises the red channel at (9,9).

```
namespace System.Runtime.InteropServices{using I=IntPtr;class P{[DllImport("User32")]static extern I GetDC(I h);[DllImport("Gdi32")]static extern int GetPixel(I h,int x,int y);[DllImport("Gdi32")]static extern int SetPixel(I h,int x,int y,int c);static void Main(){for(I d=GetDC((I)0);;Threading.Thread.Sleep(99))SetPixel(d,9,9,GetPixel(d,9,9)|255);}}}

```

I originally didn't want to import `GetPixel`/`SetPixel`, but there's no particularly easy way to read a single pixel off a `Graphic`. So right now this is effectively the same as my VC++ attempt. Maybe saving to bitmap will be shorter...

---

-5 bytes thanks to @TuukkaX

# Answer
> 3 votes
# SmileBASIC, 20 bytes

```
SPSET.,299,99,1,1,33

```

Updates constantly.
Sets sprite `0` to a `1`x`1` area at `299`,`99` on the sprite sheet (which is a red pixel).
`33` is the display attribute, which is `1` (display on) + `32` (additive blending).

# Answer
> 0 votes
# Java 7, 266 bytes

```
import java.awt.*;public class K extends java.applet.Applet{public static void main(String[]a){new K();}Label l=new Label(".");public K(){add(l);}public void paint(Graphics g){s(Color.red);s(Color.green);s(Color.blue);repaint();}void s(Color c){l.setForeground(c);}}

```

I ran this on windows 7. Opens a Java Applet which has a white background by default. Adds a label with a period and then changes the color of the label ad nauseum.

# Answer
> 0 votes
# Tcl/Tk, 61

```
wm at . -tr #F0F0F0
wm o . 1
grid [canvas .c]
.c cr o 9 9 9 9

```

On the image there is a black pixel near the upper left corner of the Vivaldi icon:

---

If on an interactive shell, there are abbreviations of commands available:

# Tcl/Tk, 57

```
wm at . -tr #F0F0F0
wm o . 1
gri [can .c]
.c cr o 9 9 9 9

```

There is a black pixel over the V white area of the Vivaldi icon:

---
Tags: code-golf, graphical-output
---


title: Listify a number

text:
# Question
Title: Listify a number
Given a real number, convert it to a list of lists, with the negative sign (if any) becoming an empty list, the integer part becoming a list of digits, and the fractional part (if any) becoming a list of digits. The digits must be actual numbers, not strings.

### Examples

`0``[[0]]`

`123``[[1,2,3]]`

`-123``[[],[1,2,3]]`

`123.45``[[1,2,3],[4,5]]`

`0.45``[[0],[4,5]]`

`-0.45``[[],[0],[4,5]]`

`-123.45``[[],[1,2,3],[4,5]]`

# Answer
> 7 votes
# C#, ~~60~~ 66 bytes

```
using System.Linq;s=>s.Split('-','.').Select(p=>p.Select(c=>c-48))

```

Try it online!

# Answer
> 7 votes
# JavaScript (ES6), ~~33~~ ~~44~~ ~~43~~ 41 bytes

Takes input as a string. Sacrificed ~~11~~ 10 bytes converting the elements in the output to numbers after the challenge spec was updated.

```
s=>s.split(/\D/).map(a=>[...a].map(eval))

```
* Saved a byte thanks to Arnauld's suggestion of using `eval`.

---

## Test it

```
console.log((
s=>s.split(/\D/).map(a=>[...a].map(eval))
)("-123.45"))
```

---

## Explanation

```
s=>

```

Anonymous function taking the string as an argument via parameter `s`.
`"-123.45"`

```
s.split(/\D/)

```

Use RegEx to split the string to an array on all non-digit characters - i.e., `-` and `.`
`["","123","45"]`

```
.map(a=>)

```

Map over the array, passing each string to a function via parameter `a`.

```
[...a]

```

Split to an array of individual character strings.
`[[],["1","2","3"],["4","5"]]`

```
.map(eval)

```

Map over the subarray and `eval` each string, which converts it to an integer.
`[[],[1,2,3],[4,5]]`

# Answer
> 5 votes
# Jelly,  ~~13~~  10 bytes

```
ŒṘµ<”/œpV€

```

A monadic link taking a number and returning the resulting list of lists of numbers.

**Try it online!** (the footer just prints the python representation to show all the actual lists)
...or see the test suite.

### How?

```
ŒṘµ<”/œpV€ - Link: number
ŒṘ         - Python representation (yields a string representation of the number)
  µ        - monadic chain separation (call that s)
    ”/     - literal '/' character
   <       - less than? (vectorises) ('.' and '-' are, digit characters are not)
      œp   - partition s at truthy indexes of the resulting list discarding the borders
        V€ - evaluate €ach (list of characters) as Jelly code (vectorises)

```

# Answer
> 5 votes
# Python 2, 58 bytes

```
lambda x:[map(int,i)for i in`x`.replace(*'-.').split('.')]

```

Try it online!

# Answer
> 4 votes
# 05AB1E, ~~12~~ 11 bytes

Thanks to *Riley* for saving a byte. Code:

```
'-'.:'.¡εSï

```

Uses the **05AB1E** encoding. Try it online!

Explanation:

```
'-'.:            # Replace "-" by "."
     '.¡         # Split on "."
        ε        # Apply to each element..
         S       #   Split into a list of characters
          ï      #   Convert back to int

```

# Answer
> 3 votes
# Python 2, 59 bytes

```
lambda a:[[]]*(a<0)+[map(int,n)for n in`abs(a)`.split('.')]

```

Try it online!

-5 bytes from Felipe Nardi Batista

# Answer
> 2 votes
# Actually, 23 bytes

```
'.@;)A$s⌠♂≈⌡M[[]]+@s~@t

```

Try it online!

Explanation:

```
'.@;)A$s⌠♂≈⌡M[[]]+@s~@t
'.                       push "."
  @;)                    make a copy of the input and move it to the bottom of the stack
     A$s                 absolute value of input, stringify, split on periods
        ⌠♂≈⌡M            convert integer and fractional parts to lists of digits
             [[]]+       prepend an empty list
                  @s~    bitwise negation of sign of input (1 -> -2, 0 -> -1, -1 -> 0)
                     @t  elements in the list starting at that 0-based index (drops the leading empty list if the input was positive)

```

# Answer
> 2 votes
# SOGL V0.12, 11 bytes

```
Ζ-.ŗ .Θ⌡č¹r

```

Try it Here!

Outputs to the top of the stack (because SOGL converts it to a multiline string because it is made for ascii-art). To view the result, look in the console after  ``r`@10:` (the outer brackets are the stack arrays) or just append `οø∑` after the code

```
Ζ-.ŗ         replace "-" with "."
     .Θ      split on "."s
       ⌡     for each
        č      chop into characters (casts to strings :/)
         ¹   wrap in array (this + for each is like map())
          r  reverse types, vectorizing

```

# Answer
> 2 votes
# Japt (v2.0a0), ~~12~~ ~~10~~ 8 bytes

Takes input as a string.

```
q\D ®¬®n

```

Test it (`-Q` flag for visualisation purposes only.)

* 2 bytes saved thanks to Justin.
* 2 bytes saved thanks to ETH.

---

## Explanation

Implicit input of string `U`.

```
q\D

```

Use RegEx to split (`q`) to an array on all non-digit characters.

```
®

```

Map over the array.

```
¬

```

Split each string to an array of individual characters.

```
®

```

Map over the array.

```
n

```

Convert to integer.

# Answer
> 1 votes
# Octave, 54 bytes

```
@(x)cellfun(@(c){c-48},strsplit(num2str(x),{'-' '.'}))

```

Anonymous function that takes a number as input and produces a cell array of numeric vectors.

Try it online!

### Explanation

```
@(x)cellfun(@(c){c-48},strsplit(num2str(x),{'-' '.'}))

@(x)                                                    % Function with input x
                                num2str(x)              % Convert x to string
                       strsplit(          ,{'-' '.'})   % Split at '-' or '.'. Gives a
                                                        % cell array of substrings
    cellfun(          ,                               ) % To each substring apply
                                                        % the following function
            @(c){c-48}                                  % Subtract 48 from each char
                                                        % and pack into a cell

```

# Answer
> 1 votes
# C (gcc), ~~170~~ ~~164~~ ~~152~~ ~~146~~ 144 bytes

Should be able to golf this down a bit...

```
#define P printf
#define V *v[1]
main(c,v)char**v;{for(V^45?P("[[%c",V++):P("[[],[%c",V++,V++);V;V^46?P(",%c",V++):P("],[%c",V++,V++));P("]]");}

```

Try it online!

# Answer
> 1 votes
# Jelly, 12 bytes

```
ŒṘ⁾-.yṣ”.V€€

```

Try it online!

# Answer
> 1 votes
# Actually, 16 bytes

```
$'.'-(Æ'.@s⌠♂≈⌡M

```

Try it online!

Explanation:

```
$'.'-(Æ'.@s⌠♂≈⌡M Implicit eval'd input
$                Convert to str
 '.              Push '.'
   '-            Push '-'
     (           Rotate stack left
      Æ          Pop a, b, c; push c.replace(b, a)
       '.        Push '.'
         @       Pop a, b; push b, a (swap)
          ⌠♂≈⌡   Push function ♂≈
           ♂       Map
            ≈        Convert to int
              M  Map

```

# Answer
> 1 votes
# Perl 5, 56 54 + 1 (-p) = 55 bytes

```
$_="[[$_]]";s/\D\K\./0./;s/\d(?=\d)/$&,/g;s/-|\./],[/g

```

Try it online!

*Saved two bytes due to Dom reminding me about $&*

**Explanation:**

```
$_="[[$_]]";        # Add opening and closing to ends of strings
s/\D\K\./0./;       # handle the case of .45 or -.45 by inserting 0 before
                    # the decimal.  Otherwise, .45 & 45 would be ambiguous.
s/\d(?=\d)/$&,/g;   # Put a comma between numbers.
s/-|\./],[/g        # Turn - and . into separators between lists

```

# Answer
> 1 votes
## R, ~~51~~ ~~47~~ 72 bytes

```
x=RG::s(strtoi(s(gsub('-','.',scan()),on='\\.')))
x[is.na(x)]=list(NULL)

```

I'm loving the `RG` library.

Had to add 26 bytes to make sure the empty list was actually empty.

```
               gsub('-','.',scan())             # replace - with . in input; also converts to string
             s(                    ,on='\\.')   # split string on '.'
      strtoi(                                )  # convert to numeric
RG::s(                                        ) # convert to lists of digits

    x[is.na(x)]=list(NULL)                      # converts list of `NA` to empty list

```

Example output:

```
> x=RG::s(strtoi(s(gsub('-','.',-123.45),on='\\.')))
> x[is.na(x)]=list(NULL)
> x
[[1]]
NULL

[[2]]
[1] 1 2 3

[[3]]
[1] 4 5

```

# Answer
> 1 votes
# Perl 6, 23 bytes

```
+«*.split(/\D/)».comb

```

Test it

## Expanded

```
+«\            # numify each of the following (possibly in parallel)
*\             # WhateverCode lambda (this is the input)
.split(/\D/)\  # split on non-digits ( . and - )
».comb         # split each of those into individual characters

```

Note that `…».comb` is a higher precedence than `+«…`

# Answer
> 0 votes
# Python 2, 59 bytes

```
lambda x:(x<0)*[[]]+[map(int,i)for i in`abs(x)`.split('.')]

```

Try it online!

# Answer
> 0 votes
# CJam, 13 bytes

```
r'-'.er'./::~

```

Try it online!

# Answer
> 0 votes
# Pyth, 12 bytes

```
sMMcXz\-\.\.

```

Try it here.

# Answer
> 0 votes
# Perl 6, 22 bytes

```
{m:g/^\d*|\d+/».comb}

```

Try it online!

The elements in the returned list are strings, but as is normal for Perl, they can be used as numbers and will be converted implicitly; they are "actual numbers" for all practical purposes. To force them to be numbers in their most immediate representation, one need only prefix the contents of the code block with "+«" for three more bytes.

# Answer
> 0 votes
# RUBY, 75 bytes

```
->(x){(x<0?[[]]:[])+x.abs.to_s.split('.').map{|y|y.chars.map{|z|z.to_i}}}

```

Try it online!

---
Tags: code-golf, number
---


title: Simple portmanteau with longest overlap

text:
# Question
Title: Simple portmanteau with longest overlap
I've been using a library called Djangular recently, which integrates Django and Angular.

After a while I thought 'Wouldn't it be fun to programmatically generate portmanteau?'

Here are some examples (e.g. testcases):

Django + Angular -\> Djangular
Camel + Leopard -\> Cameleopard
Spoon + Fork -\> Spoork
Ham + Hammer -\> Hammer

The general rule is to find the first common letter working backwards on first word, and working forwards on the last word. Not all portmanteau can be found this way though...

I've deliberately picked 'simple' ones to generate (for instance we're ignoring things like Zebra + Donkey = Zedonk, which is too arbitrary to generate programmatically - the correct behaviour).

Ties can be resolved eitherway - suppose you have `cart + ante` \- both `carte`, (since t is the last common letter in the first word) and `cante`, (since a is the first common letter of the last word) are value. Unfun loopholes are not allowed (including pulling 'solved' examples off wikipedia)

This is code golf, so shortest answer wins. I'll pick the winner a month from posting. Please post the output for all your code.

# Answer
# Python 3, ~~128~~ 79 bytes

Let me know if I got anything wrong and critiques are always welcome.

```
def f(a,b):
    c=len(a)-1-a[::-1].find(b[1])
    if a[-1]==b[0]:return a[:-1]+b
    if a[c]==a[c-1]:c-=1
    return a[:c]+b[1:]

```

Called with f(word 1,word 2) and returns the portmanteau. Will throw an error if the inputs aren't compatible. Works for all test cases.

Edit:

If I've read the edits to this question correctly, this updated code should work

```
f=lambda a,b:a[:-1]+b if a[-1]==b[0] else a[:len(a)-1-a[::-1].find(b[1])]+b[1:]

```
> 3 votes

# Answer
## CoffeeScript, 111 bytes/characters

Source:

```
l="toLowerCase";f=(a,b)->return a.substr(0,i)+b.substr(j)[l]()for c,j in b when(i=a[l]().lastIndexOf(c[l]()))>0

```

Try it online!

To use:

```
alert("
#{f("Django","Angular")}
#{f("Camel","Leopard")}
#{f("Spoon","Fork")}
#{f("Ham","Hammer")}
")

```

I hoped it will be shorter, but.... ok, still better than `PHP` :D

The examples result in (using the alert statement above):

```
Djangular Cameleopard Spoork Hammer

```

Explanation (Might not be valid coffescript):

```
l="toLowerCase"; # Keeps code shorter (and DRY :D )
f=(a,b)->
  return a.substr(0,i)+b.substr(j)[l]() # Return the result
     for c,j in b # Postfix for loop
       when(i=a[l]().lastIndexOf(c[l]()))>0
         # Run the return statement only when the
         # character `c` is found (also stores its last position in `i`)

```
> 2 votes

# Answer
# Haskell, 61 bytes

Doesn't handle case, but that doesn't seem to be a big deal? Tell me if it is.

```
a!b=maybe(init a!b)((a++).(`drop`b))$last a`lookup`zip b[1..]

```

Then `"Django"!"Angular"` is `"Djangular"`.
> 2 votes

# Answer
# rs, **24 bytes**

```
(.*)(.).* .*?(\2.*)/\1\3

```

To copy the initial post from @refi64 here's the live demo and all test cases. The only improvement is that you can spare the \2 back reference by including it in the third group.

I didn't want to pollute with an answer that's actually a comment, but some person on Stack Exchange decided that you can't comment when you're a newcomer and that edits should be refused, because that should obviously be a comment. Thus, sorry for that misplaced content.
> 2 votes

# Answer
# PHP (270 bytes)

```
function portmanteau($s1, $s2){ $r = ''; $y = false; foreach(str_split($s1) as $c1){ $r .= $c1; foreach(str_split($s2) as $c2){ if($y){ $r.= $c2; } if(strtolower($c1)==strtolower($c2)){ $y = true; continue; } } if($y){ break; } } if(!$y) $r .= $s2; return ucfirst($r); }

```

Ungolfed:

```
function portmanteau($str1, $str2){
    $resultingString = '';

    $letterMatched = false;
    foreach(str_split($str1) as $char){
        $resultingString .= $char;

        foreach(str_split($str2) as $char2){
            if($letterMatched){
                $resultingString.= $char2;
            }

            if(strtolower($char)==strtolower($char2)){
                $letterMatched = true;
                continue;
            }
        }
        if($letterMatched){
            break;
        }
    }
    if(!$letterMatched) $resultingString .= $str2;

    return ucfirst($resultingString);
}

```

Usage:

```
echo portmanteau('Croissant', 'Donut');

```

Tested and works with the examples in the question.
> 1 votes

# Answer
# Haskell, 148 bytes

C/case isn't restored though. Without case this was 99...

```
import Data.Char
o a b=|a==""=b|0<1=a
p""b=""
p a""=""
p a b|last a==head b=a++tail b|0<1=o(p(init a)b)(p a(tail b))
z a b=p(t a)(t b)
t=map toLower

```
> 1 votes

# Answer
## Perl, 138<br>

I'm sure someone can optimize this further
`($a,$b,$l,$r)=(@ARGV,0);for$A(split//,$a){$r.=$A;for$B(split//,$b){$r.=$B if$l;if($A=~/$B/i){$l=1;next;}}last if$l;}$r.=$b if!$l;`
138 w/ optimizations and output
`($a,$b,$l,$r)=(@ARGV,0);for$A($a=~/./g){$r.=$A;for$B($b=~/./g){$r.=$B if$l;if($A=~/$B/i){$l=1;next;}}last if$l;}$r.=$b if!$l;print"$r\n";`
> 1 votes

# Answer
# rs, 26 bytes

```
(.*)(.).* .*?\2(.*)/\1\2\3

```

Live demo and all test cases.

So far this is the shortest answer!

The underlying logic is pretty simple. It just matches greedily on the first word (to get the last common character) and non-greedily on the second (to get the first common character). It then replaces the string with everything *but* the text in between the two characters.
> 0 votes

---
Tags: code-golf, string
---


title: Codebreakers and Codewriters

text:
# Question
Title: Codebreakers and Codewriters
Let's say you have some text, and you want it to send it to your friend, but you don't want anyone else to read it. That probably means you want to encrypt it so that only you and your friend can read it. But, there is a problem: you and your friend forgot to agree on an encryption method, so if you send them a message, they won't be able to decrypt it!

After thinking about this for a while, you decide to just send your friend the code to encrypt your message along with the message. Your friend is very smart, so they can probably figure out how to decrypt the message by studying the encryption method.

Of course, since other people might be reading the message, you want to choose an encryption scheme that makes it as hard as possible to crack (figure out the decryption scheme).

# Cops' Task

In this challenge, Cops will play the role of the writer: you will design an encryption scheme that converts strings to strings. However, this encryption scheme *must be **bijective***, meaning that no two strings must map to another string, and every string can be mapped to by an input. It must take only one input—the string to be encoded.

You will then post some code that performs the encryption, and a single message encrypted with the scheme detailed by your code.

Since you are paying by the byte to send messages, your score will be the length of your code *plus the length of the ciphertext*. If your answer is cracked, you will have a score of infinity.

After one week, you may reveal the text and mark your answer as **Safe**. Safe answers are those that cannot be cracked.

# Robbers' Task

Robbers will play either as the friend of the writer or the malicious middle man (there is no material difference, but you can role-play as either if it makes it more fun to do so). They will take the encryption schemes and the ciphertext and attempt to figure out the encrypted message. Once they figure out the encrypted message, they will post it in a comment. (There will not be a separate robbers' thread for this question.)

The winner will be the robber with the most cracks.

---

Here is an example of what a cracked solution might look like:

# Answer
# Jelly, 57 + 32 = 89 bytes (cracked)

```
“¡ḟċ⁷Ḣṡ⁵ĊnɠñḂƇLƒg⁺QfȥẒṾ⁹+=?JṚWġ%Aȧ’
O‘ḅ256b¢*21%¢ḅ¢ḃ256’Ọ

```

Encrypted message:

```
EªæBsÊ$Ê³¢?r×Q4e²?ò[Ý6

```

As a hex-string:

```
4518AAE6421973CA
9724CAB3A23F72D7
AD18855134651810
B23F1CF25BDD9036

```

Explanation:

```
O‘ḅ256b¢*21%¢ḅ¢ḃ256’Ọ
O                     convert each into codepoint
 ‘ḅ256                convert from bijective base 256 to integer
      b¢              convert from integer to base N
        *21           map each to its 21th power
           %¢         modulo N
             ḅ¢       convert to integer from base N
               ḃ256’  convert from integer to bijective base 256
                    Ọ convert each from codepoint

```

Where `N` is encoded by the string `“¡ḟċ⁷Ḣṡ⁵ĊnɠñḂƇLƒg⁺QfȥẒṾ⁹+=?JṚWġ%Aȧ’`, which is the number `105587021056759938494595233483151378724567978408381355454441180598980268016731`.

Also, this is the RSA method with `N` given above and public key `21`. Cracking this is equivalent to finding the two prime factors of `N`.
> 5 votes

# Answer
# Jelly, 88 + 64 = 152 bytes

Encryption function:

```
“¥@ɦ⁺€€Ṅ`yȤDƁWĊ;Y^y⁻U ⁸ßɠƁXẹṡWZc'µ÷ḷỊ0ÇtṙA×Ḃß4©qV)iḷỊDƭ Mṛ+<ṛ_idðD’
O‘ḅ256b¢*21%¢ḅ¢ḃ256’Ọ

```

Encrypted message:

```
AX!?ÖÍL¹    JÓ°û0àah4Û{µÌá`
^tÝrRÕù#êwðãTÓK"Íû´Ëß!øòOf«

```

As a hex-string:

```
9F419458213FD6CD4CB9094A10D3B0FB
8F30E0616834DB7BB517CCE1600A5E74
DD7252D5F923EA77F0E354D34B9F22CD
FB80B4CBDF21F80E94F24F9A66AB9112

```

Explanation:

```
O‘ḅ256b¢*13%¢ḅ¢ḃ256’Ọ
O                     convert each into codepoint
 ‘ḅ256                convert from bijective base 256 to integer
      b¢              convert from integer to base N
        *13           map each to its 13th power
           %¢         modulo N
             ḅ¢       convert to integer from base N
               ḃ256’  convert from integer to bijective base 256
                    Ọ convert each from codepoint

```

Where `N` is encoded by the string:

```
“¥@ɦ⁺€€Ṅ`yȤDƁWĊ;Y^y⁻U ⁸ßɠƁXẹṡWZc'µ÷ḷỊ0ÇtṙA×Ḃß4©qV)iḷỊDƭ Mṛ+<ṛ_idðD’

```

which is the number

```
15465347049748408180402050551405372385300458901874153987195606642192077081674726470827949979631079014102900173229117045997489671500506945449681040725068819

```

Also, this is the RSA method with `N` given above and public key `13`. Cracking this is equivalent to finding the two prime factors of `N`, which has 512 bits.
> 5 votes

# Answer
## JavaScript (ES6), 43 + 33 = 76 bytes Cracked by Leaky Nun

Encryption function, 43 bytes:

```
s=>[...s].sort(_=>Math.cos(i++),i=0).join``

```

Encrypted message, 33 bytes:

*NB: This encryption method is browser-dependent.*

```
FireFox: "ty a)s kaasoeocr!hTt; o s  -cwaoo"
Chrome : "oht aasoaoas   e)tosr;oky c!-cw T"
Edge   : "tskso ;- caroteoTha wa soo ay c!)"

```
> 3 votes

# Answer
# Braingolf, Cracked

```
(d1&,&g)&@

```

Try it online!

## Encrypted message, 45 bytes (UTF-8)

```
°Áݭїϳ{ًչםק{їϳэÁק{|э³קѡ|

```

## Hexcodes of encrypted message

```
C2 B0 C3 81 DD AD D1 97 CF
B3 C2 90 7B D9 8B D5 B9 D7
9D D7 A7 7B D1 97 CF B3 D1
8D C3 81 D7 A7 7B 7C D1 8D
C2 B3 D7 A7 D1 A1 7C C2 85

```

## Decrypted message

```
C'mon, this one's *easy*!

```

## Explanation

```
(d1&,&g)&@  Implicit input from commandline args
(......)    Foreach loop, foreach codepoint of input
 d          Split into digits
  1         Push 1
   &,       Reverse
     &g     Concatenate
        &@  Print

```

## Decoder

A decoder can be made by changing only 3 characters. Simply remove the `1`, and insert `$_` inbetween `&,` and `&g`

```
(d&,$_&g)&@

```
> 3 votes

# Answer
# JavaScript (ES6), 96+9=105 bytes

```
q=>Buffer(q).map((a,i,d)=>d[i-1]^Math.abs(1e16*Math.sin(d[i]+i))%255).sort((a,i)=>Math.tan(a*i))

```

Ciphertext (hex-encoded): `7d111c74b99faff76a`

Try it online!

### Sample outputs (using V8 engine):

abc123 -\> db48ea4f86b9

Hello -\> 1b3420f5ab
> 3 votes

---
Tags: cops-and-robbers, encryption
---


title: Where will your buddies sit?

text:
# Question
Title: Where will your buddies sit?
You and some buddies are going bowling. There are a total of *N* bowlers. However, there are only *N*-1 chairs to sit in. The solution is simple: whoever's turn it currently is doesn't get a chair. Then when their turn is over, they sit in the chair of the person that goes next.

Lets take an example. Say You are named *A*, and your four friends are named *B*, *C*, *D*, and *E*. Every player moves in alphabetical order, so you get to go first. Since there are 5 players, there are only 4 seats. Your friends sit in the four seats in this order:

> CEBD

You go, and yay you get a strike! It's *B*'s turn next, so you sit in his chair. Now it looks like this:

> CEAD

*B* goes. Gutterball! Then he sits in *C*'s spot, and *C* goes next turn.

> BEAD

then *C* sits in *D*'s chair.

> BEAC

and *D* sits in *E*'s chair

> BDAC

and lastly, *E* sits in your chair.

> BDEC

You'll notice that now everybody's seat is (pseudo) shuffled. You must find out, after *X* turns, who will be sitting where?

# Input

Your program must take two inputs from the user, a string and a number. No prompts are needed. The string will be 1-51 alphabetic characters (B-Z and a-z) with no repeats. This represents the order your friends chose to sit. There will be no uppercase *A* because that is you, and you always go first. The number will be the total number of rounds (not games) that you and your friends play. This number will be positive and reasonably sized (less than 1000).

# Output

Your program must print out the order your friends are sitting in after X turns, and whose turn it is. So for example, if after X turns the order was BEDGCAHF and it was *Z*'s turn, your program must print exactly this:

```
BEDGCAHF
It is Z's turn.

```

Here are a few sample input and outputs.

```
input: E, 4
E
It is A's turn.

input: E, 5
A
It is E's turn.

input: Bb, 2
AB
It is b's turn.

input: dgOPZXKDQYioHflFhpqzUsSaeILwckVNEtGTCJBvnruRyWMmjxb, 999
JNuvFDqjwEPVnMSlOWXgAZyGKordIRBtkamziphcUYbxfCsTQeH
It is L's turn.

```

# Rules

* Everybody goes in alphabetical order, with capital letters taking precedence over lower case.
* This is code-golf, so standard loopholes apply, and submissions are scored in bytes.

# Answer
# Pyth, 37 bytes

```
uXGK<.<+\ASzH2)QzpeK"It is ""'s turn.

```

Online Demonstration: Pyth Compiler/Executor

The algorithm is kinda based on @isaacg's solution. Like him I start with the initial seat-order and repeatedly use the replace-functionality of `X` to replace the next player with the current player.

But unlike his implementation, which replaces the char of the next player by the current player in the seating order, I use it in a more broad way. I replace each char of the current player by the next player and each char of the next player by the current player. This is accomplished by passing both players as second arg and omit the third arg (`XG"ab")` instead of `XG"a""b"`). Since the current player is not part of the string (he is playing), the first replacement has no effect at all. But it allows me to generate both players at the same time, while @isaacg has to generate them individually.

Another crazy new feature I use is the assignment operator. Until recently `=N1` got translated into `N = 1`, which was executed with Python. But nowadays it compiles to `assign('N',1)`. This function assigns `N` with 1 and returns the value (but doesn't print it). This allows saving intermediate results, which occur for instance in a reduce operation. Using this I was able to store the pair of players, which changed positions last, and print second player.

### Detailed Explanation

```
                      implicit: z = input string, Q = input number
u              Qz     reduce for H in range(Q), start with G = z
                        update G with:
       +\ASz              "A" + sorted(z)
     .<     H             cyclic shifted by H
    <        2            get the first 2 elements (current + next player)
   K                      store the result in K
 XG           )           replace next player by current player in G
                      implicit print

peK"It is ""'s turn.  print "It is" + K[-1] (current player) + "'s turn."

```
> 3 votes

# Answer
# Pyth, ~~39~~ 38 bytes

```
L@+\ASzbuXGyhHyHQzpyQ"It is ""'s turn.

```

This is based around repeated applications of the find and replace operation, `X`. The first bit defines a lookup function, `y`, which finds the `b`th player in the player order. Then, we repeatedly perform substitutions to find the final seating order, and finally print out whose turn it is.

Amusingly, the code to find the final seating order is shorter (18 bytes) than the code to print whose turn it is (21 bytes).

The code takes the seating string on the first line of STDIN, and the number of turns on the second.

Demonstration.

Explanation:

```
L@+\ASzbuXGyhHyHQzpyQ"It is ""'s turn.
                                          Implicit:
                                          z = input()
                                          Q = eval(input())

L                                         def y(b): return
  +\ASz                                    "A" + sorted(z)
 @     b                                  (               )[b]
        u       Qz                        reduce for H in range(len(Q)),
                                          G starts as z.
         XGyhHyH                          replace in G y(H+1) with y(H).
                  pyQ"It is ""'s turn.    Print out whose turn it is.

```
> 8 votes

# Answer
# CJam, ~~49~~ ~~45~~ 43 bytes

```
l_'A+$ri{:L2<(erL(+}*1<"
It is "\"'s turn."

```

I think this works. It just runs the algorithm as is.

Try it online.

## Explanation

```
l                       Read line (initial seating order)
_'A+$                   Copy, add "A" and sort to give bowling order

ri{          }*         Do <number of turns> times...
   :L                     Save bowling order as L
     2<(                  Get next and current bowlers
        er                Replace next with current in seating
          L(+             Push bowling order again and update (rotate)

1<                      Get current bowler from start of bowling order
"
It is "\"'s turn."      Output message

```
> 7 votes

# Answer
# Python 3, 110

```
s=input()
S=sorted(s+'A')*999
exec("y,*S=S;s=s.replace(S[0],y);"*int(input()))
print(s+"\nIt is %s's turn."%y)

```

An optimized version of Sp3000's solution using `replace`. The list `S` cycles though the letters present in order. We perform repeated replacements in the given string of each character of `S` by the previous one.
> 4 votes

# Answer
# Clip 10, ~~59~~ 56 bytes

```
[t{)k[qa)qglqtg(lqt}wx)nyN"It is "gnyt"'s turn.."`]s,x'A

```

## Example

```
[t{)k[qa)qglqtg(lqt}wx)nyN"It is "gnyt"'s turn.."`]s,x'A
dgOPZXKDQYioHflFhpqzUsSaeILwckVNEtGTCJBvnruRyWMmjxb
999
JNuvFDqjwEPVnMSlOWXgAZyGKordIRBtkamziphcUYbxfCsTQeH
It is L's turn.

```

## Explanation

The first input is the list of players, assigned to the variable `x`.

The second input is the number of turns, which the program obtains with `ny`.

```
[t                                        ]s,x'A .-t is the sorted list of players including A-.
  {                                      `       .-Print the following:            -.
    k[q            }wx)ny                        .-In each round (q is all the previous rounds)-.
       a)q                                       .-Replace                         -.
          glqt                                   .-the next player                 -.
              g(lqt                              .-with the previous player        -.

                     N                           .-Also print a newline            -.
                      "It is "    "'s turn.."
                              gnyt               .-The ny'th player in t           -.

```

Thanks to Sp3000 for the idea of using "replace".
> 3 votes

# Answer
# Python 3, 128 bytes

```
L=input()
S=sorted(L)+["A"]
i=0
exec("L=L.replace(S[i],S[i-1]);i=-~i%len(S);"*int(input()))
print(L+"\nIt is %s's turn."%S[i-1])

```

Takes two lines of input via STDIN — initial seating order then number of turns.

This is basically the same search-and-replace idea as my CJam solution. The only tricky part is that we stick `A` at the *back* of the bowling order and make our index `i` the index of the *next* bowler, thus taking advantage of indexing by -1 and avoiding `IndexError`s.

This is a few bytes shorter in Python 2, but I'm posting Python 3 for comparison with OP's solution.
> 3 votes

# Answer
# JavaScript (ES6) 116

116 bytes as program with I/O via popup window. 114 as a testable function.

Run code snippet in Firefox to test.

```
// as a program with I/O
for(t=[...s=(P=prompt)()].sort(),x=P(),p='A';x--;p=n)t.push(p),s=s.replace(n=t.shift(),p);P(`${s}
It is ${p}' turn`)

// as a function with 2 parameters, returning output as a 2 lines string
f=(s,x)=>{for(t=[...s].sort(),p='A';x--;p=n)t.push(p),s=s.replace(n=t.shift(),p);return(`${s}
It is ${p}' turn`)}

// Test suite
test=[
['CEBD',5], ['E', 4],['E',5],['Bb', 2],
['dgOPZXKDQYioHflFhpqzUsSaeILwckVNEtGTCJBvnruRyWMmjxb', 999]];

Out=x=>OUT.innerHTML=OUT.innerHTML+x;

test.forEach(([p,x])=>Out(p+' '+x+':\n'+f(p,x)+'\n'))
```

```
Test cases from OP:
<pre id=OUT></pre>
```
> 2 votes

# Answer
## PowerShell, 168 bytes

```
function x($s,$t){$p="A"+$s-split''|?{$_}|%{[int][char]$_}|sort|%{[char]$_};$l=$p.count;1..$t|%{$s=$s.replace($p[$_%$l],$p[($_-1)%$l])};$s;"It is $($p[$t%$l])'s turn."}

```

I've decided all my answers on this site will be in PowerShell. One day I'll have an answer that can compete...

call the function like this: `x Bb 2`
> 2 votes

# Answer
This answer isn't going to win, but I'll throw it out there anyway.

# Python 3, 167 bytes

```
s=input()
n=int(input())
c='A'
t=sorted(set(s+c))
F=len(t)
f=list(s)
for i in range(n):
 I=f.index(t[(i+1)%F]);c,f[I]=f[I],c
print(''.join(f)+'\nIt is '+c+"'s turn.")

```
> 1 votes

# Answer
# Pip, 54 bytes

Not very competitive, but at least I get to show off Pip's mutable strings and the Swap command. Takes the seating order and number of rounds as command-line arguments (which get assigned to `a` and `b`, respectively).

```
u:'Ao:SN A^u.aLbSu(aa@?C(o++i))Pa"It is ".u."'s turn."

```

**Explanation:**

```
u:'A                   u = player who's currently up

o:SN A^u.a
      ^u.a             Append "A" to the seating order, split into list of characters
o:SN A                 ASCII value of each char, sort the resulting list, assign to o

LbSu(aa@?C(o++i))
Lb                     Repeat b times:
  Su                   Swap u with:
    (a          )      The character of a at index:
      a@?              Find in a:
         C(o++i)       chr(ASCII value of next player from o)
                       (Subscripts wrap around, as in CJam, so no need for mod)

Pa                     Print the final lineup
"It is ".u."'s turn."  Current player (auto-printed)

```

It would have been 49 if I'd bothered to implement `SS` (sort as strings) at the same time I did `SN` (sort numeric)... Ah well, the perils of having a language in development.
> 1 votes

# Answer
# Python 2, 105 bytes

```
a,s='A',input()
exec"b=a<max(s)and min(e for e in s if e>a)or'A';s=s.replace(b,a);a=b;"*input()
print s,b

```

Try it online!

Golf of:

```
s=input()
n=input()
a='A'
for i in range(n):
 try:
  b=min(e for e in s if e>a)
 except:
  b='A'
 s=s.replace(b,a)
 a=b
print s
print b

```
> 1 votes

# Answer
# Perl 5, 102 + 1 (-n) = 103 bytes

```
s/\d+//;$t=$&;@p=sort'A',split//;for$i(1..$t){s/$p[$i%@p]/$p[--$i%@p]/}say"$_
It is $p[$t%@p]'s turn."

```

Try it online!

**Input**

Seating order, followed by number of turns without spaces:

```
SEatingOrder###

```
> 0 votes

---
Tags: code-golf, string
---


title: Chopsticks mutated with points KoTH

text:
# Question
Title: Chopsticks mutated with points KoTH
Basic rules (different from mine)

### Story

It is the year 4579, humans now have 2 hands with 1001 fingers each. Chopsticks has become based off of points. And @Dennis has more rep then @Martin... Hand drawn red circles are now downvoted... Jon Skeet has hit 2 trillion rep on every SE site... Yeah scary I know

Chopsticks is a hand game that has been solved. So to get around this I have created it mutated. I increased the amount of fingers.

## Rules of the game

The way this is played

Everyone starts with 2 hands. Each hand has 1001 fingers. Every hand starts with 1 (one) finger up on *each* hand. During your turn you can "hit" the other players hand. To hit you choose 1 of your hands to hit with and 1 of their hands to hit. The hand that was hit now has the amount of fingers that was their at first AND the amount of fingers that you had on the hand you hit with.

### EX

`P1: 1,1` `P2: 1,1`. `P1[0]` hits `P2[1]`. Now fingers are `P1:1,1` `P2:1,2`. Now `P2[1]` hits `p1[0]`. The fingers are now P1: `3,1` P2 `1,2`.

If one hand gets to 1001 fingers up or more then that hand is out. Then player who got a hand out (for their turn) can "split". Splitting is when you take the hand that is in and halve the amount of fingers (round up) and give those fingers to the other hand getting it back in.

### EX

P1: `1000,2` P2 `7,7`. `P2[0]` hits `P1[0]`. Score is P1: `0,2` P2 `1,1`. `P1[1]` splits for his turn and the score is P1: `1,1` and P2 `7,7`.

The game ends when one player has both hands out. Points are scored by the amount of fingers the winner has. More points = better. The loser gains no points.

There are other rules that are used but these are the ones used here.

Everybody plays everybody (round robin)

## Endgame

Total your points up from every round you win. Then average everybody's points up. Divide your total by the average points and get your final score. Most points win.

## Actual rules

Standard loopholes

Please do *not* try to solve the game. I actually have to be able to run it :P

Make sure the bot can run fast. With the length of rounds judging this will take a while

All libraries needed in your program must be in the default python library. Also list the ones you need imported. Imports will just be the basic import (for math I do: `import math`)

Answers must work in Python 3.x

# Handler

Your bot will be its own Python 3 file with a `play` function.

`play` will be passed two lists of two numbers each. This number indicates how many fingers are up on each hand. The first list is your own hand.

If you choose to hit the other player's hand, then return a list of two bits. The first bit is the index of the hand you are using to hit (`0` for the first, `1` for the last), and the second bit is the index of the hand you are hitting on the opponent.

If you choose to split, return any other truthy value.

Tada!

The controller can be found here. Save each bot in its own file and list each bot's filename (without `.py`) in `botnames`.

# Final note:

You and the other bot will take turns going first. If the game does not terminate in 100,000 (one hundred thousand) rounds, the game will be terminated and neither bot wins.

The controller is not protected against moves taking forever, but unnecessary overhead will be strongly frowned upon.

# Answer
> 6 votes
# CodingAndAlgorithms

This answer actually uses coding and algorithms, unlike the others so far!reference: imgur(also beats all of the answers posted before this)

```
def play(A, B):
    if sum(A) == 1:
        return [A.index(1), B.index(max(B))]
    elif max(A) + max(B) > 1000:
        return [A.index(max(A)), B.index(max(B))]
    elif 0 in A:
        return 1
    elif 0 in B:
        return [A.index(min(A)), 1-B.index(0)]
    else:
        return [A.index(min(A)), B.index(min(B))]

```

# Answer
> 3 votes
# Aggressor

```
def play(s, o):
    return [s.index(max(s)),o.index(max(o))]if all(s)else 1

```

Another starter bot, Aggressor will hit the larger of the opponent's hands with the larger of its own hands if both of its hands are non-empty; otherwise, it splits.

# Answer
> 3 votes
# CautionBot

```
def play(s,o):
 if max(s)+max(o)>1000 and (all(s) or max(s)+min(o)<1001):
  return [s.index(max(s)),o.index(max(o))]
 else:
  return [s.index(min(s)),o.index(min(filter(bool,o)))]if all(s) else 'split'

```

CautionBot doesn't want to cause too much trouble, so it hits the smaller of the opponent's hands with its smaller hand if it has both hands, and otherwise splits. However, CautionBot is no fool, so if it can take out an opponents' hand without immediately losing next turn, it will do so instead of its normal move.

# Answer
> 3 votes
# Equalizer

```
def play(s, o):
    if not all(s):
        return 1
    else:
        return [s.index(max(s)), o.index(min(filter(bool, o)))]

```

If Equalizer is missing a hand, it will split. Otherwise, it hits its opponents smallest hand with its own largest hand.

# Answer
> 2 votes
# RandomBot

```
import random

def play(s, o):
    return [random.randint(0,1)for i in'  ']if all(s)else 1

```

Just to get things started, here's a bot which makes a random hit if its hands are both non-empty; otherwise, splits.

Golfed because why not :3

# Answer
> 2 votes
## Error

Yes, that is the name of the bot.

```
def play(s, o):
    if max(s)+max(o)>1000:
        return [s.index(max(s)),o.index(max(o))]
    if 0 in s:return ''
    return [s.index(max(s)),o.index(min(o))]

```

I arrived at at this by testing with the other bots. However it is consistently second-last in my simulations. So Ill be making another bot eventually.

Edit: I can't seem to write any bot that beats CautionBot, and my extra testing seems to indicate that this is second best, not second worst.

# Answer
> 1 votes
# Marathoner

I tweaked Aggressor's code provided by "HyperNeutrino" to simply hit the smaller of the opponents two hands with the smaller of it's hands. It is a very silly strategy of course but I can't turn down being at the top of a chart! (Even though that chart would be losses)

I'm not sure if this code will run without errors because I was unable to test it due to being at work. However, it should run flawlessly.

```
def play(s, o):
     return [s.index(min(s)),o.index(min(o))]if all(s)else 1

```

---
Tags: king-of-the-hill, python
---


title: A-Z in 10's, you see?

text:
# Question
Title: A-Z in 10's, you see?
As a follow up to my previous challenge Count to 20 with Words!, we will once again be using the word list from that challenge to perform another task. This time, you will be exclusively using:

https://github.com/Magic Octopus Urn/wordListsByLength/blob/master/10.txt

To choose 26 different words, each starting with a unique letter, and output them in ascending order from A to Z. Here's a valid example:

```
aardwolves
babbitting
caravaning
debilitate
evaporator
fantasized
geographer
hawfinches
imbecility
juvenility
kalanchoes
lamaseries
malodorous
nudibranch
oligophagy
pantywaist
quarreling
russetting
scantiness
teetotaler
undercount
voodooisms
wentletrap
xenophobic
yeomanries
zwitterion

```

---

This is an aardwolf, this is a hawfinch, this is a kalanchoe, this is a nudibranch and a wentletrap.

---

# Rules

* No reading directly from the repository, or any other loopholes.
* You may select any 26 of the words provided in the link.
    + You choose words and these are the words your program should output every time.
* One word beginning with each of the following letters must be selected:
    + `[a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]`
* This is , lowest byte-count wins.

---

Any other suggestions for spin-offs using the word lists?

Also, feel free to steal my word-lists and make challenges.

# Answer
# Bubblegum, ~~100~~ 99 bytes

```
00000000: 45ce 4502 0420 0800 c0bb bfb4 3bc1 adcf  E.E.. ......;...
00000010: 6f23 b7a1 910b 63b3 0016 84da 40d4 fd41  o#....c.....@..A
00000020: 344c 2b81 e824 e09f 9e19 e4e9 8d3a 1353  4L+..$.......:.S
00000030: 3f7c c3fc 59b8 b732 5b07 62e7 c383 4fcc  ?|..Y..2[.b...O.
00000040: 4d5f 88c5 bd60 6f44 8c8d b87d 215e 78c3  M_...`oD...}!^x.
00000050: 359e ec4d 360c bd4a 94e2 6e25 e06f ef43  5..M6..J..n%.o.C
00000060: d286 17                                  ...

```

Try it online!

Output:

```
artinesses
businesses
cozinesses
dozinesses
easinesses
fastnesses
gastnesses
hazinesses
ickinesses
jokinesses
kindnesses
lazinesses
mazinesses
nosinesses
oozinesses
pastnesses
queasiness
rosinesses
sexinesses
tininesses
uglinesses
vastnesses
wilinesses
xanthomata
yeastiness
zaninesses

```

The words were again selected with simulated annealing:

```
from __future__ import print_function
import math
import random
import zopfli.zlib

wordlists = [[] for n in range(26)]
for word in open('wordListsByLength/10.txt', 'rb').read().splitlines():
    wordlists[ord(word[:1]) - ord('a')].append(word)

words = [random.choice(wordlist) for wordlist in wordlists]

temperature = 1.
score = 9999
best = score

while True:
    old_score = score
    n = random.randrange(len(wordlists))
    old_word = words[n]
    words[n] = random.choice(wordlists[n])
    score = len(zopfli.zlib.compress(b'\n'.join(words)) - 6
    if score > old_score and random.random() >= math.exp((old_score - score) / temperature):
        words[n] = old_word
        score = old_score
    else:
        temperature *= .9999
        if score < best:
            best = score
            print(best, repr(b'\n'.join(words)))

```
> 6 votes

# Answer
## JavaScript (ES6), 168 bytes

For each starting letter, outputs either the first word ending in *-inesses* or the first available word.

```
_=>`ash0bus0coz0doz0eer0foz0gor0hom0ink0jok0kaiserdoms
log0mir0nos0ooz0pun0quackeries
ros0siz0tin0ugl0vacantness
wir0xanthomata
yardmaster
zan0`.split`0`.join`inesses
`

```

### Demo

```
let f =

_=>`ash0bus0coz0doz0eer0foz0gor0hom0ink0jok0kaiserdoms
log0mir0nos0ooz0pun0quackeries
ros0siz0tin0ugl0vacantness
wir0xanthomata
yardmaster
zan0`.split`0`.join`inesses
`

o.innerHTML = f()
```

```
<pre id=o></pre>
```
> 5 votes

# Answer
# Jelly, 69 bytes

*This is the naive approach it may be improvable by some clever ticks*

```
“6)ọʋtL⁺%ḍʠ9ƲȮṆ'ṫZpɲṇḃb7ṗ³ðʠ©q€©[ẠṾṠɠ+ȯ!?^_iṘ©ð⁴ạ'8œÐṣTP³ḃXŻDƭƇM⁽H>Ỵ»

```

**Try it online!**

(Assumes that "Valid separators are ASCII-printable non-alphabetical characters (even numbers, don't care)" holds from the previous challenge)
> 4 votes

# Answer
# Jelly, 49 bytes

```
“J9,⁹FṾ»ŒVŒlµL=⁵µÐf
¢Ḣ€OIT+“¢&ĠUṗɓṃ€~ƙṂ’D¤;@0‘ị¢Y

```

Try it online! (Takes about 22 seconds on TIO)

Outputs:

```
aardwolves
babbitting
cabalettas
daftnesses
earlywoods
fabricants
gadgetries
habiliment
iatrogenic
jaborandis
kaiserdoms
labialized
macadamize
naboberies
oafishness
pacemaking
quackeries
rabbinical
sabadillas
tabernacle
ubiquinone
vacantness
wadsetting
xanthomata
yardmaster
zabaglione

```

**How it Works**

```
“J9,⁹FṾ»ŒVŒlµL=⁵µÐf           - all length 10 Jelly dictionary words
“J9,⁹FṾ»                        - literal string "dictionary.long"
        ŒV                      - Python eval: get list of long words
          Œl                    - set all to lowercase
            µ   µÐf             - filter keep only those which meet:
             L                  - length
              =                 - equal to
               ⁵                - 10

¢Ḣ€OIT+“¢&ĠUṗɓṃ€~ƙṂ’D¤;@0‘ị¢Y - main link
¢                               - length 10 Jelly dictionary words from helper
 Ḣ€                             - first letter of each.
   O                            - ord: character values
    I                           - difference between consecutive elements
     T                          - indices of nonzero elements
                            (gets indices of first word starting with each letter)
      +                         - add
       “¢&ĠUṗɓṃ€~ƙṂ’D¤          - the list [2,0,5,9,1,3,3,1,1,6,1,2,0,0,0,0,2,1,1,1,0,3,1,8,0]
                      ;@0       - append 0 to beginning (golfable?)
                         ‘      - increment each element
                          ị¢    - index into the above length 10 words
                            Y   - join by newlines

```
> 4 votes

# Answer
# Japt, ~~169~~ 107 bytes

```
`a®
¾n
¯g
¸w
e
fox
g
z

jo
ê]
¦m
µt
nos
oil
po
qua×@i
c
 x
d
ugl
void
°r
xopb
yeÇ
z`·£`ê£`hX

```

Try it online!

I wrote a program that helps me optimize the compression. It sorts a list by its shoco compression size.
> 3 votes

# Answer
# Python 2, ~~256~~ ~~231~~ 220 bytes

```
i=97
for w in"uto ibli aco emo ntom utur laci olo deo ackfishes ymo exic alac omo cean alyn uaternion eno eri omo rban eno avelessly ero outhfully witterion".split():print chr(i)+(w+["graphy","ology"][w[3:]>''])[:9];i+=1

```

Saved 36 bytes thanks to Jonathan Allan, who did most of the hard work for this (I just found the words :P)

Try it online!
> 3 votes

# Answer
# Japt, 85 bytes

```
97
`...`£`...`hXiU°d}R

```

where the two pairs of backticks represent strings of seemingly random printable and unprintable characters. Try it online! Output:

```
achinesses
boninesses
cozinesses
dozinesses
easinesses
fozinesses
gorinesses
hazinesses
ickinesses
jokinesses
keennesses
lazinesses
mazinesses
nosinesses
oozinesses
pipinesses
quadrantes
riminesses
sizinesses
tininesses
uglinesses
vainnesses
warinesses
xylotomies
yeomanries
zaninesses

```

### Explanation

The basic technique is:

```
97             Set U to 97
`ch
on
...`£  }R      Map each line X in this multiline string to:
U°d              Take U.toCharCode() and increment U.  ["a", "b", "c", ...]
Xi               Prepend this to X.  ["ach", "bon", "c", ...]
`cozinesses`h    Overwrite this onto the beginning of "cozinesses".
                 ["achinesses", "boninesses", "cozinesses", ...]
    £  }R      Rejoin with newlines and implicitly output.

```

I found `cozinesses` by starting with `nesses` as some other answers have used and repeatedly finding the previous letter that appeared the among the most of the 26 letters. Since greedy techniques are not often optimal, I later wrote a script to find the real optimal word:

```
alphabet="abcdefghijklmnopqrstuvwxyz".split``;
wordlist=alphabet.map(x=>[]);
document.body.innerText.split`\n`.slice(0,-1).map(x=>wordlist[x.charCodeAt()-97].push(x));
f=(q="",n=7,s=0,words=wordlist,z=n&&alphabet.map(x=>[x+q,words.map(y=>[y=y.filter(z=>z[n]==x),t+=0 in y][0],t=0),t]))=>n?z.filter(x=>x[2]>=Math.max(1,...z.map(x=>(x[2]-2)*2/3))).map(x=>f(x[0],n-1,s+26-x[2],x[1])).sort((a,b)=>a[1]-b[1])[0]:[q,s];

console.time("find optimal word");
console.log(f());
console.timeEnd("find optimal word");

```

<sup>(I don't care that it's incredibly ugly. This is how PPCG has taught me to code :P Don't worry, I don't do this in production.)</sup>

Anyway, when run in the browser console on the 10-letter word list, this outputs

```
[ "ozinesses", 57 ]

```

The `57` being the number of letters that would have to appear in the multiline string. It also took about 17 seconds on my computer, so be patient when you run it.

By replacing the `f=` line with

```
f=(q="",n=9,s=0,words=wordlist,z=n&&alphabet.map(x=>[x+q,words.map(y=>[y=y.filter(z=>z[n]==x),t+=0 in y][0],t=0),t]))=>n?[for(x of z.filter(x=>x[2]>=Math.max(1,...z.map(x=>(x[2]-2)*2/3))))for(y of f(x[0],n-1,s+26-x[2],x[1]))y].sort((a,b)=>a[1]-b[1]).filter((x,i,a)=>x[1]<=a[0][1]+20):[[q,s]];

```

you can get all suffixes within 20 chars of the optimal one. (Change the `20` at the end to something else to adjust this. Note: this function probably only works in Firefox.) You can find a list of all suffixes under 100 here.

Anyway, from there on it's just a task of finding the word for each letter of the alphabet that has the longest suffix in common with `ozinesses`. I wrote a Japt script to do this, as well as compress the necessary prefixes for me and tell me how long the resulting program will be. (You'll have to manually paste the word list between the quotation marks though.)

This explanation was probably somewhat confusing, so please feel free to ask any questions you may have.
> 3 votes

# Answer
# Bubblegum, ~~110~~ 106 bytes

Hexdump:

```
0000000: 45cc 4116 8240 0c83 e1bd b72c 50a1 0ed3  E.A..@.....,P...
0000010: 2015 454e 2fcf 4727 bb6f 91fc 1293 b946   .EN/.G'.o.....F
0000020: 68dc 3aec c91e 4772 2055 2279 e776 94aa  h.:...Gr U"y.v..
0000030: 1727 695b f392 7ca0 b1b8 f445 573b 39f3  .'i[..|....EW;9.
0000040: 5679 7344 1236 2717 169e 5b2b acdc 0663  VysD.6'...[+...c
0000050: 2f72 1b5b e10d 1b2e 7ed8 ddd5 b14c e84e  /r.[....~....L.N
0000060: 7e15 55fc df3d c473 f003                 ~.U..=.s..

```

Try it online!

Prints:

```
ashinesses
boxinesses
cozinesses
dozinesses
easinesses
foxinesses
gamenesses
hazinesses
inkinesses
jokinesses
knackeries
lamenesses
mazinesses
nosinesses
oilinesses
pokinesses
quackeries
rosinesses
samenesses
tamenesses
uglinesses
voidnesses
wilinesses
xenophobes
yeomanries
zaninesses

```
> 2 votes

# Answer
# Javascript (ES6), 163 bytes

```
_=>`ach
bon
c
d
eas
f
gam
ha
ick
jok
keen
la
ma
nos
o
pip
quackeri
rac
si
tid
ugl
vain
war
xenogami
yeomanri
zan`.replace(/.+/g,s=>s+"-ozinesses".substr(s.length))

```

```
f=
_=>`ach
bon
c
d
eas
f
gam
ha
ick
jok
keen
la
ma
nos
o
pip
quackeri
rac
si
tid
ugl
vain
war
xenogami
yeomanri
zan`.replace(/.+/g,s=>s+"-ozinesses".substr(s.length))
o.innerText = f()
```

```
<pre id=o>
```
> 2 votes

# Answer
# Python 2,  ~~168~~  166 bytes

```
i=97
for w in"ch on ag ew as ox am az ck ok azatsk ac at os il ip uacker ac ex id gl agilit ar enogam eomanr an".split():print"%c%si%ses"%(i,w,"ness"*(len(w)<3));i+=1

```

**Try it online!**

### How?

Initialises `i` to `97` (the ordinal of the character `a`) then loops through a list formed by `split`ting a string at spaces forming and `print`ing the words, incrementing `i` as it goes. Most of the entries, `w`, in the list are of length two, these are words that start with the alphabetic letter and end in `inesses`, i.e. of the form:
`chr(i)+w+'inesses'`.
The entries of length 6 are of the form:
`chr(i)+w+'ies'`
This means a formatting may be used to prepend the alphabetic letter and add an ending with the `'ness'` inserted like `'i'+?+'es'` when `w` is short like so:
`"%c%si%ses"%(i,w,"ness"*(len(w)<3))`
\- %c converts `i` to a character; the two `%s` insert `w` and `"ness"*(len(w)<3)`, where the latter is `"ness"` if `w` is short or `""` if `w` is long.
> 1 votes

# Answer
# SOGL V0.12, 66 bytes

```
"⅟μ█X§¡Ψ}|μ⁾k,²9γ↑č─[╝B4mh|c↑′ρ╤τnE╗Ζ±$ņ¦Pγ9¬oΘ′`║F→█#▲xpņRe└ωηηƨ‘

```

Try it Here!

A simple dictionary compession with the problem that no word that starts with X was in SOGLs dictionary, so I compensated with xenotropic - tropic was in the dictionary. And I needed to add the starting quote because otherwise the parser thought that `[` started a loop :/
> 1 votes

# Answer
# Charcoal, 84 bytes

```
ＵＯχ²⁶”m⌈⎚∧³δ¤↶””｜↖⧴=P“⪪šl¢‘υKBＳＡＤ ⁶⁸ςz↧\–～⎇Ｖ▷–ê"℅ ž⟲‹‹⮌0Bff5Ｙ⪪Ｅ？Þ¹@)⟦£δＴ⪪⌕↙]\ＲＺ_Ｑ‹″”

```

Try it online! Uses @HermanLauenstein's wordlist, but I saved one byte because I can miss out the `f`. For once, somewhat competitive even in in verbose mode, which is only 166 bytes. Try it online!

```
Oblong(c 26 "fozinesses")Print("ach\nbon\nc\nd\neas\n\ngam\nha\nick\njok\nkeen\nla\nma\nnos\no\npip\nquackeri\nrac\nsi\ntid\nugl\nvain\nwar\nxenogami\nyeomanri\nzan")

```
> 0 votes

---
Tags: code-golf, kolmogorov-complexity, natural-language
---


# Question
Title: Challenge: Multiplication of integers a by b without multiplication symbols
This challenge is as follows.

(Uhoh no! Now everyone is going to use reciprocal division. Now all the answers are going to look the same and lose originality, ugh!)

Given two integers multiply them, ... but you can't use the multiplication symbols "\*" and "x". As you probably know multiplication is just an extension of successive additions, so this challenge is definitely feasible, as for instance the product of 8 and 5 is five sums of 8 or eight sums of 5:

8 * 5 = 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5, & also ...

= 8 + 8 + 8 + 8 + 8 = 40

Restrictions/Conditions:

1) The two numbers are allowed to be any two integers.

2) The calculation should work on both positive and negative integers.

3) The multiplication product should be correct no matter the order in which the two integer factors are presented.

4) You cannot import any installable modules/libraries not native to the base functions of your programming language.

5) There is no need to worry about expanding the scope of either of the integer sizes as it is highly unlikely that either of the integers would overload your system memory.

6) You cannot use either of the operators "\*" or "x" as multiplication operators.

7) In case anybody asks, this is multiplication in base 10, exclusively.

8) New Restriction: One multiplication function/operators are now banned. Sorry Jonathon. Creating a new operator is fine, but using any built in one function multiplication operators are banned.

Desired output is the following:

```
a x b=c

```

Again, "x" here is not to be used as an operator, just a character.

So if a is 5 and b is 8, then c should be 40, and vice-versa.

This is , so the shortest code in bytes wins! Good luck!

Finally, if you could give a brief description of how your program works, everyone will appreciate that, I'm sure. Thanks.

# Answer
> 3 votes
# J, 2 bytes

```
%%

```

*x* * *y* = *x* / (1 / *y*)

```
%%  Input: x (LHS), y (RHS)
 %  Reciprocal of y
%   Divide x by 1/y

```

Also, multiplication is addition after log, then computing the power using base *e*.

## 5 bytes

```
+&.^.

```

*x* * *y* = *e*^(log(*x* * *y*)) = *e*^(log(*x*) + log(*y*))

```
+&.^.  Input: x (LHS), y (RHS)
 & ^.  Natural log of x and y
+      Add them
 &.^.  Apply inverse of natural log to the sum
       NB. e^sum

```

# Answer
> 2 votes
# Jelly, ~~12~~ 3 bytes

Uh turns out this works - port of Mile's J answer

```
İ÷@

```

A dyadic link taking the two integers

**Try it online!**

### How?

```
İ÷@ - Link: a, b
İ   - inverse a (i.e. 1/a - note: if a is 0 this yields inf)
 ÷@ - divide with reversed arguments (if a was 0, this is b divided by inf, which yields 0)

```

---

...which sure beats this:

```
Aẋ/SN¹⁸ṠSỊ¤?

```

A monadic link taking a list of the two integers and returning their product.

### How?

```
Aẋ/SN¹⁸ṠSỊ¤? - Link: list [a, b]    e.g. [-7, -3]     [3, -7]          [7, 3]    or [3, 0]
A            - absolute values           [ 7,  3]     [3,  7]          [7, 3]       [3, 0]
 ẋ/          - reduce by repetition      [ 7, 7, 7]   [3,3,3,3,3,3,3]  [7, 7, 7]    []
   S         - sum                        21           21               21           0
           ? - if:
          ¤  -   nilad followed by link(s) as a nilad:
      ⁸      -     chain's left argument [-7, -3]     [3, -7]          [7, 3]       [3, 0]
       Ṡ     -     sign                  [-1, -1]     [1, -1]          [1, 1]       [1, 0]
        S    -     sum                    -2           0                2            1
         Ị   -     abs(v) <= 1?            0           1                0            1
    N        - then: negate                           -21                  negate(0)=0
     ¹       - else: do nothing           21                            21

```

# Answer
> 2 votes
# Python 2, 31 bytes

```
lambda x,y:y and x/(1/float(y))

```

Try it online!

Old approach was longer, but then I remembered Math!:

# Python 2, 49 bytes

```
lambda x,y:sum([x,-x][y<0]for i in range(abs(y)))

```

Try it online!

# Answer
> 1 votes
# Ly, 17 bytes

```
n1-<ns>[<l+>1-]<u

```

A more difficult golf than I imagined...

# Answer
> 0 votes
# , 20 bytes

```
function(a,b)a/(1/b)

```

in R, `a/Inf` is `0`. Moreover, in the R, we can actually see define `*` to be this operation instead of `.Primitive("*")` which is the standard multiplication operator. The TIO link shows the old and new values and demonstrates that we can use our new `*` operator as the infix multiplication operator.

Try it online!

### 3 Bytes:

```
%*%

```

the matrix multiplication operator. Implicitly converts numbers into matrices, so it returns a `1x1` matrix as a result, but that's stored as a length-1 vector in R, just like a single number is.

OR

```
%o%

```

Which is an alias for `outer(x,y,'*')` which also computes the correct value for numbers.

# Answer
> 0 votes
## JavaScript (ES7), 14 bytes

```
(x,y)=>x/y**-1

```

# Answer
> 0 votes
# Japt, 4 bytes

```
/VpJ

```

Test it

---

## Explanation

Same as Neil's JS solution; divides (`/`) the first integer (`U`, implicit) by the second integer (`V`) raised to the power (`p`) of -1 (`J`).

# Answer
> 0 votes
# Brainfuck, 32 bytes

```
,>,[-<[->>+>+<<<]>>[-<<+>>]<]>>.

```

```
,>, take ascii input and put it in the first and second cells

[-  until the second cell is zero

    <[->>+>+<<<]> move the first cell value into the third and fourth cells

    >[-<<+>>]<    move the third cell to the first one again

] end loop. This layers the first value onto the fourth cell,
  as many times as the value in the second cell (= product of 1st & 2nd)

>>. print the fourth cell

```

# Answer
> 0 votes
# Forth, 7 bytes ( But it's a cheat. )

```
: m * ; ( Renaming it is still using it. )

use:
10 11 m . 110  ok

```

# Forth, 37 bytes ( the suggested loop )

```
: c 0 swap 0 ?do over + loop . drop ;

Use:
2 2 c  4  ok
0 0 c 0  ok
0 1 c 0  ok
1 0 c 0  ok
1 1 c 1  ok
1 2 c 2  ok
2 1 c 2  ok
1001 2002 c 2004002  ok

```

---
Tags: code-golf
---


title: Compute the Matrix-Vector

text:
# Question
Title: Compute the Matrix-Vector
Given an integer array of at least two elements, output the **Matrix-Vector** (defined below) of the array.

To compute the **Matrix-Vector**, first rotate through the size-`n` input array to create a matrix of size `n x n`, with the first element of the array following the main diagonal. This forms the matrix portion. For the vector, flip the input array vertically. Then perform normal matrix multiplication. The output vector is the result.

For example,

```
a = [1, 2, 3]

```

First, rotate the array two times to the right, to obtain `[3, 1, 2]` and `[2, 3, 1]`, then stack them to form a `3x3` matrix

```
[[1, 2, 3]
 [3, 1, 2]
 [2, 3, 1]]

```

Next, flip the array vertically to form the vector

```
[[1, 2, 3]    [[1]
 [3, 1, 2]  x  [2]
 [2, 3, 1]]    [3]]

```

Perform usual matrix multiplication

```
[[1, 2, 3]    [[1]    [[1+4+9]    [[14]
 [3, 1, 2]  x  [2]  =  [3+2+6]  =  [11]
 [2, 3, 1]]    [3]]    [2+6+3]]    [11]]

```

And the output is `[14, 11, 11]` or `[[14], [11], [11]]` (your choice of whether it's flattened or not).

### Example #2

```
a = [2, 5, 8, 3]

[[2, 5, 8, 3]    [[2]    [[4+25+64+9]     [[102]
 [3, 2, 5, 8]  x  [5]  =  [6+10+40+24]  =  [80]
 [8, 3, 2, 5]     [8]     [16+15+16+15]    [62]
 [5, 8, 3, 2]]    [3]]    [10+40+24+6]]    [80]]

[102, 80, 62, 80]

```

## Rules

* The input and output can be assumed to fit in your language's native integer type.
* The input and output can be given in any convenient format.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so other people can try out your code!
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
> 10 votes
# Jelly, 5 bytes

```
ṙJṚæ.

```

Try it online!

## Explanation

Firstly:

$$\left\[\begin{matrix} \vec{v}\_1 \\ \vec{v}\_2 \\ \vec{v}\_3 \\ \vec{v}\_4 \\ \end{matrix}\right\] \vec{x} = \left\[\begin{matrix} \vec{v}\_1 \cdot \vec{x} \\ \vec{v}\_2 \cdot \vec{x} \\ \vec{v}\_3 \cdot \vec{x} \\ \vec{v}\_4 \cdot \vec{x} \\ \end{matrix}\right\]$$

where \\$\vec{v}\_k\\$ are **row** vectors and \\$x\\$ is a **column** vector.

This demonstrates that matrix multiplication is just dot product between rows and columns.

Then, \\$\vec{v}\_1\\$ is actually \\$\vec{v}\\$ rotated \\$0\\$ to the right, and \\$\vec{v}\_k\\$ is \\$\vec{v}\\$ rotated \\$k-1\\$ to the right, etc.

From another angle, \\$\vec{v}\_1\\$ is \\$\vec{v}\\$ rotated \\$n\\$ to the left, and \\$\vec{v}\_n\\$ is \\$\vec{v}\\$ rotated \\$1\\$ to the left, etc.

## How it works

```
ṙJṚæ.   input: z (a list of length n)
ṙJ      [rot(z,1), rot(z,2), ..., rot(z,n)] (to the left)
  Ṛ     [rot(z,n), ..., rot(z,2), rot(z,1)]
   æ.   [rot(z,n).z , ..., rot(z,2).z , rot(z,1).z] (dot product)

```

# Answer
> 5 votes
# Python 2, 68 bytes

```
lambda x:[sum(map(int.__mul__,x,x[i:]+x[:i]))for i in range(len(x))]

```

Try it online!

# Answer
> 4 votes
# Python 2, 73 bytes

```
def f(v):r=range(len(v));return[sum(v[i]*(v*2)[i+j]for i in r)for j in r]

```

Try it online!

# Answer
> 4 votes
# Pyth, 10 bytes

```
ms*VQ.>QdU

```

Test suite.

# Answer
> 3 votes
# Jelly, 9 bytes

```
LḶN⁸ṙæ×W€

```

Try it online!

A function that returns a vertical array. As a full program it appears as if it returns a horizontal array. To return a horizontal array you'd do `LḶN⁸ṙ×⁸S€` instead.

# Answer
> 3 votes
# 05AB1E, 11 bytes

```
DgGDÁ})ε*}O

```

Try it online!

# Answer
> 2 votes
# Mathematica, 35 bytes

```
Most@FoldList[RotateRight,#,1^#].#&

```

Try it online!

*-9 bytes from @Not a tree*

# Answer
> 2 votes
# , ~~66~~ 62 bytes

```
sapply(length(n<-scan()):1,function(i)c(n[-(1:i)],n[1:i])%*%n)

```

Try it online!

# Answer
> 2 votes
# Haskell, 49 bytes

```
f v=sum.zipWith(*)v.fst<$>zip(iterate tail$v++v)v

```

Try it online!

For an input `v=[1,2]`

* `iterate tail$v++v` yields the list `[[1,2,1,2],[2,1,2],[1,2],[2],[],...]`
* `fst<$>zip l v` is the same as `take(length v)l` and yields `[[1,2,1,2],[2,1,2]]`
* `sum.zipWith(*)v` is mapped on each element and to yield the vector-matrix row product.

# Answer
> 1 votes
# CJam, 17 bytes

```
{__,,\fm>\f.*::+}

```

Try it online!

# Answer
> 1 votes
# GolfScript, 37 bytes

```
{..,({.)\+}[*]{[1$\]zip{~*}%{+}*}%\;}

```

Try it online!

# Answer
> 1 votes
# Python 3 \+ numpy, 68 bytes

```
lambda v:dot([roll(v,i)for i in range(len(v))],v)
from numpy import*

```

Try it online!

# Answer
> 1 votes
# , 14 bytes

```
+/ .*~#\.1&|.]

```

Try it online!

## Explanation

```
+/ .*~#\.1&|.]  Input: array M
      #\.       Length of each suffix, forms the range [len(M), ..., 2, 1]
             ]  Identity, get M
         1&|.   For each 'x' in the suffix lengths, rotate left M  by 'x'
+/ .*~          Dot product with M

```

# Answer
> 1 votes
# Haskell, ~~56~~ ~~55~~ 52 bytes

```
f l=[sum$zipWith(*)l$drop i$l++l|i<-[0..length l-1]]

```

Try it online!

*Saved one byte thanks to @Laikoni*

*Saved three bytes: `l++l` instead of `cycle l`*

# Answer
> 1 votes
# APL, 17 bytes

```
(↑¯1⌽(⍳≢)⌽¨⊂)+.×⍪

```

Explanation:

```
(↑¯1⌽(⍳≢)⌽¨⊂)+.×⍪

 ↑                      matrix format of
  ¯1⌽                   right rotate by 1 of
     (⍳≢)               the 1..[length N]
         ⌽¨             rotations of
           ⊂            the enclosed input
             +.×        inner product with
                ⍪       1-column matrix of input

```

# Answer
> 1 votes
# Octave - ~~67~~ 48 bytes

*Thanks to Luis Mendo for shaving this code down by 19 bytes!*

*Note: This code can only run in Octave. MATLAB does not support expressions inside functions that can create variables while simultaneously evaluating the expressions that create them.*

```
n=numel(a=input(''));a(mod((x=0:n-1)-x',n)+1)*a'

```

The original code in MATLAB can be found here, but can be run in any version of MATLAB. This code is 67 bytes:

```
a=input('');n=numel(a)-1;a(mod(bsxfun(@minus,0:n,(0:n)'),n+1)+1)*a'

```

# Explanation

1. `a=input('');` \- Receives a (row) vector from the user through standard input. You must enter the vector in Octave form (i.e. `[1,2,3]`).
2. `n=numel(...);` \- Obtains the total number of elements in the input vector.
3. `x=0:n-1`\- Creates a row vector that increases from `0` up to `n-1` in steps of 1.
4. `(x=0:n-1)-x'` \- Performs broadcasting so that we have a `n x n` matrix so that each row `i` are elements from 0 up to `n-1` with each element in row `i` subtracted by `i`.
5. `mod(..., n)+1` \- Ensures that any values that are negative wrap around to `n` so that each row `i` contains the vector from 0 up to `n-1` **circularly** shifted to the left by `i` elements. We add 1 as MATLAB / Octave starts indexing vectors or matrices with 1.
6. `a(...)` \- Creates a `n x n` matrix where using (4), we access the correct indices of the input vector dictated by each value from (4) thus achieving the matrix we need.
7. `(...)*a'` \- Performs matrix vector multiplication by transposing / flipping `a` to become a column vector prior to doing the multiplication.

# Example Runs

```
>> n=numel(a=input(''));a(mod((x=0:n-1)-x',n)+1)*a'
[1,2,3]

ans =

         14.00
         11.00
         11.00

>> n=numel(a=input(''));a(mod((x=0:n-1)-x',n)+1)*a'
[2,5,8,3]

ans =

        102.00
         80.00
         62.00
         80.00

```

---

# Try it online!

# Answer
> 1 votes
# Octave, 34 bytes

```
@(a)a*toeplitz(a,shift(flip(a),1))

```

Try it online!

# Answer
> 1 votes
## Husk, 11 bytes

```
mΣ§‡*´ṀKoṫ¢

```

Try it online!

## Explanation

```
mΣ§‡*´ṀKoṫ¢  Implicit input, e.g. [1,2,3]
          ¢  Cycle: [1,2,3,1,2,3,...
        oṫ   Tails: [[1,2,3,1,2,3...],[2,3,1,2,3...],[3,1,2,3...]...
     ´ṀK     Replace each element of input with input: [[1,2,3],[1,2,3],[1,2,3]]
   ‡*        Vectorized multiplication (truncated with respect to shortest list)
  §          applied to the last two results: [[1,4,9],[2,6,3],[3,2,6]]
mΣ           Sum of each row: [14,11,11]

```

# Answer
> 0 votes
# Javascript 79 bytes

Takes in an input array and outputs an array of the matrix vector

```
a=>(b=[...a],a.map(x=>([...b].reduce((m,n,i)=>m+=n*a[i],0,b.push(b.shift())))))

```

## Explanation

```
a=>(
    b=[...a],                    // copy the input into b
    a.map(x=>(                   // transform a into a new array
        [...b].reduce(           // copy b into a new array and reduce
            (m,n,i)=>m+=n*a[i],  // memo += the element in the array * the ith
                                 // element in a
            0,                   // start memo at 0
            b.push(b.shift())    // shift the first element in b to the end
                                 // not used by reduce, but performing this op
                                 // here saves a few bytes
        )
    ))
)

```

# Answer
> 0 votes
## Clojure, 80 bytes

```
#(map(fn[_ c](apply +(map * c %)))%(iterate(fn[c](into[(last c)](butlast c)))%))

```

`iterate` produces an infinite sequence, but instead of using `(take (count %) (iterate ...))` to stop it I use `%` as an extra argument to `map`.

# Answer
> 0 votes
# Perl 5, 65 + 1 (-a) = 66 bytes

```
@o=@F;for(@o){$r=0;$r+=$_*$F[$i++%@F]for@o;say$r;unshift@F,pop@F}

```

Try it online!

Takes the input vector as space separated numbers. Outputs linefeed separated numbers representing the result vector.

# Answer
> 0 votes
# C (gcc), 126 bytes

```
i,j;int*f(int*a,int n){int*r=malloc(n*sizeof(int));for(i=0;i<n;i++){r[i]=0;for(j=0;j<n;j++)r[i]+=a[j]*a[(j-i+n)%n];}return r;}

```

Try it online!

An array may be represented in input as a pointer and length.

# Answer
> 0 votes
# Common Lisp, 78 bytes

```
(lambda(x)(loop as i on(append x x)as y in x collect(reduce'+(mapcar'* i x))))

```

Try it online!

Double the array (in this case a Lisp list) and iterate over the sublists with `i` (using `x`, through `y`, to stop the iteration). Then calculate the next element of the result by summing the result of multiplying each element of `x` with each element of `i` (again stopping when the shorter list is terminated).

---
Tags: code-golf, math, array, matrix
---


title: Solve this uHerbert challenge

text:
# Question
Title: Solve this uHerbert challenge
**TL;DR**: Solve this particular challenge, a robot simulation, by stepping on all of the white pads, and avoiding the gray pads. You can step on a white pad any number of times, as long as you step on each white pad at least once. Solutions in languages like Befunge with a 2D instruction pointer would also be accepted, but H comes with the uHerbert program and its language specifications are given below. You do not need the uHerbert program to solve this, but it makes checking your solution a lot easier.

Here is what the level looks like. This is a 25x25 grid of cells, in which the robot and each white and gray pad occupy one cell. The robot is initially facing upward.

**Background on uHerbert**

Herbert is a robot simulation which I first encountered in the online IGF (Independent Games Festival) programming challenge back in 2008. For a long time, I was disappointed that I couldn't try out the challenges after the actual contest was over. Luckily, someone else must have read my mind and coded up this dandy little program: uHerbert (aka mu-Herbert or micro-Herbert).

**H (Language Specifications)**

The program is a robot simulation, but also acts an interpreter for the programming language H which serves only to move the robot.

There are three instructions:

* S: the robot steps one cell forward
* L: the robot turns left 90 degrees in place
* R: the robot turns right 90 degrees in place

There are three standard programming features at your disposal: functions, parameters, and recursion. Two different parameter types are supported.

**Numeric parameters**

```
g(A):sslg(A-1)

```

Here, g is a function with a one numeric parameter. This is boiler plate code; following this you can write your actual program by calling your function and passing an argument:

```
g(4)

```

This would call your function 4 times, and the recursion automatically terminates when your parameter `A` reaches a value of zero:

```
g(4) = sslg(4-1) = sslg(3) = sslsslg(2) = sslsslsslg(1) = sslsslsslssl

```

**Functional parameters**

You can also use functional parameters, which basically just reproduce instructions that you pass in:

```
f(A):rAlA

```

So if you call this function and pass instructions, it would evaluate to:

```
f(ss) = rsslss
f(sslssr) = rsslssrlsslssr

```

**Other syntax**

Functions can have more than one parameter, and they can also have both types. They could alternatively have no parameters. The following are both valid functions as well:

```
j:ssss
k(A,B):Ajjjk(A,B-1)

```

As you can see, the function j takes no parameters, and the function k takes both types of parameters. A is a functional parameter and B is a numeric parameter, as described above.

**Infinite recursion**

Infinite recursion is also allowed, but can only be initiated once and is effectively terminated when you step on the final white pad (without having stepped on any gray pads):

```
m:sslssrm

```

**Solve condition**

The goal is to get the robot to step on all of the white pads, and to avoid stepping on any of the gray pads. White pads can be stepped on any number of times, as long as each one is stepped on at least once. The robot is able to step on any point in the grid that it can reach (some levels have barrier walls and in this level the gray pads sort of act as a barrier).

The puzzle shown earlier is available on the site above from **level\_pack2.zip** and is called **level3.txt**. Both the uHerbert program and the level pack are still available from the above link as of today (the site has been archived but the archive engine still hosts it), but they are not required for a solution.

**I would like to see the shortest solution possible as per code golf.** Solutions in languages other than H will not be accepted as valid. (It would certainly be interesting to see an example solution in a language like Befunge where the instruction pointer travels on a 2D grid, but per atomic code golf scoring, only H instructions can be given an accurate score. The instruction pointer could be treated as the robot's position, for example.) A valid solution is one where the robot steps on all the white pads (each at least once) and does not step on any gray pads. Stepping in other parts of the grid is fine but in this particular puzzle you can't do that without stepping on a gray pad. The starting position of the robot cannot be changed.

I should also note that solutions which jump to a non-adjacent cell will not be accepted. This is not possible for the robot in the simulation, and would not represent a valid solution. H does not allow this anyway. So a valid solution must be one comprised of single steps. For each cell in the grid, there are only four adjacent cells: the ones orthogonal to it (above, below, and to the left and right). This of course would disallow diagonal steps, but because you are only able to turn in 90 degree increments, diagonal steps are not even possible.

If the robot is given an instruction which requires it to move into a barrier or outside the grid, the result is basically "derp" - the robot hits the wall and stays where it is, and the instruction pointer moves to the next instruction (the instruction is basically skipped).

**Note about solution size**

When you open this level in the program, you'll notice it is apparently possible to solve in 13 bytes. I am totally baffled as to how that is possible, and curious to see how close others are able to come to that. My shortest solution is 30 bytes in H. If anyone wants me to post it, I will, but I'd like to see other solutions before posting mine. The program also gives you a score, but the score is irrelevant to this question. Solutions of any score will be accepted.

It seems that the uHerbert program does not count parentheses or colons as part of your program (you will see this when it counts up your bytes). So for the purposes of this question, in the H language, parentheses and colons will not count as bytes towards your solution since they are primarily delimiters and purely syntactical rather than semantic in nature.

# Answer
# H, 13 bytes

```
a:ssr
b:sasaaab
b

```

### Demo
> 6 votes

---
Tags: atomic-code-golf, simulation
---