Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
int max=9, r=1, x=0,y=0;
int[,] m=new int [max,max];
float border = max-0.6f;
for (int d = 0; d < 2*max-1; d++)
{
for (int i=0; i< Mathf.RoundToInt(border);i++) {m[d%4==1?x++:d%4==3?x--:x, d%4==0?y++:d%4==2?y--:y] = r++;}
border -= d==0?0f:0.5f;
}
m[x,y]=r;
int max=9, r=1, x=0,y=0;
int[,] m=new int [max,max];
float border = max-0.6f;
for (int d = 0; d < 2*max-1; border -= d++ ==0?0f:0.5f) {for (int i=0; i< Mathf.RoundToInt(border);i++)
{m[d%4==1?x++:d%4==3?x--:x,d%4==0?y++:d%4==2?y--:y]=r++;}}
m[x,y]=r;
int max=9, r=1, x= -1,y=0;
int[,] m=new int [max,max];
float border = max;
for (int d = 2; d <= 2*max+1; border = max+0.5f - 0.5f*d++) {for (int i=0; i< (int)(border);i++) {m[x+=(d%4-1)%2, y+=(d%4-2)%2] = r++;}}
int max=6,x=-1,y=0,r=1;
int[,] A=new int[max,max];
for(int d=1;d<=2*max;d++) for(int k=0;k<max-d/2;k++) A[y+=(d%4-1)%2,x-=(d%4-2)%2]=r++;
int max=9; int[,] m=new int[max,max];
for(int d=1,r=1,x=-1,y=0,b=max;d<=2*max; b+=max-d+d++/2) while (r<=b) m[x-=(d%4-2)%2,y+=(d%4-1)%2]=r++;
int N=6,x=-1,y=0,r=1;
int[,] A=new int[N,N];
for(int d=1;d<2*N;d-=(N*d-d*d/4-r)>>31) A[y+=(d%4-1)%2,x-=(d%4-2)%2]=r++;
int N=6,x=-1,y=0,r=1;
int[,] A=new int[N,N];
for(int d=1;d<2*N;d+=N*d-d*d/4<r?1:0) A[y+=(d%4-1)%2,x-=(d%4-2)%2]=r++;
int N=7,x=-1,y=0,r=0,d=1;
int[,] A=new int[N,N];
while((d+=r/(N*d-d*d/4))<2*N) A[y+=(d%4-1)%2,x-=(d%4-2)%2]=++r;
for(int [,] s={{1,1,-1,0,6}}, A=new int[s[0,4],s[0,4]]; s[0,0]<2*s[0,4]; s[0,0]+=s[0,4]*s[0,0]-s[0,0]*s[0,0]/4<s[0,1]?1:0) A[s[0,2]-=(s[0,0]%4-2)%2,s[0,3]+=(s[0,0]%4-1)%2]=s[0,1]++;
int Nx=9,Ny=6; int[,] m=new int[Nx,Ny];
for(int d=1,r=1,x=-1,y=0,b=Nx;1<=(d%2==0?Nx--:Ny--);b+=d++%2==0?Nx:Ny) while (r<=b) m[x-=(d%4-2)%2,y+=(d%4-1)%2]=r++;
def spiral(x,y,s):
diag = list()
for i in getUnsortDiag(s):
diag[(len(diag)+1)//2:(len(diag)+1)//2] = [i]
x -= 1
y -= 1
halfS = math.ceil(float(s)/2)
if (x == y): return diag[x]
if (x > y <= s-x-1 and y+1 < halfS): return diag[y]+x-y
if (halfS <= x > y): return diag[x]-x+y
if (s-x-1 <= y >= halfS): return diag[y]-x+y
return diag[x+1]+x-y
def getUnsortDiag(s):
res, step, changeStep = 1, (s-1)*2, False
for i in range(s):
yield res
res += step
if changeStep:
step -= 4
changeStep = ~changeStep
#include <complex>
#include <vector>
#include <cstdio>
typedef std::vector<int> row;
typedef std::vector<row> matrix;
typedef std::complex<int> vec;
inline int & at(matrix &x, const vec &v) {
return x[v.real()][v.imag()];
}
inline bool is_illegal(matrix & x, const vec & p) {
return p.real() == x.size() || p.real() < 0
|| p.imag() == x.size() || p.imag() < 0
|| at(x, p) != 0;
}
inline void turn_right(vec & v) { v *= vec(0, -1); }
void fill(matrix &x) {
vec pos(0, 0), dir(0, 1);
for (int i = 1, e = x.size() * x.size(); i <= e; ++i) {
at(x, pos) = i;
if (is_illegal(x, pos + dir)) turn_right(dir);
pos += dir;
}
}
int main()
{
int n = 10;
row r(n, 0);
matrix x(n, r);
fill(x);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j)
std::printf("%4d", x[i][j]);
std::printf("\n");
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
if ( argc < 2 ) {
printf("\n Usage: %s [dimension]\n\n", argv[0]);
return 0;
}
int dim = atoi(argv[1]); // FIXME: yeah, we need to check the upper bounds as well
if ( dim <= 0 ) {
printf("Dimension has to be > 0\n");
return 0;
}
// create and initialize the matrix
int **array = new int*[dim];
for (int i = 0; i < dim; ++i) {
array[i] = new int[dim];
for ( int j=0; j < dim; ++j ) {
array[i][j] = 0;
}
}
enum { Right = 0, Down = 1, Left = 2, Up = 3 };
int step[][2] = { {1, 0}, {0, 1}, {-1, 0}, {0, -1} };
int count = dim * dim;
int row = 0, col = 0;
int dir = Right;
for (int c = 0; c < count; ++c ) {
array[row][col] = c+1;
// new coordinates
int col1 = col + step[dir][0];
int row1 = row + step[dir][1];
// check if valid
if ( col1 < dim && col1 >= 0 && row1 < dim && row1 >= 0 && array[row1][col1] == 0 ) {
col = col1;
row = row1;
}
else {
dir += 1;
if ( dir > Up ) {
dir = Right;
}
col += step[dir][0];
row += step[dir][1];
}
}
// print the result
for ( int i = 0; i < dim; ++i ) {
for ( int j = 0; j < dim; ++j ) {
printf("%3i ", array[i][j]);
}
printf("\n");
}
// clean up the memory
for (int i = 0; i < dim; ++i ) {
delete[] array[i];
}
delete[] array;
return 0;
}
size_t n = 100000;
volatile size_t ret;
for (size_t i = 0; i < n; ++i)
{
for (size_t j = 0; j < n; ++j)
{
if (i > j)
{
if (i + j < n)
{
ret = (n - (j + 1)) * (j + 1) * 4 - (i - (j + 1));
}
else
{
ret = i * (n - i) * 4 - (i - (n - i)) - (j - n + i + 1);
}
}
else
{
if (i + j < n)
{
ret = i * (n - i) * 4 - (i - (n - i)) + i + j - n + 1;
}
else
{
ret = (n - (n - j - 1)) * (n - j - 1) * 4 + (j - (n - j)) + i + (j - n) + 3;
}
}
}
}
I
nt Calc(int N,int x,int y){
int a=x>=y ? 0 : 3;
if(x+y>=N) a^=1;
x=2*x-N+1;
y=2*y-N+1;
int r=x*((2-a)%2)+y*((a-1)%2);
int m=x*((1-a)%2)+y*((2-a)%2);
return N*N-(r+1)*(r+1)+a*r+(m+r)/2;
}
0 5 18 39 68 105..., по мере отдаления от 0 для соседних рядов действуют те же правила).def spiral(x,y,s):
x,y = x-1, y-1
if (x == y): return getDiag(x,s)
if (x > y <= s-x-1): return getDiag(y,s)+x-y
if (x > y): return getDiag(x,s)-x+y
if (s-x-1 <= y): return getDiag(y,s)-x+y
return getDiag(x+1,s)+x-y
getDiag = lambda x,n: (n-x)*4*x+1 if (x <= math.ceil(float(n)/2)-1) else (x)*(2+4*(n-x-1))+1+2*(n-x-1)У одного решение не скомпилилось, у другого простое консольное решение на плюсах, а у меня вот такой приятный глазу UI. Похоже, выбор был очевиден.Мне одному кажется, что выбор тут очевиден не в пользу автора?
Works is better than perfect.
void step(int x, int y) {
if (safe(x, y)) {
// красим ячейку
fill(x, y);
// шагаем дальше
step(x + 1, y - 2);
step(x + 2, y - 1);
// и остальные шесть ходов
}
}
void main() {
clearTable();
step(0, 0);
}
К сожалению, FB не является моей приоритетной целью;
Я плох в плюсах, но, вроде как, там нельзя в кастомное место консоли выводить символ.
(Господа минусующие! Пожалуйста, напишите, что не так со статьей. А то я просто поделился своим опытом, и сразу такой холодный и молчаливый прием)
N = 9
A, x, d = {0: N * N}, 1, 1j
for p in range(N * N - 1, 0, -1):
A[x] = p
if abs(x.imag) == abs(x.real):
x += (1 - 1j) * (d == 1)
d *= 1j
x += d
r = [[A[-x + N // 2 - (N // 2 - y) * 1j] for x in range(N)] for y in range(N)]
print('\n'.join(' '.join("%4d" % elem for elem in line) for line in r))
Дано N <= 10^18, row <= N, col <= N. Вывести число, находящееся в строке row, столбце col для квадрата со стороной N.
Дано N <= 10^18, row <= N, col <= N. Вывести число, находящееся в строке row, столбце col для квадрата со стороной N.
x <= math.ceil(float(n)/2)-1
void CalcBack(int N,long long m,int &x,int &y){
m=(long long)N*N-m;
int r=(int)sqrt((double)m);
if((r+N)&1) r--;
if(r<0) x=y=(N+1)/2;
else{
long long dm=m-(long long)r*r;
int dmr=(int)(dm%(r+1));
int k=(N-r)/2;
switch(dm/(r+1)){
case 0: x=k; y=k+dmr+1; break;
case 1: x=k+dmr+1; y=N+1-k; break;
case 2: x=N+1-k; y=N-k-dmr; break;
case 3: x=N-k-dmr; y=k; break;
}
}
}
Option Explicit
Dim N As Long
Dim V() As Long
Private Sub Form_Click()
Me.Cls
N = InputBox("N=?")
FillSquare
ShowSquare
End Sub
Private Sub FillSquare()
If N < 1 Then Exit Sub
ReDim V(1 To N, 1 To N)
Dim modeIsRow As Boolean, dirIsFromLeft As Boolean, iter&, i&, j&, r&, c&, r1&, rn&, c1&, cn&, try&
r1 = 1: rn = N: c1 = 1: cn = N: modeIsRow = True: dirIsFromLeft = True:
iter = 1
Do
try = try + 1
If modeIsRow Then
If dirIsFromLeft Then r = r1 Else r = rn
For i = IIf(dirIsFromLeft, c1, cn) To IIf(dirIsFromLeft, cn, c1) Step IIf(dirIsFromLeft, 1, -1)
V(r, i) = iter: iter = iter + 1
Next i
If dirIsFromLeft Then r1 = r1 + 1 Else rn = rn - 1
Else
If dirIsFromLeft Then c = cn Else c = c1
For i = IIf(dirIsFromLeft, r1, rn) To IIf(dirIsFromLeft, rn, r1) Step IIf(dirIsFromLeft, 1, -1)
V(i, c) = iter: iter = iter + 1
Next i
If dirIsFromLeft Then cn = cn - 1 Else c1 = c1 + 1
End If
If c1 > cn Or r1 > rn Then Exit Do
modeIsRow = Not modeIsRow
If try Mod 2 = 0 Then dirIsFromLeft = Not dirIsFromLeft
Loop
End Sub
Private Sub ShowSquare()
Dim i&, j&, s$
Me.Cls
Print vbNewLine
For i = 1 To N
s = vbTab
For j = 1 To N
s = s & (V(i, j) & vbTab)
Next j
Print s & vbNewLine
Next i
End Sub
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Box
{
public interface IAsset
{
void Accept(IVisitor visitor);
}
public class MyBox : IAsset
{
public int[,] Arr;
public int Size;
public MyBox(int size)
{
this.Size = size;
Arr = new int[size, size];
}
public void Accept(IVisitor visitor)
{
visitor.Visit(this);
}
public override string ToString()
{
string s = "";
for (int i = 0; i < Size; i++)
{
for(int j = 0; j < Size; j++)
{
s += (" " + String.Format("{0:D2}", Arr[j, i]) + " ").Replace(" 00 ", " __ ");
}
s += "\r\n";
}
return s;
}
}
public interface IVisitor
{
void Visit(MyBox box);
}
public class MyVisitor : IVisitor
{
public enum Directions { Left, Right, Up, Down }
public class Rules
{
private int index = 0;
public Directions CurrentDirection
{
get
{
return rules[index];
}
}
private List<Directions> rules = new List<Directions>
{
Directions.Right,
Directions.Down,
Directions.Left,
Directions.Up
};
public void SwitchToNext()
{
index++;
if (index > 3)
index = 0;
}
}
private Rules rules = new Rules();
private bool isObstacle(MyBox box, Directions direction, int x, int y)
{
switch(direction)
{
case Directions.Right:
if (x + 1 >= box.Size)
return true;
return box.Arr[x + 1, y] != 0;
case Directions.Down:
if (y + 1 >= box.Size)
return true;
return box.Arr[x, y + 1] != 0;
case Directions.Left:
if (x - 1 < 0)
return true;
return box.Arr[x - 1, y] != 0;
case Directions.Up:
if (y - 1 < 0)
return true;
return box.Arr[x, y - 1] != 0;
default:
throw new NotSupportedException();
}
}
public void Visit(MyBox box)
{
int x = -1;
int y = 0;
int value = 1;
while(value < box.Size * box.Size + 1)
{
if(isObstacle(box, rules.CurrentDirection, x, y))
rules.SwitchToNext();
switch(rules.CurrentDirection)
{
case Directions.Right:
x++;
break;
case Directions.Down:
y++;
break;
case Directions.Left:
x--;
break;
case Directions.Up:
y--;
break;
}
box.Arr[x, y] = value;
value++;
}
}
}
class Program
{
static void Main(string[] args)
{
Console.Write("Type the size (enter for 8): ");
string str = Console.ReadLine();
if (String.IsNullOrWhiteSpace(str))
str = "8";
int size = Int32.Parse(str);
IVisitor visitor = new MyVisitor();
MyBox box = new MyBox(size);
box.Accept(visitor);
Console.WriteLine(box);
}
}
}
def position(a):
x = 0
y = 0
minX, maxX = 1, a - 1
minY, maxY = 0, a - 1
xyz = 1
for count in range(1, a**2 + 1, 1):
yield x, y
if xyz == 1:
y += 1
if y == maxY:
xyz +=1
maxY -=1
elif xyz == 2:
x += 1
if x == maxX:
xyz +=1
maxX -=1
elif xyz == 3:
y -= 1
if y == minY:
xyz +=1
minY +=1
elif xyz == 4:
x -= 1
if x == minX:
xyz +=1
minX +=1
if xyz > 4:
xyz = 1
def PrintHelix(z):
a = len(z)
for x in range(a):
row = ""
for y in range(a):
row += " " + z[x][y]
print (row)
a = 3# len
z = [[0]*a for x in range(a)]
for index, (x,y) in enumerate(position(a), 1):
z[x][y] = str(index)
PrintHelix(z)
#include<stdio.h>
void main(){
int N;
scanf("%d",&N);
for(int i=0;i<N;i++){
int k=2*i<N ? i : N-i;
for(int j=0;j<k;j++) printf("%4d ",4*j*(N-j-2)+4*N+(j-i)-3);
for(int j=k;j<N-k;j++) printf("%4d ",2*i<N ? 4*(N-i)*i+(j-i)+1 : 4*(N-i)*i+2*N-3*i-1-j);
for(int j=N-k;j<N;j++) printf("%4d ",(4*(N-j)-1)*(j+1)+i-2*N);
printf("\n");
}
}Вы бы взяли на работу человека, пишушего такой код? :)
-module(facebook).
-export([square/1, print_square/1]).
square(N)->square(1, N).
square(Start, 1)->[[Start]];
square(Start, 2)->[[Start, Start+1], [Start+3, Start+2]];
square(Start, N)->
TopRight = Start+N-1,
[lists:seq(Start, TopRight)]++
extend(square(TopRight+3*N-3, N-2), TopRight+3*N-4, TopRight+1, [])++
[lists:reverse(lists:seq(TopRight+N-1, TopRight+2*N-2))].
extend([H|T], Left, Right, Acc)->
extend(T, Left-1, Right+1, [[Left]++H++[Right]|Acc]);
extend([], _, _, Acc)->lists:reverse(Acc).
print_square(N)->
lists:foreach(fun(Row)->io:format("~w~n", [Row]) end, square(N)).
Как я выбил собеседование в Facebook