text:
<file_sep>---
date: 2020-06-11 00:00:00
title: Ferramentas que uso para trabalhar
description: Um resumo das ferramentas que costumo utilizar no meu dia a dia
category: Dev
background: '#FCB005'
image: 'assets/img/ferramentas-que-uso-thumbnail.jpg'
keywords: 'ferramentas;development;productivity'
---

Você como desenvolvedor deve utilizar um conjunto de ferramentas no seu dia a dia. Neste post quero deixar um resumo das ferramentas que mais utilizo para trabalhar e que me ajudam muito.

## Visual Studio Code

![Visual Studio Code](/assets/img/fqu-vscode.png)

[https://code.visualstudio.com/](https://code.visualstudio.com/)

Tempos atrás, não era muito adepto de utilizar ferramental da Microsoft, (tinha um preconceito bobo quanto a isso, para mim só o pacote office era bom, que vergona ne!). Mas depois de começar a utilizar o VS Code tudo mudou. Hoje não me vejo programando em outro editor que não seja esse, mesmo sabendo que existem muitos outros por ai. (para mim é ótimo).

O VS Code tem muitas funcionalidades bacanas (isso daria outro post), mas agora somente vou focar em mostrar a configuração que eu utilizo.

#### Tema

Utilizo o tema **Nord** que é baseado nesta [paleta](https://www.nordtheme.com/). Como eu fico muito tempo olhando para a tela a combinação de cores deste tema não me cansa os olhos.

![Nord](/assets/img/fqu-vscode-nord.png)

#### Extensões

***Auto Rename Tag***

Esta extensão ajuda muito na hora de escrever código com linguagens de marcação (HTML/XML), e é preciso renomear uma tag.

![Auto Rename Tag](/assets/img/fqu-vscode-autocomplete-tag.gif)

***Bracket Pair Colorizer***

Esta extensão mostra com cores diferentes os conjuntos de chaves, dessa forma é muito mais simples identificar um trecho de código que esteja dentro de um par de chaves, ainda mais quando o código vai ficando muito extenso.

![Bracket Pair Colorizer](/assets/img/fqu-vscode-bracket.png)

***ESLint***

Acredito que a padronização de código é bastante importante nos projetos, então esta extensão me auxilia para que o meu código fique padronizado seguindo as regras configuradas para códigos Javascript.  Para mais informação sobre este assunto pode dar uma olhada na [documentação oficial](https://eslint.org/).

***vscode-icons***

Sou bastante visual também, então gosto de "firulas".  Com esta extensão o editor mostra um icone relacionado ao tipo de arquivo do projeto. Não muda nada, mas visualmente é legal.

![vscode-icons](/assets/img/fqu-vscode-icons.gif)

***Reactjs code snippets***

Para aumentar a produtividade na hora de escrever aplicações com [React JS](https://reactjs.org/), esta extensão é uma mão na roda. O VS Code tem várias extensões com snippets prontos para outras linguagens também.

![Reactjs code snippets](/assets/img/fqu-vscode-react.gif)

***GitLens***

É bom conhecer os principais comandos do git, porém tem alguns comandos do git que é muito mais produtivo (na minha opinião), utilizar uma ferramenta visual. Como a produtividade é importante para mim também, então utilizo esta extensão que permite fazer muitas coisas com o git de forma visual.

![GitLens](/assets/img/fqu-vscode-gitlens.gif)

#### Configurações

Vou colocar [aqui](https://gist.github.com/gasakawa/a4072d13da3e99269da7e5de20b296ba) as configurações que eu utilizo no meu VS Code, fique a vontade de copiar tudo ou somente aquilo que você considere que faz sentido.

## Extensões Google Chrome

***React Developer Tools***

Aplicações desenvolvidas com React renderizam os componentes como elementos HTML, então na hora de desenvolver uma aplicação React é necessário as vezes verificar os componentes que são utilizados em uma determinada página. Para isto a extensão React Developer Tools, ajuda bastante.

![React Developer Tools](/assets/img/fqu-chrome-react.jpg)

***JSON Viewer***

As respostas de uma API, geralmente são em formato JSON. Fazendo os testes de uma API diretamente no browser, esta extensão ajuda na visualização da resposta.

![JSON Viewer](/assets/img/fqu-vscode-jsonviewer.png)

***Octotree***

Esta extensão é **sensacional**, descobri ela recentemente graças ao curso de GoStack da [rocketseat](https://rocketseat.com.br). Sabe quando estamos vendo um repositório no github, e vamos navegando nas pastas ou arquivos o que leva bastante tempo, que é melhor clonar o repositório na máquina local? Com esta extensão isso não é mais necessário.

![Octotree](/assets/img/fqu-chrome-octotree.gif)

## Aplicações / Tools

***Notion***

Antes utilizava o Evernote, porém hoje uso o [notion](https://www.notion.so/) para organizar meu trabalho e ideias. Mas o notion não é somente uma ferramenta de "notes", ela é bem poderosa e funcional, que permite fazer quase tudo o necessário em um só lugar e fomenta o trabalho em equipe, já que é possível compartilhar com outras pessoas.

Eu particularmente utilizo para (To-Do, Anotações, Roadmap, Kanban)

![Notion](/assets/img/fqu-notion.png)

***Devdocs.io***

Como desenvolvedor, leio muita documentação para poder resolver os problemas do dia a dia. O [Devdocs](https://devdocs.io/) é um "repositório" que reune a documentação de praticamente todas as linguages ou tecnologias utilizadas mundo a fora. E a documentação que não está disponível nessa plataforma, tem o link que te leva a documentação oficial.

![Devdocs](/assets/img/fqu-devdocs.png)

Bom praticamente essas são as principais ferramentas que utilizo, se você tem alguma sugestão ou conhece alguma outra ferramenta bacana, indica também nos comentários.

Se tiver dúvidas, elogios, sugestões, deixe seu comentário. Se também curtiu o conteúdo, compartilhe com os seus amigos.

Até a próxima!
<file_sep>import React from 'react';
import { Link } from 'gatsby';

import * as S from './styled';
import image from '../../images/not-found.svg';

const PageNotFound = () => (
  <S.Container>
    <S.Header>

Página não encontrada

    </S.Header>
    <S.Body>

          Parece que você se perdeu, clique
          {' '}
          <Link to="/">aqui</Link>
          {' '}
          para voltar ao inicio

    </S.Body>
  </S.Container>
);

export default PageNotFound;
<file_sep>import styled from 'styled-components';

export const Container = styled.div`
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
`;

export const Header = styled.header`
    padding: 30px;
    text-align: center;
    width: 100%;
    background: var(--mediumBackground);

    h1 {
        font-size: 3em;
        color: var(--texts);
    }

`;

export const Body = styled.div`
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;

    img {
        width: 500px;
        height: 500px;
    }

    div {
        p {
            color: var(--texts);
            font-size: 1.5em;

            a {
                color: var(--texts);
                font-weight: 700;
                text-decoration: none;
                transition: color 0.5s;
                &:hover {
                    color: var(--highlight);
                }
            }
        }
    }
`;
<file_sep>---
title: Salvando alterações locais com o DevTools do browser
description: Como salvar mudanças no CSS ou HTML direto na sua máquina usando DevTools
date: 2020-05-13T03:22:29.000Z
image: assets/img/chrome-devtools.jpg
category: Misc
background: '#7AAB13'
keywords: 'devtools;browser;chrome;firefox'
---

Muitas vezes na hora de desenvolver um site ou uma página web, nos deparamos com a necessidade de testar algumas mudanças em propriedades **CSS**, código **HTML** ou inclusive no **Javascript** para validar rapidamente uma mudança.

Para isto podemos usar o **DevTools** no [Google Chrome](https://developers.google.com/web/tools/chrome-devtools) ou no [Mozilla Firefox](https://developer.mozilla.org/pt-BR/docs/Tools).

Esta ferramenta que vem junto com os browsers modernos, são uma "mão na roda" para os desenvolvedores na hora de analisar, criar, validar funcionalidades e comportamentos de HTML, CSS e Javascript nas páginas web.

Neste post, vou focar somente na alteração de propriedades CSS em arquivos locais e como salvar as mesmas diretamente do browser, sem necessidade de abrir o código fonte no seu editor favorito.

### _Isto somente funciona em arquivos locais da sua máquina, não é possível alterar CSS/HTML/Javascript de sites remotos_

# Google Chrome

Realizar alterações no Google Chrome pode parecer um pouco "complicado", mas não realidade não é, então vamos ao passo a passo.

## 1. Inclua os arquivos locais no workspace do navegador

No Google Chrome é necessário incluir o diretório com os arquivos do seu projeto web no workspace do navegador. Para isto abra o DevTools e na aba _"Sources"_ clique em _"Add folder to workspace"_

![](/assets/img/gasakawa-devtools-chrome-workspace.png)

O navegador, vai solicitar acesso ao diretório que deseja incluir. Uma vez liberado o acesso os diretórios e arquivos devem aparecer no workspace

![](/assets/img/gasakawa-devtools-ask-permissions.png)

![](/assets/img/gasakawa-devtools-workspace-added.png)

## 2. Selecione o elemento HTML para editar o seu estilo.

![](/assets/img/gasakawa-devtools-element.png)

## 3. Edite o CSS na aba _"Styles"_

Esta forma é mais simples é deve ser a mais utilizada pelos desenvolvedores (pelo menos é a que eu mais utilizo) ;)

![](/assets/img/gasakawa-devtools-chrome-css-change.png)

## 4. Visualize e salve as alterações

As alterações são percebidas automaticamente na tela a cada mudança no código, mas é possível visualizar as alterações no código também, (como se fosse o git).

![](/assets/img/gasakawa-devtools-local-modifications.png)

Note que os arquivos alterados ficam com um asterisco (\*) do lado esquerdo, então se clicar na opção _"Local modifications..."_, habilita uma nova aba chamada _"Changes"_, onde é possível visualizar as alterações feitas em todos os arquivos do workspace.

![](/assets/img/gasakawa-dev-tools-changes.png)

Salve as mudanças com Ctrl + S e pronto as alterações serão refletidas no seu filesystem diretamente.

# Mozilla Firefox

Realizar estas alterações locais no Firefox é muito mais simples, vamos ver o passo a passo.

## 1. Selecione o elemento HTML para editar o seu estilo.

![](/assets/img/gasakawa-devtools-firefox-element.png)

## 2. Edite o CSS

![](/assets/img/gasakawa-devtools-firefox-css-change.png)

Note que na propriedade do CSS que foi feita a alteraçao, fica uma marca da cor verde do lado esquerdo. Esta é a forma com a qual o Firefox sinaliza as alterações.

## 3. Salve as alterações

Salvar as alterações é muito simples, basta clicar na aba _"Editor de estilos"_ e na sequência clicar em _"Save"_ do lado de cada arquivo que foi modificado.

![](/assets/img/gasakawa-devtools-firefox-save.png)

# Conclusão

Editar CSS diretamente no navegador facilita muito a validação das alterações, poder salvar diretamente do navegador estas alterações no nosso computador local agiliza um pouco o desenvolvimento.

Se tiver dúvidas, elogios, sugestões, deixe seu comentário. Se também curtiu o conteúdo, compartilhe com os seus amigos.
<file_sep>---

date: 2020-09-18 00:00:00
title: Otimizando imagens com NodeJS
description: Como otimizar imagens utilizando a lib sharp
category: JS
background: '#F0D91D'
image: 'assets/img/compactar-imagem.png'
keywords: 'javascript;nodejs'
---

Estava fazendo um projeto pessoal e me deparei com a necessidade de otimizar o tamanho das imagens que precisava utilizar. Existem vários serviços online para isto, (redimensionar, cortar, reduzir peso, etc). Porém encontrei uma lib javascript bastante interessante. O nome dela é [sharp](https://github.com/lovell/sharp) e quero compartilhar com vocês como resolvi o meu problema.

O código é bem simples porém poderoso :), (pode clonar ele do [Github](https://github.com/gasakawa/image-compress)).

```javascript
require('dotenv/config');
const sharp = require('sharp');
const fs = require('fs').promises;

const compress = async () => {
  const directory = await fs.readdir(process.env.SRC_FOLDER);

  const pattern = new RegExp('^.*.(jpg|JPG|gif|GIF|png|PNG)$');

  const files = directory.filter(file => pattern.test(file));

  if (files.length > 0) {
  // O `async`/ `await` não funciona nas funções do Array, então é necessário utilizar `await Promise.all`, porque a função da lib `sharp` que será utilizada retorna uma promise.
    await Promise.all(
      files.map(async file => {
        const content = await fs.readFile(`${process.env.SRC_FOLDER}/${file}`);
        const compressContent = await sharp(content)
          .resize(Number(process.env.WIDTH), Number(process.env.HEIGHT), {
            fit: 'inside',
            withoutEnlargement: true,
          })
          .toFormat('jpeg', {
            progressive: true,
            quality: 90,
          })
          .toBuffer();

        await fs.writeFile(
          `${process.env.DEST_FOLDER}/${file}`,
          compressContent
        );
      })
    );
  }
};

compress();

```

*Bora explicar ele então?*

```javascript
require('dotenv/config');
const sharp = require('sharp');
const fs = require('fs').promises;
```

- `require('dotenv/config')`, como utilizo algumas variáveis de ambiente para deixar mais customizado, a lib dotenv vai carregar as variáveis de ambiente do arquivo `.env`, para poder acessá-las utilizando `process.env.NOME_VARIAVEL`.
- `const sharp = require('sharp')` importo a lib `sharp`
- `const fs = require('fs').promises` o `fs` já vem nativamente com o node, então aqui utilizo `promises` para poder utilizar o `async` / `await` e não os `callbacks` tradicionais.

A função `compress` é a que faz o trabalho sujo, então vamos ver como ela funciona.

```javascript
const directory = await fs.readdir(process.env.SRC_FOLDER);
const pattern = new RegExp('^.*.(jpg|JPG|gif|GIF|png|PNG)$');
const files = directory.filter(file => pattern.test(file));
```

- `const directory = await fs.readdir(process.env.SRC_FOLDER)`  aqui vamos ler o diretório especificado na variável de ambiente `SRC_FOLDER` que é onde devem estar as imágens "grandes" a serem otimizadas.
- `const pattern = new RegExp('^.*.(jpg|JPG|gif|GIF|png|PNG)$')` somente quero imagens `jpg`, `gif`, ou `png`. (Pode adicionar outras extensões se desejar).
- `const files = directory.filter(file => pattern.test(file))` no diretório podem existir outros tipos de arquivos além de imágens, então filtro os arquivos de acordo às extensões que realmente quero tratar.

Aqui usamos as funções da lib `sharp`

```javascript
const compressContent = await sharp(content)
.resize(Number(process.env.WIDTH), Number(process.env.HEIGHT), {
    fit: 'inside',
    withoutEnlargement: true,
})
.toFormat('jpeg', {
    progressive: true,
    quality: 90,
})
.toBuffer();
```

- `resize`, redemensiona o tamanho da imágem, aqui pode usar o tamanho definido nas variáveis de ambiente.
- `toFormat`, converte a imagem em `jpg` sempre.
- `toBuffer` , retorna o conteúdo da imágem em um `Buffer`.

### Exemplo

Imagem antes de ser otimizada.

![Imágem antes de Otimizar](/assets/img/tamanho-imagens-antes-optimizar.png)

Imagem depois de ser otimizada.

![Imágem antes de Otimizar](/assets/img/tamanho-imagens-apos-optimizar.png)

Bom é isso ai pessoal, espero que ajude se você tem uma necessidade parecida. Se tiver dúvidas, elogios, sugestões, deixe seu comentário. Se também curtiu o conteúdo, compartilhe com os seus amigos.

Até a próxima!

<file_sep>const links = [
  {
    label: 'Github',
    url: 'https://github.com/gasakawa',
  },
  {
    label: 'Twitter',
    url: 'https://twitter.com/GabrielAsakawa',
  },
  {
    label: 'Instagram',
    url: 'https://instagram.com/gasakawa',
  },
  {
    label: 'Facebook',
    url: 'https://www.facebook.com/gabriel.asakawa',
  },
  {
    label: 'Linkedin',
    url: 'https://www.linkedin.com/in/gabriel-asakawa',
  },
];

export default links;
<file_sep>// Add your keys here and rename the file to `.env`

GATSBY_ALGOLIA_APP_ID=XXX
ALGOLIA_ADMIN_KEY=XXX
GATSBY_ALGOLIA_SEARCH_KEY=
GATSBY_ALGOLIA_INDEX_NAME=XXX

GA_TRACKING_ID=Your GA Tracking ID<file_sep>---
title: Desestruturação de objetos e arrays em Javascript
description: Como usar a desestruturação em Javascript
date: 2020-05-19T03:22:29.000Z
image: assets/img/javascript.png
category: JS
background: '#F0D91D'
keywords: 'javascript'
---

A sintaxe da atribuição via desestruturação é uma expressão JavaScript que possibilita descompactar valores de arrays ou propriedades de objetos em variáveis distintas. Isto significa, que podemos extrair dados de arrays ou objetos, e atribuir estes dados à variáveis.

Você pode ser perguntar, *para que vou fazer isso*? *ou como isso me ajuda*? Bom para responder sua pergunta, vamos ver os exemplos abaixo.

## Desestruturando Arrays

```javascript
const lista = ['Gabriel', 'Asakawa', 'Brasil']
const nome = lista[0] // Gabriel
const sobrenome = lista[1] // Asakawa
const pais = lista[2] // Brasil

console.log(nome, sobrenome, pais) // <NAME> Brasil

```

No código acima, usei uma forma de extrair elementos de um array que funciona e era muito utilizada, porém veja que devo indicar a posição de cada elemento do array em uma linha diferente. Isto torna o código mais verboso.

Utilizando a desestrutração o código pode ser reduzido, veja algums cenários.

### Básico

```javascript
const lista = ['Gabriel', 'Asakawa', 'Brasil']
const [nome, sobrenome, pais] = lista

console.log(nome, sobrenome, pais) // <NAME> Brasil
```

Utilizando a funcionalidade de desestrutração do JS, o código tem menos linhas e é mais fácil de ler.

### Pulando elementos do array

```javascript
const lista = ['Gabriel', 'Asakawa', 'Brasil', 'São Paulo']
const [nome, , pais, estado] = lista

console.log(nome, pais, estado) // <NAME>il São Paulo
```

Veja que o array que recebe a atribuição tem uma vírgula sobrando. Na verdade não está sobrando, ela representa a posição do elemento do array que não queriamos extrair (que foi pulado).

### Valores default

Podemos atribuir um valor default a uma variável, no caso em que o valor extraído do array é *undefined*.

```javascript
const [a, b = 7] = [1]

console(a, b) // 1 7
```

### Usando o operador (...)

Quando é necessário atribuir a uma variável um elemento do array e a outra variável o resto dos elementos do mesmo array, podemos utilizar o operador **(...)**.

```javascript
const lista = ['Gabriel', 'Pai', 'Desenvolvedor', 'Nerd']
const [nome, ...outros] = lista

console.log(nome) // Gabriel
console.log(outros) // ['Pai', 'Desenvolvedor', 'Nerd']
```

## Desestruturando Objetos

A desestrutração de um objeto é similar à do array, a diferença é o uso de chaves **{ }** no lugar de colchetes **[ ]**.

```javascript
const pessoa = {
    nome: 'Gabriel',
    sobrenome: 'Asakawa',
    pais: 'Brasil'
}
const nome = pessoa.nome // Gabriel
const sobrenome = pessoa.sobrenome // Asakawa
const pais = pessoa.pais // Brasil

console.log(nome, sobrenome, pais) // <NAME> Brasil
```

No código acima, usei uma forma de extrair elementos de um objeto que funciona bem, mas o código é verboso e repetitivo. Então mais uma vez podemos utilizar a desestrutração e o código pode ser reduzido, veja algums cenários.

### Básico

```javascript
const pessoa = {
    nome: 'Gabriel',
    sobrenome: 'Asakawa',
    pais: 'Brasil'
}
// correto
const {nome, sobrenome, pais} = pessoa
console.log(nome, sobrenome, pais) // <NAME> Brasil

// incorreto
const {nome, sobre, pais} = pessoa
console.log(nome, sobre, pais) // Gabriel undefined Brasil
```

Na desestrutração de objetos direta, o nome da variável que irá receber o valor da propriedade do objeto, **deve** ser igual ao nome da propriedade do objeto. Caso contrário a atribuição do valor não será feita.

### Objetos aninhados

```javascript
const pessoa = {
    nome: 'Gabriel',
    sobrenome: 'Asakawa',
    pais: 'Brasil',
    endereco : {
        rua: 'Av Paulista',
        cep: '00000-000'
    }
}
const {nome, sobrenome, endereco: {rua, cep}} = pessoa

console.log(nome, sobrenome, rua, cep) // <NAME> Av. Paulista 00000-000
```

### Nomes de variáveis diferentes

Como falei antes, na hora de desestrutrar um objeto de forma direta, o nome da variável que irá receber o valor da proprieade do objeto deve ser igual, porém é possível usar outro nome de variável caso seja necessário.

```javascript
const pessoa = {
    nome: 'Gabriel',
    sobrenome: 'Asakawa',
    pais: 'Brasil'
}
const {nome, sobrenome: lastname} = pessoa

console.log(nome, lastname) // <NAME>
```

Outro casos de uso, podem ser vistos [aqui](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment).

### Conclusão

Utilizar a desestrutração, ajuda a reduzir linhas de código e permite que o código seja mais legível. Além disso é possível também extrair somente os dados de um array ou objeto, que realmente são necessários naquele momento.

Se tiver dúvidas, elogios, sugestões, deixe seu comentário. Se também curtiu o conteúdo, compartilhe com os seus amigos.
<file_sep>import {
  Github,
  Twitter,
  Facebook,
  Instagram,
  Linkedin,
} from 'styled-icons/boxicons-logos';

const Icons = {
  Github,
  Twitter,
  Facebook,
  Instagram,
  Linkedin,
};

export default Icons;
<file_sep>import ReactGA from 'react-ga';

export const searchClickTrack = () => {
  ReactGA.event({
    category: 'search',
    action: 'click',
    label: 'Search no Menu Bar',
  });
};

export const themeTrack = theme => {
  ReactGA.event({
    category: 'theme',
    action: 'view',
    label: `Usa ${theme} theme`,
    nonInteraction: true,
  });
};

export const topClickTrack = () => {
  ReactGA.event({
    category: 'top',
    action: 'click',
    label: 'Top na Menu Bar',
  });
};

export const displayTrack = display => {
  ReactGA.event({
    category: 'display',
    action: 'view',
    label: `Usa ${display} display`,
  });
};
<file_sep>import React from 'react';
import { Github } from '@styled-icons/boxicons-logos/Github';

import * as S from './styled';

const About = () => (
  <S.AboutWrapper>

Sobre mim

      Meu nome é <NAME>, nasci em Angola / África, minha mãe brasileira
      descendente de japoneses e o meu pai africano e para adicionar, me criei
      na Colômbia. Sim isso mesmo, como meus amigos na faculdade falavam eu
      praticamente sou a ONU.

      Me formei em 2008 em Engenharia de Sistemas e Computação na Universidad
      del Valle (Cali - Colômbia)

      Meu primeiro contato com computação foi ainda no Colégio (1999), na aula
      de informática aprendiamos linguagem C. Na época não me interessava tanto,
      porque na verdade eu queria ser Médico, computação era minha segunda
      opção. Mas o destino me levou a estudar computação e já se fazem mais de
      16 anos brincando com máquinas.

      Hoje atúo como Tech Lead na empresa

        Stefanini Scala

        e já trabalhei em empresas como

        HabberTec

      ,

        GFT

Habilidades / Experiências

      Durante meus anos de experiência trabalhei com algumas linguagens de
      programação, tecnologias e sistemas operacionais

Lingugem C, C++

PHP

Java

Javascript

NodeJS

ReactJS

Automatizadores (Webpack, Grunt)

        IBM (Webpshere Application Server, Business Process Manager, Operational
        Decision Manager, Integration Bus, MobileFirst)

CSS Frameworks (Bootstrap)

Shell Script

Linux, Windows

REST, GraphQL

  </S.AboutWrapper>
);

export default About;
<file_sep>---
date: 2020-04-27 00:00:00
title: Meu primeiro post
description: Seja bem-vindo
category: Misc
background: '#7AAB13'
image: ''
keywords: ''
---

# O que esperar deste blog?

Venho ~~enrolando~~ planejando este blog há pelo menos uns 5 anos :), porém pensei demais para realmente começar a escrever nele. Talvez fosse preguiça, não saber o que escrever, nunca ter feito, em fim, não sei ao certo o porquê, mas cá estamos e desta vez tenho certeza que vai.

Vou tentar juntar algumas das minhas paixões (tecnologia, programação, video game, basquete e música, etc) neste espaço e compartilhar um pouco do conhecimento e experiência que adquiri na carreira profissional, que com certeza irá ajudar alguém de alguma forma.

> "Ensinar é aprender duas vezes" -- <NAME>

Não sou o dono da verdade, e espero que você curta e compartilhe o conteúdo que será criado aqui e o mais importante é que deixe o seu feedback ou sugestão. _**Seja muito bem vindo**_.

branch_name: refs/heads/master

languages: Markdown Shell JavaScript

repo_language: Markdown

repo_name: gasakawa/blog


text:
<file_sep>import React, {useState, useEffect} from "react";
import { getTodayData, getAnimalsData } from '../api'
import { TodayItem } from './TodayItem'
import {Preloader} from '../layout/Preloader';
import { useDispatch } from 'react-redux';
import { addTodayData, toggleTodayReady, toggleTodayError, toggleLoading, addAnimalsData, addNextPage } from '../actions'

export const TodayList = (data) => {
  const dispatch = useDispatch();
  const { todayData, todayReady, todayError, loading, nextPage } = data.state;

  useEffect(()=> {
    dispatch(toggleLoading(true));
    if (!todayData.length) {
      getTodayData()
      .then(response=> {
          dispatch(addTodayData(response.data.results));
      })
      . then((data)=>{
            dispatch(toggleTodayReady(true));
            dispatch(toggleLoading(false));
          })
        .catch(e=>{
          dispatch(toggleLoading(false));
          dispatch(toggleTodayError(true));
          window.location.assign('/login')
        });
      getAnimalsData()
      .then(response=> {
          dispatch(addAnimalsData(response.data.results));
          dispatch(addNextPage(response.data.next))
      })

    }
    dispatch(toggleLoading(false));
}, [todayReady]);
return (

    {todayError ? (
Sorry, something went wrong, please try again later.
):(
      loading ? <Preloader /> :  (

Назначения на сегодня:

        {todayData.map((item, i) => {return <TodayItem key={i} item={item}/>})}

    ))}

)
}

<file_sep>import { connect } from 'react-redux';
import { addAnimalsData, addNextPage } from '../actions/index';
import { AnimalsList } from '../components/AnimalsList'

const mapStateToProps = (state) => {
    return { state:state }
}
const MapDispatchToProps = (dispatch) => {
    return {
        addAnimalsData: (animalsData) => dispatch(addAnimalsData(animalsData)),
        addNextPage: (nextPage) => dispatch(addNextPage(nextPage))
    }
}

export default connect(
    mapStateToProps,
    MapDispatchToProps
)(AnimalsList);
<file_sep>
Test --- Animal Shelter

### Description
Animal Shelter is a SPA implemented on React Redux.

<file_sep>import React, {useState, useEffect} from "react";
import { auth, getTodayData } from '../api'
import { useDispatch } from 'react-redux';
import { toggleLoginError, toggleLoginReady} from '../actions'

export const LoginForm = (data) => {
  const { loginError, loginReady } = data.state;
  const [login, setLogin] = useState('test_user_1')
  const [password, setPassword] = useState('<PASSWORD>')
  const dispatch = useDispatch();

  const handleChange = (e) => {
    setLogin(e.target.value)
  }

  const handleSendForm = (e) => {
    e.preventDefault()
    if (login.length > 0 || password.length > 0) {
      auth(login, password)
        .then((response) => {
          localStorage.setItem('access', response.data.access);
          window.location.assign('/today');
        })
        .catch((error) => {
              dispatch(toggleLoginError(true));
              console.log('Имя пользователя или пароль введены не верно')
            }
        );
    }
  }
  useEffect(() => {
    if (!loginReady) {
      dispatch(toggleLoginError(true));
    } else {
      dispatch(toggleLoginReady(false));
    }
  }, [loginError])

//   username: 'test_user_1',
// password: '<PASSWORD>'

  return (

Авторизация

      <form className="s12" action='post'>

            <input
              type="text"
              placeholder='Login'
              id='login'
              onChange={handleChange}
              value='test_user_1'
            />

            <input
              id="password"
              type="password"
              data-length="30"
              value='user10000'
              placeholder='Password'
              onChange={e => {
                setPassword(e.target.value)
                dispatch(toggleLoginError(false))
              }}
            />

          {loginError ?
Имя пользователя или пароль введены не верно
 : ''}
        <button className="waves-effect waves-light btn red lighten-1 " onClick={handleSendForm}>Войти</button>

      </form>

  );
}<file_sep>const initialState = {
    loginError: false,
    loginReady: true,
    animalsData: [],
    todayData: [],
    todayReady: false,
    todayError: false,
    loading: false,
    nextPage: '',
    animalCardData: {name: '',
                    animal_attributes: [
                        {value: ''},
                        {value: ''},
                        {value: ''},
                        {value: ''},
                    ]
                },
}

export default initialState;<file_sep>export const toggleLoginError = (loginError) => ({
    type: 'LOGIN_ERROR',
    loginError
})
export const toggleTodayError = (todayError) => ({
    type: 'TODAY_ERROR',
    todayError
})
export const toggleLoading = (loading) => ({
    type: 'TOGGLE_LOADING',
    loading
})
export const toggleLoginReady = (loginReady) => ({
    type: 'LOGIN_READY',
    loginReady
})
export const addTodayData = (todayData) => ({
    type: 'GET_TODAY_DATA',
    todayData
})
export const addAnimalsData = (animalsData) => ({
    type: 'GET_ANIMALS_DATA',
    animalsData
})
export const toggleTodayReady = (todayReady) => ({
    type: 'TOGGLE_TODAY_READY',
    todayReady
})

export const addNextPage = (nextPage) => ({
    type: 'CREATE_NEXT_PAGE',
    nextPage
})
export const addAnimalCardData = (animalCardData) => ({
    type: 'CREATE_ANIMAL_DATA',
    animalCardData
})<file_sep>import { Route, Switch } from 'react-router-dom';
import { Header} from './layout/Header';
import { Footer} from './layout/Footer';
import { Home } from './page/Home';
import Login from './page/Login';
import Today from './page/Today';
import Animal from './page/Animal';
import Animals from './page/Animals';
import { NotFound } from './page/NotFound';
import { BrowserRouter } from 'react-router-dom';

import './index.css';

const App = () => {
    return <>
        <BrowserRouter basename='/'>

            <Switch>
                <Route exact path="/" component={Home}/>
                <Route exact path="/login" component={Login}/>
                <Route exact path="/today" component={Today}/>
                <Route exact path="/animals" component={Animals}/>
                <Route exact path="/animal/animalCard/:id" component={Animal}/>
                <Route component={NotFound}/>
            </Switch>

        </BrowserRouter>
    </>
}

export default App;
<file_sep>import { Link } from 'react-router-dom';

export const AnimalsItem = (item) =>{
    const linkId = `animal/animalCard/${item.item.id}`;

    return (

              <Link to={linkId} className='hover'>
                {item.item.name}
              </Link>

Порода: {item.item.spec_parent_name}

Тип: {item.item.spec_name}

    );
}

<file_sep>import {useEffect, useState} from 'react';
import {useParams, useHistory } from 'react-router-dom';
import { getAnimalCartData } from '../api';
import {Preloader} from '../layout/Preloader';
import { addAnimalCardData, toggleLoading } from '../actions';

import {useDispatch} from 'react-redux';

export const  AnimalCard = (data) => {
    const dispatch = useDispatch();
    const { id } = useParams();
    const { animalCardData, loading } = data.state
    const {goBack} = useHistory();

    useEffect(()=> {
        dispatch(toggleLoading(true));

        getAnimalCartData(id)
        .then(response=> {
            if (response.data.animal_attributes[1]) {
                dispatch(addAnimalCardData(response.data));
            } else {
                let arr = {
                    name: response.data.name,
                    animal_attributes: [
                        {value: 'нет информации'},
                        {value: 'нет информации'},
                        {value: response.data.animal_attributes[0].value},
                        {value: 'нет информации'},
                    ]
                }
                console.log(arr)
                dispatch(addAnimalCardData(arr));
            }
            console.log(animalCardData)
            dispatch(toggleLoading(false));

        })
        // .catch(()=>{
        //     window.location.assign('/login')
        //   });
    }, []);

    return (
        loading ? <Preloader /> : (

                {animalCardData.name}

Рост: {animalCardData.animal_attributes[0].value}

Вес: {animalCardData.animal_attributes[1].value}

Пол: {animalCardData.animal_attributes[2].value}

Цвет: {animalCardData.animal_attributes[3].value}

Тип: {animalCardData.spec_parent_name}

Подтип: {animalCardData.spec_name}

             {e.preventDefault(); goBack()}}>Вернуться

        )

    )
}<file_sep>import React, {useState, useEffect} from "react";
import {Preloader} from '../layout/Preloader';
import { useDispatch } from 'react-redux';
import { getAnimalsData } from '../api'
import {  addAnimalsData, addNextPage, toggleLoading } from '../actions'
import { AnimalsItem } from "./AnimalsItem";

export const AnimalsList = (data) => {
  const dispatch = useDispatch();
  const { animalsData, nextPage, loading } = data.state;

  useEffect(()=> {
    dispatch(toggleLoading(true));

    if (animalsData.length < 1) {
      getAnimalsData()
      .then(response=> {
          dispatch(addAnimalsData(response.data.results));
          dispatch(toggleLoading(false));
      })
      .catch(error => {
        console.log(error)
        window.location.assign('/login')
      })
    }
    dispatch(toggleLoading(false));
}, []);
const handleClick = () => {
  getAnimalsData(nextPage.slice(15))
  .then(response=> {
    dispatch(addAnimalsData([...animalsData, ...response.data.results]));
    dispatch(addNextPage(response.data.next))
  })
}
return (

    {!animalsData ? (<Preloader />):(

Животные в приюте:

        {loading ? <Preloader /> : (<>{animalsData.map((item, i) => {return <AnimalsItem key={i} item={item}/>})}
        <button className="waves-effect waves-light btn red lighten-1 " onClick={handleClick}>ПОказать больше</button></>)}

    )}

)
}

<file_sep>export const NotFound = () => {
    return
The page is not found

}
<file_sep>import { Link } from 'react-router-dom';

export const TodayItem = (item) =>{
    const linkId = `animal/animalCard/${item.item.animal.id}`;

    return (

              <Link to={linkId}>
                {item.item.animal.name}
              </Link>

Порода: {item.item.animal.spec_name}

Назначение: {item.item.my_type}

Препараты:

Название: {item.item.drugs[0].drug_name}

Доза: {item.item.drugs[0].drug_dosage} {item.item.drugs[0].form_of_drug}

    );
}

<file_sep>import { Link } from 'react-router-dom';

export const Header = () => {
    return (

                    <Link to='/animals' className="brand-logo left cursor">Приют №1</Link>

                        <Link to='/today' className='cursor' id='mob-dn'>Назначения на сегодня</Link>

    )
}

<file_sep>export const Home = () => {
    window.location.assign('/login');
}

branch_name: refs/heads/main

languages: Markdown JavaScript


text:
<file_sep>// ANTHONY
$(document).ready(function () {
    $('h1').addClass('text-center');
    $('h2').addClass('text-center');
    $('.myBannerHeading').addClass('class page-header');
    $('.myBannerHeading').removeClass('myBannerHeading');
    $('#yellowHeading').text("Yellow Team");

    $('#orangeTeamList').css('background-color','orange');
    $('#blueTeamList').css('background-color', 'blue');
    $('#redTeamList').css('background-color', 'red');
    $('#yellowTeamList').css('background-color', 'yellow');

    $("#yellowTeamList").append('
Joseph Banks
');
    $("#yellowTeamList").append('
<NAME>
');

    $("#oops").hide();
    $("#footerPlaceholder").remove();

    $("#footer").css('font-family','Courier');
    $("#footer").css('height','24')
    $("#footer").append('
<NAME>
');
    $("#footer").append('
<EMAIL>
');
});

repo_language: JavaScript


text:
<repo_name>prrat/blogPro<file_sep>/App/urls.py
from . import views
from django.urls import path
from .feeds import LatestPostsFeed
from django.conf import settings #add this
from django.conf.urls.static import static #add this

urlpatterns = [
    path('', views.PostList.as_view(), name='home'),
    path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
    path("feed/rss", LatestPostsFeed(), name="post_feed"),
    path("upload", views.upload, name="upload"),
    path('signup', views.signup, name='signup'), #added
    path('contact', views.contact, name='contact'),
    path('currency', views.currency, name='currency'),
    path('signup', views.signup, name='signup'), #added
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)<file_sep>/App/forms.py
from .models import Comment
from django import forms
from .models import *
from django.contrib.auth.forms import UserCreationForm

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('name', 'email', 'body')

class SignUpForm(UserCreationForm):
    class Meta:
        model = User
        fields = ('username', '<PASSWORD>', '<PASSWORD>', )

class ContactForm(forms.Form):
    from_email = forms.EmailField(required=True)
    subject = forms.CharField(required=True)
    message = forms.CharField(widget=forms.Textarea, required=True)

class ImageForm(forms.ModelForm):
    '''Form for the image model'''
    class Meta:
        model = Image
        fields = ('title', 'image')<file_sep>/App/views.py
from django.shortcuts import render, get_object_or_404
from .models import Post
from django.views import generic
from .models import Post
from .forms import CommentForm
from django.core.files.storage import FileSystemStorage
from .forms import SignUpForm
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from .forms import ContactForm

# Create your views here.

class PostList(generic.ListView):
    queryset = Post.objects.filter(status=1).order_by('-created_on')
    template_name = 'index.html'
    paginate_by = 3

class PostDetail(generic.DetailView):
    model = Post
    template_name = 'post_detail.html'

    def post_detail(request, slug):

        template_name = 'post_detail.html'
        post = get_object_or_404(Post, slug=slug)
        comments = post.comments.filter(active=True)
        new_comment = None
        # Comment posted
        if request.method == 'POST':
            comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            # Create Comment object but don't save to database yet
            new_comment = comment_form.save(commit=False)
            # Assign the current post to the comment
            new_comment.post = post
            # Save the comment to the database
            new_comment.save()
        else:
            comment_form = CommentForm()

        return render(request, template_name, {'post': post,
                                            'comments': comments,
                                           'new_comment': new_comment,'comment_form': comment_form})
def currency(request):
      template = 'currency.html'
      return render(request, template)

def upload(request):
    if request.method == 'POST' and request.FILES['upload']:
        upload = request.FILES['upload']
        fss = FileSystemStorage()
        file = fss.save(upload.name, upload)
        file_url = fss.url(file)
        return render(request, 'upload.html', {'file_url': file_url})
    return render(request, 'upload.html')

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()
            # load the profile instance created by the signal
            user.save()
            raw_password = form.cleaned_data.get('password1')

            # login user after signing up
            user = authenticate(username=user.username, password=<PASSWORD>)
            login(request, user)

            # redirect user to home page
            return redirect('home')
    else:
        form = SignUpForm()
    return render(request, 'signup.html', {'form': form})

def contact(request):
    return render(request, 'contact.html')

# def base(request):
#       template1 = 'base.html'
#       return render(request, template1)

# def post_detail(request):
#       template2 = 'post_detail.html'
#       return render(request, template2)

# def sidebar(request):
#       template3 = 'sidebar.html'
#       return render(request, template3)

repo_language: Python

repo_name: prrat/blogPro


text:
<file_sep>#include "BinaryTree.h"

BiTreeNode* CreateTreeNode(int value)
{
    BiTreeNode *pNode = new BiTreeNode;
    pNode->val = value;
    return pNode;
}

void findMax(BiTreeNode *root, unordered_map<int, int> &hashTable, int &max)
{
    if (root == nullptr)
    {
        if (max < hashTable.size())
            max = hashTable.size();
        return;
    }

    // If the key(root->val) has never been in the table, insert the key and set its mapped value to 1, otherwise increase its mapped value by 1
    if (hashTable.count(root->val) == 0)    // root
        hashTable[root->val] = 1;
    else
        hashTable[root->val]++;

    findMax(root->left, hashTable, max);    // left child
    findMax(root->right, hashTable, max);   // right child
    hashTable[root->val]--;
    if (hashTable[root->val] == 0)
    {
        hashTable.erase(root->val);
    }
}<file_sep>#include <algorithm>
#include <cmath>

using namespace std;
/*Lesson1 - BinaryGap
*A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
*
*For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two
*binary gaps : one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has
*binary representation 1111 and has no binary gaps.
*
*Write a function : int BinaryGap(int N);that, given a positive integer N, returns the length of its longest binary gap.The function should return 0 if N doesn't
*contain a binary gap.
*For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5.
*
*Assume that :N is an integer within the range[1..2, 147, 483, 647].
*Complexity :
*           expected worst - case time complexity is O(log(N));
*           expected worst - case space complexity is O(1).
*/
int BinaryGap(int N);

/*Lesson3 - FrogJmp
*A small frog wants to get to the other side of the road.The frog is currently located at position X and wants to get to a position greater than or equal to Y.The
*small frog always jumps a fixed distance, D.Count the minimal number of jumps that the small frog must perform to reach its target.
*
*Write a function :int FrogJmp(int X, int Y, int D);
*that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.
*
*For example, given:X = 10,Y = 85,D = 30,the function should return 3, because the frog will be positioned as follows :
*after the first jump, at position 10 + 30 = 40
*after the second jump, at position 10 + 30 + 30 = 70
*after the third jump, at position 10 + 30 + 30 + 30 = 100
*Assume that :
*    X, Y and D are integers within the range[1..1, 000, 000, 000];
*    X ¡Ü Y.
*Complexity:
*    expected worst - case time complexity is O(1);
*    expected worst - case space complexity is O(1).
*/
int FrogJmp(int X, int Y, int D);<file_sep>#include "ArrayFunc.h"
#include "Sort.h"
#include <unordered_map>

using namespace std;

vector<int> CyclicRotation(vector<int> &A, int K)
{
    if (A.empty()) { return A; }

    int i, j;
    for (i = 0; i < K; i++)
    {
        int temp = A.back();
        for (j = A.size() - 1; j > 0; j--)
        {
            A[j] = A[j - 1];
        }
        A[j] = temp;
    }
    return A;
}

int OddOccurrencesInArray(vector<int> &A)
{
    int ret = A[0];
    for (int i = 1; i < A.size(); i++)
    {
        ret = ret ^ A[i];
    }
    return ret;
}

int PermMissingElem(vector<int> &A)
{
    if (A.empty()) { return 1; }

    int sum = 0, arraySum = 0;
    sum = ((A.size() + 1)*(A.size() + 2)) >> 1; // The sum of arithmetic sequence "1,2,3,...,N+1"
    for (int i = 0; i < A.size(); i++)
    {
        arraySum += A[i];   // The sum of the array.
    }
    return sum - arraySum;
}

int TapeEquilibrium(vector<int> &A)
{
    int i, arraySum = 0, sum1, sum2;
    unsigned int minDiff = -1;
    for (i = 0; i < A.size(); i++)
    {
        arraySum += A[i];
    }

    sum1 = 0;
    sum2 = arraySum;
    for (i = 0; i < A.size()-1; i++)
    {
        sum1 = sum1 + A[i]; // The sum of the first part
        sum2 = sum2 - A[i]; // The sum of the second part
        if (minDiff > abs(sum1 - sum2))
        {
            minDiff = abs(sum1 - sum2);
        }
    }
    return minDiff;
}

// Solve it with Pigeonhole principle.There are N integers in the input.So for the first N + 1 positive
// integers, at least one of them must be missing.
int MissingInteger(vector<int> &A)
{
    const int len = A.size() + 1;
    vector<bool> buckets(len, false);
    // We only care about the first N + 1 positive integers.The status of integer i + 1 is in buckets[i].
    for (int i = 0; i < A.size(); i++)
    {
        if (A[i]>0 && A[i] <= len)
            buckets[A[i] - 1] = true;
    }

    // Find out the missing minimal positive integer.
    for (int i = 0; i < len; i++)
    {
        if (buckets[i] == false)
            return i + 1;
    }
    cout << "Should never be here." << endl;
    return -1;
}

// Permutation means A[i] must be in the scope of (1,...,N).
int PermCheck(vector<int> &A)
{
    const int len = A.size();
    vector<bool> buckets(len, false);
    for (int i = 0; i < A.size(); i++)
    {
        if (A[i] >= 1 && A[i] <= len)   // A[i] is within the range[1..1, 000, 000, 000], it used to handle integers that is larger than length.
            buckets[A[i] - 1] = true;
    }

    for (int i = 0; i < len; i++)
    {
        if (buckets[i] == false)
            return 0;
    }
    return 1;
}

int FrogRiverOne(int X, vector<int> &A)
{
    vector<int> pos(X, 1);
    int sum = X;        // The sum of 'pos' array
    for (int i = 0; i < A.size(); i++)
    {
        if (pos[A[i] - 1] == 1)
        {
            sum -= pos[A[i] - 1];
            pos[A[i] - 1] = 0;
        }
        if (sum == 0)   // The earliest time all position values within [1,...,X] appears
        {
            return i;
        }
    }

    cout << "The frog is never able to jump to the other side of the river!" << endl;
    return -1;
}

// Use lazy-write to improve the performance.When receiving the max_counter command, we record the current-max value,
// but do not change the list content.Only when we are going to return the list or increace a specific element, we will
// apply the stored value to the corresponding element(s).
vector<int> MaxCounters(int N, vector<int> &A)
{
    vector<int> counters(N, 0);
    int maxCounter  = 0;    // The current maximum value of any counter
    int lastCounter = 0;    // The used value in previous 'max counter command'
    for (int i = 0; i < A.size(); i++)
    {
        if (A[i] > N)   // A[i]=N+1,max counter command
        {   // Just record the current maximum value for later write
            lastCounter = maxCounter;
        }
        else
        {   // 1<=A[i]<=N, increase command
            counters[A[i] - 1] = max(counters[A[i] - 1], lastCounter);
            counters[A[i] - 1]++;
            maxCounter = max(counters[A[i] - 1], maxCounter);
        }
    }

    // Update element has never been used after previous 'max counter command'
    for (int i = 0; i < N; i++)
    {
        counters[i] = max(counters[i], lastCounter);
    }
    return counters;
}

int PassingCars(vector<int> &A)
{
    int sum = 0, pairsSum = 0;
    for (int i = 0; i < A.size(); i++)
    {
        sum += A[i];    // A[i] is either 0 or 1
    }

    for (int i = 0; i < A.size(); i++)
    {
        sum -= A[i];    // Calculate the sum of remaining elements by excluding current element
        if (A[i] == 0)  // Start from 0 to make pair with following 1 elements
        {
            pairsSum += sum;
        }
        if (pairsSum > 1000000000)
            return -1;
    }
    return pairsSum;
}

int CountDiv(int A, int B, int K)
{
    int lower = A, upper = B;
    if (A%K != 0)   // Find the first value after A that is divisible by K
    {
        lower = A - A%K + K;
    }
    if (B%K != 0)   // Find the last value before B that is divisible by K
    {
        upper = B - B%K;
    }

    if (lower > upper)
        return 0;
    else
        return (upper - lower) / K + 1;
}

// The key to solve this task is these two patterns :
// (1) There must be some slices, with length of two or three, having the minimal average value among all the slices.
// (2) And all the longer slices with minimal average are built up with these 2 - element and / or 3 - element small slices.
int MinAvgTwoSlice(vector<int> &A)
{
    float minAvgVal, avgSlice2, avgSlice3;
    int minAvgPos = 0;                  // The begin position of the first slice with mininal average
    minAvgVal = (A[0] + A[1]) / 2;      // The mininal average

    for (int i = 0; i < A.size()-2; i++)
    {
        // Try the next 2-element slice
        avgSlice2 = (float)(A[i] + A[i + 1]) / 2;
        if (avgSlice2 < minAvgVal)
        {
            minAvgVal = avgSlice2;
            minAvgPos = i;
        }

        // Try the next 3-element slice
        avgSlice3 = (float)(A[i] + A[i + 1] + A[i + 2]) / 3;
        if (avgSlice3 < minAvgVal)
        {
            minAvgVal = avgSlice3;
            minAvgPos = i;
        }
    }

    // Try the last 2-element slice
    avgSlice2 = (A[A.size() - 2] + A[A.size() - 1]) / 2;
    if (avgSlice2 < minAvgVal)
    {
        minAvgVal = avgSlice2;
        minAvgPos = A.size() - 2;
    }
    return minAvgPos;
}

vector<int> GenomicRangeQuery(string &S, vector<int> &P, vector<int> &Q)
{
    vector<int> lastSeenPos_A(S.size(), -1);
    vector<int> lastSeenPos_C(S.size(), -1);
    vector<int> lastSeenPos_G(S.size(), -1);
    vector<int> lastSeenPos_T(S.size(), -1);
    vector<int> ret(Q.size(), 0);

    // Record the last position on which was the genome (A, C, G, T) was seen
    for (int i = 0; i < S.size(); i++)
    {
        LastOcurrPos(lastSeenPos_A, S, 'A', i);
        LastOcurrPos(lastSeenPos_C, S, 'C', i);
        LastOcurrPos(lastSeenPos_G, S, 'G', i);
        LastOcurrPos(lastSeenPos_T, S, 'T', i);
    }

    // If the last seen genome position based on Q, is large equal than P,we have found the right candidate
    for (int i = 0; i < Q.size(); i++)
    {
        if (lastSeenPos_A[Q[i]] >= P[i])        // 'A':1
            ret[i] = 1;
        else if (lastSeenPos_C[Q[i]] >= P[i])   // 'C':2
            ret[i] = 2;
        else if (lastSeenPos_G[Q[i]] >= P[i])   // 'G':3
            ret[i] = 3;
        else if (lastSeenPos_T[Q[i]] >= P[i])   // 'T':4
            ret[i] = 4;
        else
            cout << "Should never be here." << endl;
    }
    return ret;
}

void LastOcurrPos(vector<int> &outPos, string &S, char c, int idx)
{
    if (S[idx] == c)
    {
        outPos[idx] = idx;
    }
    else if (idx > 0)
    {
        outPos[idx] = outPos[idx - 1];
    }
}

int Distinct(vector<int> &A)
{
    unordered_set<int> distinctVals(A.begin(), A.end());
    return distinctVals.size();
}

int MaxProductOfThree_Basic(vector<int> &A)
{
    if (A.size() == 3) { A[0] * A[1] * A[2]; }

    sort(A.begin(), A.end());

    if (A[0] >= 0 || A.back() <= 0)
    {
        return A[A.size() - 3] * A[A.size() - 2] * A[A.size() - 1];
    }
    else
    {
        if (A[0] * A[1] >= A[A.size() - 3] * A[A.size() - 2])
            return A[0] * A[1] * A.back();
        else
            return A[A.size() - 3] * A[A.size() - 2] * A[A.size() - 1];
    }
}
// Time complexity:O(N), space complexity:O(1)
int MaxProductOfThree_Special(vector<int> &A)
{
    if (A.size() == 3) { A[0] * A[1] * A[2]; }

    vector<int> mins(2, 1000), maxs(3, -1000);
    // Scan the array to get the two smallest elements and the three biggest elements
    for (int i = 0; i < A.size(); i++)
    {
        UpdateMins(mins, A[i]);
        UpdateMaxs(maxs, A[i]);
    }
    return max(mins[0] * mins[1] * maxs[2], maxs[0] * maxs[1] * maxs[2]);
}

void UpdateMins(vector<int> &mins, int val)
{   // Find minimal integer, shift down
    if (val < mins[0])
    {
        mins[1] = mins[0];  // The second smallest integer
        mins[0] = val;      // The smallest integer
    }
    else if (val < mins[1])
    {
        mins[1] = val;
    }
}

void UpdateMaxs(vector<int> &maxs, int val)
{   // Find maximal integer, shift down
    if (val > maxs[2])
    {
        maxs[0] = maxs[1];  // The third biggest integer
        maxs[1] = maxs[2];  // The second biggest integer
        maxs[2] = val;      // The biggest integer
    }
    else if (val > maxs[1])
    {
        maxs[0] = maxs[1];
        maxs[1] = val;
    }
    else if (val > maxs[0])
    {
        maxs[0] = val;
    }
}

// If we have any inequality holding for out-of-order elements, we MUST have AT LEAST an inequality holding for three consecutive elements.
// Reference:https://codesays.com/2014/solution-to-triangle-by-codility/
int Triangle(vector<int> &A)
{   // Handle with the special cases
    if (A.size() < 3) { return 0; }

    sort(A.begin(), A.end());

    for (int i = 0; i < A.size()-2; i++)
    {
        if (A[i] >= 0 && A[i] > A[i + 2] - A[i + 1])  // Beware of overflow
            return 1;
        // As we all know A[i + 1]<=A[i + 2], if A[i]<0
        // then A[i] + A[i + 1] < A[i + 2]
    }
    cout << "No triangular triplet is found." << endl;
    return 0;
}

bool LeftCompare(DiscLine d1, DiscLine d2)
{
    return (d1.left < d2.left);
}

// http://www.lucainvernizzi.net/blog/2014/11/21/codility-beta-challenge-number-of-disc-intersections/
int NumberOfDiscIntersections_Basic(vector<int> &A)
{
    if (A.size() < 2) { return 0; }

    int interCnt = 0, len = A.size();
    vector<DiscLine> discs(len);
    for (int i = 0; i < len; i++)
    {
        discs[i].left  = (long long)i - (long long)A[i];
        discs[i].right = (long long)i + (long long)A[i];
    }

    sort(discs.begin(), discs.end(), LeftCompare);

    for (int i = 0; i < len; i++)
    {
        for (int j = i-1; j >= 0; j--)
        {
            if (discs[i].left <= discs[j].right)
                interCnt++;
        }
    }
    return interCnt;
}

// https://stackoverflow.com/questions/4801242/algorithm-to-calculate-number-of-intersecting-discs
int NumberOfDiscIntersections_Special(vector<int> &A)
{
    int interCnt = 0, len = A.size();
    vector<int> sPoints(len, 0), ePoints(len, 0);

    int sIdx, eIdx, t = 0;
    for (int i = 0; i < len; i++)
    {
        sIdx = (i - A[i] > 0) ? (i - A[i]) : 0;
        eIdx = (i + A[i] < len - 1) ? (i + A[i]) : (len - 1);
        sPoints[sIdx]++;
        ePoints[eIdx]++;
    }

    for (int i = 0; i < len; i++)
    {
        if (sPoints[i] > 0)
        {
            interCnt += t*sPoints[i];
            interCnt += sPoints[i] * (sPoints[i] - 1) / 2;
            if (interCnt > 10000000)
                return -1;
            t += sPoints[i];
        }
        t -= ePoints[i];
    }
    return interCnt;
}

int Brackets(string &S)
{
    if (S.empty()) { return 1; }

    stack<char> brackets;
    bool isNested = true;
    for (int i = 0; i < S.size(); i++)
    {
        switch (S[i])
        {
        case '(':
        case '[':
        case '{':
            brackets.push(S[i]);
            break;
        case ')':
            if (!brackets.empty() && brackets.top() == '(')
            {
                brackets.pop();
            }
            else
            {
                isNested = false;
            }
            break;
        case ']':
            if (!brackets.empty() && brackets.top() == '[')
            {
                brackets.pop();
            }
            else
            {
                isNested = false;
            }
            break;
        case '}':
            if (!brackets.empty() && brackets.top() == '{')
            {
                brackets.pop();
            }
            else
            {
                isNested = false;
            }
            break;
        default:
            break;
        }
        if (isNested == false)
            break;
    }
    return (isNested && brackets.empty());
}

int StoneWall(vector<int> &H)
{
    int minBlocks = 0;
    stack<int> S;

    for (int i = 0; i < H.size(); i++)
    {
        if (S.empty() || S.top() < H[i])
        {
            S.push(H[i]);
        }
        else
        {
            while (!S.empty() && S.top() >= H[i])
            {
                if (S.top() > H[i])
                    minBlocks++;
                S.pop();
            }
            S.push(H[i]);
        }
    }

    while (!S.empty())
    {
        minBlocks++;
        S.pop();
    }

    return minBlocks;
}

int StoneWall_Special(vector<int> &H)
{
    int minBlocks = 0;
    stack<int> S;

    for (int i = 0; i < H.size(); i++)
    {
        // Remove all blocks that are bigger than current height
        while (!S.empty() && S.top() > H[i])
        {
            minBlocks++;
            S.pop();
        }

        // New block is required, push it's size to the stack
        if (S.empty() || S.top() < H[i])
        {
            S.push(H[i]);
        }
    }

    minBlocks += S.size();

    return minBlocks;
}

int Nesting(string &S)
{
    int isNesting = 1;
    stack<char> Stack;
    for (int i = 0; i < S.size(); i++)
    {
        switch (S[i])
        {
        case '(': Stack.push(S[i]); break;
        case ')':
            if (!Stack.empty() && Stack.top() == '(')
                Stack.pop();
            else
                isNesting = 0;
            break;
        default:
            cout << "Illegal character!" << endl;
            break;
        }

        if (isNesting == 0)
            break;
    }
    return isNesting && !Stack.size();  // Nesting string must meet the condition.
}

int AliveFish(vector<int> &A, vector<int> &B)
{
    int survivals = 0;      // The number of fish that will stay alive
    stack<int> downStack;   // To record the fishs flowing downstream

    for (int i = 0; i < A.size(); i++)
    {
        switch (B[i])
        {
        case 0:
            // Fight with previous downstream fish
            while (!downStack.empty() && downStack.top()<A[i])
            {
                downStack.pop();
            }
            // The first fish is flowing upstream, or the upstream fish eat all previous downstream fish
            if (downStack.empty())
                survivals++;
            break;
        case 1:
            // Push all downstreaming fish into the stack
            downStack.push(A[i]);
            break;
        default:
            cout << "Illegal direction value!" << endl;
            break;
        }
    }

    // Currently, all left downstream fish in the stack will not meet with any fish.They will stay alive.
    survivals += downStack.size();

    return survivals;
}

int EquiLeader(vector<int> &A)
{
    // Calculate each element's occurrence frequency
    unordered_map<int,int> hashTable;
    for (int i = 0; i < A.size(); i++)
    {
        if (hashTable.count(A[i]) == 0)
            hashTable[A[i]] = 1;
        else
            hashTable[A[i]]++;
    }

    // Find the leader value and its occurrence frequency
    int leader = 0, leaderNum = 0;
    for (auto& x : hashTable)
    {
        if (leaderNum < x.second)
        {
            leader    = x.first;
            leaderNum = x.second;
        }
    }

    int leftNum = 0, rightNum = leaderNum, equiLeaders = 0;
    for (int i = 0; i < A.size(); i++)
    {
        if (A[i] == leader)
        {
            leftNum++;
            rightNum--;
        }
        // Equi leader makes the left array and the right array have leaders of the same value.
        if (leftNum>(i + 1) / 2 && rightNum > (A.size() - i - 1) / 2)
            equiLeaders++;
    }

    return equiLeaders;
}<file_sep>#include "OtherFunc.h"

int BinaryGap(int N)
{
    int maxBinaryGap = 0, cnt = 0;
    bool bStart = false;
    while (N)
    {
        if (N & 0x1)
        {
            if (bStart == false)
            {
                bStart = true;  // Indicate that meet the first '1'
            }
            else
            {
                maxBinaryGap = max(maxBinaryGap, cnt);
            }
            cnt = 0;    // The number of consecutive '0'
        }
        else
        {
            cnt++;
        }
        N = N >> 1;
    }
    return maxBinaryGap;
}

int FrogJmp(int X, int Y, int D)
{
    return ceil((double)(Y - X) / D);
}<file_sep>#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_set>
#include <climits>
#include <stack>

using namespace std;
/*Lesson2 - CyclicRotation
*Task description
*A zero - indexed array A consisting of N integers is given.Rotation of the array means that each element is shifted right by one index,
*and the last element of the array is also moved to the first place.
*
*For example, the rotation of array A = [3, 8, 9, 7, 6] is[6, 3, 8, 9, 7].The goal is to rotate array A K times; that is, each element of
*A will be shifted to the right by K indexes.
*
*Write a function : vector<int> CyclicRotation(vector<int> &A, int K);
*that, given a zero - indexed array A consisting of N integers and an integer K, returns the array A rotated K times.
*
*For example, given array A = [3, 8, 9, 7, 6] and K = 3, the function should return[9, 7, 6, 3, 8].
*Assume that :N and K are integers within the range[0..100];
*            each element of array A is an integer within the range[-1, 000..1, 000].
*In your solution, focus on correctness.The performance of your solution will not be the focus of the assessment.
*/
vector<int> CyclicRotation(vector<int> &A, int K);

/*Lesson2 - OddOccurrencesInArray
*A non - empty zero - indexed array A consisting of N integers is given.The array contains an odd number of elements, and each element
*of the array can be paired with another element that has the same value, except for one element that is left unpaired.
*
*For example, in array A such that :A[0] = 9  A[1] = 3  A[2] = 9 A[3] = 3  A[4] = 9  A[5] = 7 A[6] = 9
*the elements at indexes 0 and 2 have value 9,
*the elements at indexes 1 and 3 have value 3,
*the elements at indexes 4 and 6 have value 9,
*the element at index 5 has value 7 and is unpaired.
*Write a function :
*
*int OddOccurrencesInArray(vector<int> &A); that, given an array A consisting of N integers fulfilling the above conditions, returns
*the value of the unpaired element.
*
*For example, given array A such that : A[0] = 9  A[1] = 3  A[2] = 9 A[3] = 3  A[4] = 9  A[5] = 7 A[6] = 9
*the function should return 7, as explained in the example above.
*
*Assume that :N is an odd integer within the range[1..1, 000, 000];
*             each element of array A is an integer within the range[1..1, 000, 000, 000];
*             all but one of the values in A occur an even number of times.
*Complexity  :expected worst - case time complexity is O(N);
*             expected worst - case space complexity is O(1), beyond input storage(not counting the storage required for input arguments).
*Elements of input arrays can be modified.
*/
int OddOccurrencesInArray(vector<int> &A);

/*Lesson3 - PermMissingElem
*A zero - indexed array A consisting of N different integers is given.The array contains integers in the range[1..(N + 1)], which means that
*exactly one element is missing.Your goal is to find that missing element.
*
*Write a function : int PermMissingElem(vector<int> &A);that, given a zero - indexed array A, returns the value of the missing element.
*
*For example, given array A such that :A[0] = 2,A[1] = 3,A[2] = 1,A[3] = 5,the function should return 4, as it is the missing element.
*
*Assume that :
*    N is an integer within the range[0..100, 000];
*    the elements of A are all distinct;
*    each element of array A is an integer within the range[1..(N + 1)].
*Complexity:
*    expected worst - case time complexity is O(N);
*    expected worst - case space complexity is O(1), beyond input storage(not counting the storage required for input arguments).
*Elements of input arrays can be modified.
*/
int PermMissingElem(vector<int> &A);

/*Lesson3 - TapeEquilibrium
*A non - empty zero - indexed array A consisting of N integers is given.Array A represents numbers on a tape.
*Any integer P, such that 0 < P < N, splits this tape into two non - empty parts : A[0], A[1], ..., A[P - 1] and A[P], A[P + 1], ..., A[N - 1].
*
*The difference between the two parts is the value of : | (A[0] + A[1] + ... + A[P - 1]) -(A[P] + A[P + 1] + ... + A[N - 1]) |
*
*In other words, it is the absolute difference between the sum of the first part and the sum of the second part.
*For example, consider array A such that :A[0] = 3,A[1] = 1,A[2] = 2,A[3] = 4,A[4] = 3,
*We can split this tape in four places :
*P = 1, difference = | 3 - 10 | = 7
*P = 2, difference = | 4 - 9 | = 5
*P = 3, difference = | 6 - 7 | = 1
*P = 4, difference = | 10 - 3 | = 7
*Write a function : int TapeEquilibrium(vector<int> &A);
*that, given a non - empty zero - indexed array A of N integers, returns the minimal difference that can be achieved.
*
*For example, given:A[0] = 3, A[1] = 1, A[2] = 2, A[3] = 4, A[4] = 3,
*the function should return 1, as explained above.
*
*Assume that :
*    N is an integer within the range[2..100, 000];
*    each element of array A is an integer within the range[-1, 000..1, 000].
*Complexity:
*    expected worst - case time complexity is O(N);
*    expected worst - case space complexity is O(N), beyond input storage(not counting the storage required for input arguments).
*Elements of input arrays can be modified.
*/
int TapeEquilibrium(vector<int> &A);

/*Lesson4 - MissingInteger
*Write a function :int MissingInteger(vector<int> &A);that, given a non - empty zero - indexed array A of N integers, returns the minimal positive
*integer(greater than 0) that does not occur in A.
*
*For example, given:A[0] = 1,A[1] = 3,A[2] = 6,A[3] = 4,A[4] = 1,A[5] = 2, the function should return 5.
*
*Assume that:
*    N is an integer within the range[1..100, 000];
*    each element of array A is an integer within the range[−2, 147, 483, 648..2, 147, 483, 647].
*Complexity:
*    expected worst - case time complexity is O(N);
*    expected worst - case space complexity is O(N), beyond input storage(not counting the storage required for input arguments).
Elements of input arrays can be modified.
*/
int MissingInteger(vector<int> &A);

/*Lesson4 - PermCheck
*A non - empty zero - indexed array A consisting of N integers is given.A permutation is a sequence containing each element from
*1 to N once, and only once.
*For example, array A such that :A[0] = 4,A[1] = 1,A[2] = 3,A[3] = 2,is a permutation, but array A such that :
*A[0] = 4,A[1] = 1,A[2] = 3,is not a permutation, because value 2 is missing.
*
*The goal is to check whether array A is a permutation.
*Write a function : int PermCheck(vector<int> &A);that, given a zero - indexed array A, returns 1 if array A is a permutation and 0 if it is not.
*
*For example, given array A such that :
*A[0] = 4
*A[1] = 1
*A[2] = 3
*A[3] = 2
*the function should return 1.
*
*Given array A such that :
*A[0] = 4
*A[1] = 1
*A[2] = 3
*the function should return 0.
*
*Assume that:
*    N is an integer within the range[1..100, 000];
*    each element of array A is an integer within the range[1..1, 000, 000, 000].
*Complexity:
*    expected worst - case time complexity is O(N);
*    expected worst - case space complexity is O(N), beyond input storage(not counting the storage required for input arguments).
*Elements of input arrays can be modified.
*/
int PermCheck(vector<int> &A);

/*Lesson4 - FrogRiverOne
*A small frog wants to get to the other side of a river.The frog is initially located on one bank of the river(position 0) and wants to get
*to the opposite bank(position X + 1).Leaves fall from a tree onto the surface of the river.You are given a zero - indexed array A consisting
*of N integers representing the falling leaves.A[K] represents the position where one leaf falls at time K, measured in seconds.
*
*The goal is to find the earliest time when the frog can jump to the other side of the river.The frog can cross only when leaves appear at
*every position across the river from 1 to X(that is, we want to find the earliest moment when all the positions from 1 to X are covered by leaves).
*You may assume that the speed of the current in the river is negligibly small, i.e.the leaves do not change their positions once they fall in the river.
*
*For example, you are given integer X = 5 and array A such that :
*A[0] = 1,A[1] = 3,A[2] = 1,A[3] = 4,A[4] = 2,A[5] = 3,A[6] = 5,A[7] = 4
*In second 6, a leaf falls into position 5. This is the earliest time when leaves appear in every position across the river.
*
*Write a function : int FrogRiverOne(int X, vector<int> &A);that, given a non - empty zero - indexed array A consisting of N integers and integer X,
*returns the earliest time when the frog can jump to the other side of the river.
*
*If the frog is never able to jump to the other side of the river, the function should return −1.
*
*For example, given X = 5 and array A such that : A[0] = 1, A[1] = 3, A[2] = 1, A[3] = 4, A[4] = 2, A[5] = 3, A[6] = 5, A[7] = 4
*the function should return 6, as explained above.
*
*Assume that:
*    N and X are integers within the range[1..100, 000];
*    each element of array A is an integer within the range[1..X].
*Complexity:
*    expected worst - case time complexity is O(N);
*    expected worst - case space complexity is O(X), beyond input storage(not counting the storage required for input arguments).
*/
int FrogRiverOne(int X, vector<int> &A);

/*Lesson4 - MaxCounters
You are given N counters, initially set to 0, and you have two possible operations on them :
    increase(X) − counter X is increased by 1,
    max counter − all counters are set to the maximum value of any counter.
A non - empty zero - indexed array A of M integers is given.This array represents consecutive operations :
    if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
    if A[K] = N + 1 then operation K is max counter.
For example, given integer N = 5 and array A such that :
    A[0] = 3
    A[1] = 4
    A[2] = 4
    A[3] = 6
    A[4] = 1
    A[5] = 4
    A[6] = 4
the values of the counters after each consecutive operation will be :
    (0, 0, 1, 0, 0)
    (0, 0, 1, 1, 0)
    (0, 0, 1, 2, 0)
    (2, 2, 2, 2, 2)
    (3, 2, 2, 2, 2)
    (3, 2, 2, 3, 2)
    (3, 2, 2, 4, 2)
The goal is to calculate the value of every counter after all operations.

Write a function :vector<int> MaxCounters(int N, vector<int> &A);
that, given an integer N and a non - empty zero - indexed array A consisting of M integers, returns a sequence of integers
representing the values of the counters.

The sequence should be returned as :
For example, given:
    A[0] = 3
    A[1] = 4
    A[2] = 4
    A[3] = 6
    A[4] = 1
    A[5] = 4
    A[6] = 4,the function should return[3, 2, 2, 4, 2], as explained above.
Assume that:
    N and M are integers within the range[1..100, 000];
    each element of array A is an integer within the range[1..N + 1].
Complexity:
    expected worst - case time complexity is O(N + M);
    expected worst - case space complexity is O(N), beyond input storage(not counting the storage required for input arguments).
Elements of input arrays can be modified.
*/
vector<int> MaxCounters(int N, vector<int> &A);

/*Lesson5 - PassingCars(Count the number of passing cars on the road.)
A non - empty zero - indexed array A consisting of N integers is given.The consecutive elements of array A represent consecutive cars on a road.

Array A contains only 0s and / or 1s:
    0 represents a car traveling east,
    1 represents a car traveling west.
The goal is to count passing cars.We say that a pair of cars(P, Q), where 0 ≤ P < Q < N, is passing when P is traveling to the east
and Q is traveling to the west.For example, consider array A such that :
    A[0] = 0
    A[1] = 1
    A[2] = 0
    A[3] = 1
    A[4] = 1
We have five pairs of passing cars : (0, 1), (0, 3), (0, 4), (2, 3), (2, 4).

Write a function:int PassingCars(vector<int> &A);that, given a non - empty zero - indexed array A of N integers, returns the number
of pairs of passing cars.The function should return −1 if the number of pairs of passing cars exceeds 1, 000, 000, 000.

For example, given:
    A[0] = 0
    A[1] = 1
    A[2] = 0
    A[3] = 1
    A[4] = 1,the function should return 5, as explained above.
Assume that:
    N is an integer within the range[1..100, 000];
    each element of array A is an integer that can have one of the following values : 0, 1.
Complexity :
    expected worst - case time complexity is O(N);
    expected worst - case space complexity is O(1), beyond input storage(not counting the storage required for input arguments).
Elements of input arrays can be modified.
*/
int PassingCars(vector<int> &A);

/*Lesson5 - CountDiv(Compute number of integers divisible by k in range[a...b])
Write a function:int CountDiv(int A, int B, int K);that, given three integers A, B and K, returns the number of integers within the
range [A..B] that are divisible by K, i.e.:{ i : A ≤ i ≤ B, i mod K = 0 }

For example, for A = 6, B = 11 and K = 2, your function should return 3, because there are three numbers divisible by 2 within the
range [6..11], namely 6, 8 and 10.
Assume that:
    A and B are integers within the range [0..2,000,000,000];
    K is an integer within the range [1..2,000,000,000];
    A ≤ B.
Complexity:
    expected worst-case time complexity is O(1);
    expected worst-case space complexity is O(1).
*/
int CountDiv(int A, int B, int K);

/*Lesson5 - MinAvgTwoSlice(Find the minimal average of any slice containing at least two elements.)
A non - empty zero - indexed array A consisting of N integers is given.A pair of integers(P, Q), such that 0 ≤ P < Q < N, is called a
slice of array A(notice that the slice contains at least two elements).The average of a slice(P, Q) is the sum of A[P] + A[P + 1] + ... + A[Q]
divided by the length of the slice.To be precise, the average equals(A[P] + A[P + 1] + ... + A[Q]) / (Q − P + 1).

For example, array A such that :
    A[0] = 4
    A[1] = 2
    A[2] = 2
    A[3] = 5
    A[4] = 1
    A[5] = 5
    A[6] = 8
contains the following example slices :
    slice(1, 2), whose average is(2 + 2) / 2 = 2;
    slice(3, 4), whose average is(5 + 1) / 2 = 3;
    slice(1, 4), whose average is(2 + 2 + 5 + 1) / 4 = 2.5.
The goal is to find the starting position of a slice whose average is minimal.

Write a function: int MinAvgTwoSlice(vector<int> &A);;that, given a non - empty zero - indexed array A consisting of N integers, returns
the starting position of the slice with the minimal average.If there is more than one slice with a minimal average, you should return
the smallest starting position of such a slice.

For example, given array A such that :
    A[0] = 4
    A[1] = 2
    A[2] = 2
    A[3] = 5
    A[4] = 1
    A[5] = 5
    A[6] = 8,the function should return 1, as explained above.

Assume that:
    N is an integer within the range[2..100, 000];
    each element of array A is an integer within the range[−10, 000..10, 000].
Complexity:
    expected worst - case time complexity is O(N);
    expected worst - case space complexity is O(N), beyond input storage(not counting the storage required for input arguments).
Elements of input arrays can be modified.
*/
int MinAvgTwoSlice(vector<int> &A);

/*Lesson5 - GenomicRangeQuery(Find the minimal nucleotide from a range of sequence DNA.)
A DNA sequence can be represented as a string consisting of the letters A, C, G and T, which correspond to the types of successive
nucleotides in the sequence.Each nucleotide has an impact factor, which is an integer.Nucleotides of types A, C, G and T have impact
factors of 1, 2, 3 and 4, respectively.You are going to answer several queries of the form : What is the minimal impact factor of
nucleotides contained in a particular part of the given DNA sequence ?

The DNA sequence is given as a non - empty string S = S[0]S[1]...S[N - 1] consisting of N characters.There are M queries, which are
given in non - empty arrays P and Q, each consisting of M integers.The K - th query(0 ≤ K < M) requires you to find the minimal impact
factor of nucleotides contained in the DNA sequence between positions P[K] and Q[K](inclusive).

For example, consider string S = CAGCCTA and arrays P, Q such that :
    P[0] = 2    Q[0] = 4
    P[1] = 5    Q[1] = 5
    P[2] = 0    Q[2] = 6,The answers to these M = 3 queries are as follows :
The part of the DNA between positions 2 and 4 contains nucleotides G and C(twice), whose impact factors are 3 and 2 respectively, so the answer is 2.
The part between positions 5 and 5 contains a single nucleotide T, whose impact factor is 4, so the answer is 4.
The part between positions 0 and 6 (the whole string) contains all nucleotides, in particular nucleotide A whose impact factor is 1, so the answer is 1.

Write a function :

vector<int> GenomicRangeQuery(string &S, vector<int> &P, vector<int> &Q);that, given a non - empty zero - indexed string S consisting
of N characters and two non - empty zero - indexed arrays P and Q consisting of M integers, returns an array consisting of M integers
specifying the consecutive answers to all queries.

For example, given the string S = CAGCCTA and arrays P, Q such that :
    P[0] = 2    Q[0] = 4
    P[1] = 5    Q[1] = 5
    P[2] = 0    Q[2] = 6
the function should return the values[2, 4, 1], as explained above.
Assume that:
    N is an integer within the range[1..100, 000];
    M is an integer within the range[1..50, 000];
    each element of arrays P, Q is an integer within the range[0..N − 1];
    P[K] ≤ Q[K], where 0 ≤ K < M;
    string S consists only of upper - case English letters A, C, G, T.
Complexity:
    expected worst - case time complexity is O(N + M);
    expected worst - case space complexity is O(N), beyond input storage(not counting the storage required for input arguments).
Elements of input arrays can be modified.
*/
vector<int> GenomicRangeQuery(string &S, vector<int> &P, vector<int> &Q);
void LastOcurrPos(vector<int> &outPos, string &S, char c, int idx);

/*Lesson6 - Distinct(Compute number of distinct values in an array.)
Write a function : int Distinct(vector<int> &A);that, given a zero - indexed array A consisting of N integers, returns the number
of distinct values in array A.
Assume that:
    N is an integer within the range[0..100, 000];
    each element of array A is an integer within the range[−1, 000, 000..1, 000, 000].
For example, given array A consisting of six elements such that :
    A[0] = 2    A[1] = 1    A[2] = 1
    A[3] = 2    A[4] = 3    A[5] = 1
the function should return 3, because there are 3 distinct values appearing in array A, namely 1, 2 and 3.
Complexity:
    expected worst - case time complexity is O(N*log(N));
    expected worst - case space complexity is O(N), beyond input storage(not counting the storage required for input arguments).
Elements of input arrays can be modified.
*/
int Distinct(vector<int> &A);

/*Lesson6 - MaxProductOfThree(Maximize A[P] * A[Q] * A[R] for any triplet(P, Q, R))
A non - empty zero - indexed array A consisting of N integers is given.The product of triplet(P, Q, R) equates to A[P] * A[Q] * A[R](0 ≤ P < Q < R < N).
For example, array A such that :
    A[0] = -3
    A[1] = 1
    A[2] = 2
    A[3] = -2
    A[4] = 5
    A[5] = 6
contains the following example triplets :
    (0, 1, 2), product is −3 * 1 * 2 = −6
    (1, 2, 4), product is 1 * 2 * 5 = 10
    (2, 4, 5), product is 2 * 5 * 6 = 60
Your goal is to find the maximal product of any triplet.
Write a function :int MaxProductOfThree(vector<int> &A);that, given a non - empty zero - indexed array A, returns the value of the maximal product of any triplet.
For example, given array A such that :
    A[0] = -3
    A[1] = 1
    A[2] = 2
    A[3] = -2
    A[4] = 5
    A[5] = 6
the function should return 60, as the product of triplet(2, 4, 5) is maximal.
Assume that:
    N is an integer within the range[3..100, 000];
    each element of array A is an integer within the range[−1, 000..1, 000].
Complexity:
    expected worst - case time complexity is O(N*log(N));
    expected worst - case space complexity is O(1), beyond input storage(not counting the storage required for input arguments).
Elements of input arrays can be modified.
*/
int MaxProductOfThree_Basic(vector<int> &A);
int MaxProductOfThree_Special(vector<int> &A);
void UpdateMins(vector<int> &mins, int val);
void UpdateMaxs(vector<int> &maxs, int val);

/*Lesson6 - Triangle(Determine whether a triangle can be built from a given set of edges.)
A zero - indexed array A consisting of N integers is given.A triplet(P, Q, R) is triangular if 0 ≤ P < Q < R < N and :
    A[P] + A[Q] > A[R],
    A[Q] + A[R] > A[P],
    A[R] + A[P] > A[Q].
For example, consider array A such that :
    A[0] = 10    A[1] = 2    A[2] = 5
    A[3] = 1     A[4] = 8    A[5] = 20
Triplet(0, 2, 4) is triangular.
Write a function : int Triangle(vector<int> &A);that, given a zero - indexed array A consisting of N integers, returns 1 if
there exists a triangular triplet for this array and returns 0 otherwise.
For example, given array A such that :
    A[0] = 10    A[1] = 2    A[2] = 5
    A[3] = 1     A[4] = 8    A[5] = 20
the function should return 1, as explained above.Given array A such that :
    A[0] = 10    A[1] = 50    A[2] = 5
    A[3] = 1
the function should return 0.
Assume that:
    N is an integer within the range[0..100, 000];
    each element of array A is an integer within the range[−2, 147, 483, 648..2, 147, 483, 647].
Complexity:
    expected worst - case time complexity is O(N*log(N));
    expected worst - case space complexity is O(N), beyond input storage(not counting the storage required for input arguments).
Elements of input arrays can be modified.
*/
int Triangle(vector<int> &A);

/*Lesson6 - NumberOfDiscIntersections(Compute the number of intersections in a sequence of discs.)
We draw N discs on a plane.The discs are numbered from 0 to N − 1. A zero - indexed array A of N non - negative integers,
specifying the radiuses of the discs, is given.The J - th disc is drawn with its center at(J, 0) and radius A[J].

We say that the J - th disc and K - th disc intersect if J ≠ K and the J - th and K - th discs have at least one common
point(assuming that the discs contain their borders).

The figure below shows discs drawn for N = 6 and A as follows :
A[0] = 1
A[1] = 5
A[2] = 2
A[3] = 1
A[4] = 4
A[5] = 0,There are eleven(unordered) pairs of discs that intersect, namely:
    discs 1 and 4 intersect, and both intersect with all the other discs;
    disc 2 also intersects with discs 0 and 3.
Write a function : int NumberOfDiscIntersections(vector<int> &A);that, given an array A describing N discs as explained above,
returns the number of(unordered) pairs of intersecting discs.The function should return −1 if the number of intersecting pairs exceeds 10, 000, 000.

Given array A shown above, the function should return 11, as explained above.
Assume that:
    N is an integer within the range[0..100, 000];
    each element of array A is an integer within the range[0..2, 147, 483, 647].
Complexity:
    expected worst - case time complexity is O(N*log(N));
    expected worst - case space complexity is O(N), beyond input storage(not counting the storage required for input arguments).
Elements of input arrays can be modified.
*/
struct DiscLine
{
    long long left;
    long long right;
    DiscLine() :left(0), right(0){}
};
bool LeftCompare(DiscLine d1, DiscLine d2);
int NumberOfDiscIntersections_Basic(vector<int> &A);
int NumberOfDiscIntersections_Special(vector<int> &A);

/*Lesson7 - Brackets(Determine whether a given string of parentheses is properly nested.)
A string S consisting of N characters is considered to be properly nested if any of the following conditions is true:
    S is empty;
    S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string;
    S has the form "VW" where V and W are properly nested strings.
For example, the string "{[()()]}" is properly nested but "([)()]" is not.
Write a function : int Brackets(string &S);that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise.

For example, given S = "{[()()]}", the function should return 1 and given S = "([)()]", the function should return 0, as explained above.

Assume that:
    N is an integer within the range[0..200, 000];
    string S consists only of the following characters : "(", "{", "[", "]", "}" and / or ")".
Complexity :
    expected worst - case time complexity is O(N);
    expected worst - case space complexity is O(N) (not counting the storage required for input arguments).
*/
int Brackets(string &S);

/*Lesson7 - StoneWall(Cover "Manhattan skyline" using the minimum number of rectangles.)*/
int StoneWall(vector<int> &H);
int StoneWall_Special(vector<int> &H);

/*Lesson7 - Nesting(Determine whether given string of parentheses is properly nested.)*/
int Nesting(string &S);

/*Lesson7 - Fish(N voracious fish are moving along a river.Calculate how many fish are alive.)*/
int AliveFish(vector<int> &A, vector<int> &B);

/*Lesson8 - EquiLeader(Find the index S such that the leaders of the sequences A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N - 1] are the same.*/
int EquiLeader(vector<int> &A);<file_sep>#include "Sort.h"

void QuickSort(vector<int> &data, int low, int high)
{
    int i = low, j = high;
    int pivot = data[(low + high) / 2];

    // Partition
    while (i <= j)
    {
        while (data[i] < pivot) { i++; }
        while (data[j] > pivot) { j--; }
        if (i <= j)
        {
            swap(data[i++], data[j--]);
        }
    }

    if (low < j)  QuickSort(data, low, j);   // Quick sort the first part
    if (i < high) QuickSort(data, i, high);  // Quick sort the second part
}<file_sep>#include "OtherFunc.h"
#include "ArrayFunc.h"
#include "Sort.h"
#include "BinaryTree.h"

void main()
{
    vector<int> arr({ 4, 4, 2, 5, 3, 4, 4, 4 });
    int out = EquiLeader(arr);
}<file_sep>#pragma once
#include <unordered_map>

using namespace std;

struct BiTreeNode
{
    int val;
    BiTreeNode *left, *right;

    BiTreeNode() :val(0), left(nullptr), right(nullptr){}
};

BiTreeNode* CreateTreeNode(int value);

/*The problem is to find out a path from root to leaf with the max number of distinct nodes.For example, with following binary tree :
                    4
                  /   \
                 5     6
                /     / \
               4     1   6
              /
             5
The path with max number of distinct nodes is: 4->6->1 and the function should return 3.
Assume that:
    N is an integer within the range [1,50 000]
    The height of tree T(number of edges on the longest path from root to leaf) is within the range [0, 3 5000]
    Each value in the tree T is an integer within the range [1, N]

Complexity:
    Expected worst-case time complexity is O(N).
    Expected worst-case space complexity is O(N).
*/
void findMax(BiTreeNode *root, unordered_map<int, int> &hashTable, int &max);<file_sep>#pragma once
#include <vector>
#include <algorithm>

using namespace std;

/*The divide-and-conquer strategy is used in quicksort.Below the recursion step is described :
1. Choose a pivot value.We take the value of the middle element as pivot value, but it can be any value,
   which is in range of sorted values, even if it doesn't present in the array.
2. Partition:Rearrange elements in such a way, that all elements which are lesser than the pivot go to
   the left part of the array and all elements greater than the pivot, go to the right part of the array.
   Values equal to the pivot can stay in any part of the array.Notice, that array may be divided in non - equal parts.
3. Sort both parts:Apply quicksort algorithm recursively to the left and the right parts.*/
void QuickSort(vector<int> &data, int low, int high);


text:
<file_sep># dsa-using-c
c data strucures programs

repo_name: geek-hub/dsa-using-c