Sunday 2 July 2017

Moving Average Array Java


2.4 Filas Prioritárias Muitas aplicações requerem que processemos itens com chaves em ordem, mas não necessariamente em ordem completa ordenada e não necessariamente todos de uma vez. Muitas vezes, coletamos um conjunto de itens e, em seguida, processamos um com a maior chave, então talvez coletem mais itens e, em seguida, processemos aquele com a maior chave atual, e assim por diante. Um tipo de dados apropriado nesse ambiente suporta duas operações: remova o máximo e insira. Esse tipo de dados é chamado de fila de prioridade. As filas de prioridade são caracterizadas pela remoção das operações de inserção e máximo. Por convenção, vamos comparar chaves apenas com um método less (), como temos vindo a fazer para a classificação. Assim, se os registros podem ter chaves duplicadas, máximo significa qualquer registro com o maior valor de chave. Para completar a API, também precisamos adicionar construtores e um teste se a operação estiver vazia. Para flexibilidade, usamos uma implementação genérica com um tipo de chave genérico que implementa o Comparable. O programa TopM. java é um cliente de fila de prioridade que recebe um argumento de linha de comando M. Lê transações de entrada padrão e imprime as M transações maiores. Implementações elementares. As estruturas de dados básicas discutidas na Seção 1.3 nos fornecem quatro pontos de partida imediatos para a implementação de filas de prioridade. Representação de matriz (não ordenada). Talvez a implementação da fila de prioridades mais simples seja baseada no nosso código para pilhas pushdown. O código para inserir na fila de prioridade é o mesmo que para empurrar na pilha. Para implementar remover o máximo. Podemos adicionar código como o loop interno de seleção para trocar o item máximo com o item no final e, em seguida, excluir esse, como fizemos com pop () para pilhas. O programa UnorderedArrayMaxPQ. java implementa uma fila de prioridade usando esta abordagem. Representação de matriz (ordenada). Outra abordagem é adicionar código para inserir para mover entradas maiores uma posição para a direita, mantendo assim as entradas na matriz em ordem (como na classificação de inserção). Assim, o item maior está sempre no final eo código para remover o máximo na fila de prioridade é o mesmo que para pop na pilha. O programa OrderedArrayMaxPQ. java implementa uma fila de prioridade usando esta abordagem. Representações de lista vinculada (não ordenadas e ordenadas por ordem inversa). Da mesma forma, podemos começar com nosso código de lista vinculada para pilhas pushdown, modificando o código para pop () para encontrar e retornar o máximo ou o código para push () para manter os itens na ordem inversa eo código para pop () Desvincule e retorne o primeiro item (máximo) na lista. Todas as implementações elementares discutidas têm a propriedade de que a inserção ou a remoção da operação máxima levam tempo linear no pior caso. Encontrar uma implementação onde ambas as operações são garantidas para ser rápido é uma tarefa mais interessante, e é o assunto principal desta seção. Definições de heap. O heap binário é uma estrutura de dados que pode suportar de forma eficiente as operações básicas de fila de prioridade. Em um heap binário, os itens são armazenados em uma matriz de modo que cada chave é garantida para ser maior do que (ou igual a) as chaves em duas outras posições específicas. Por sua vez, cada uma dessas chaves deve ser maior do que mais duas chaves, e assim por diante. Esta ordenação é fácil de ver se vemos as chaves como sendo em uma estrutura de árvore binária com bordas de cada chave para as duas chaves que se sabe serem menores. Definição. Uma árvore binária é heap-ordered se a chave em cada nó é maior do que (ou igual a) as chaves em que os nós dois filhos (se houver). Proposição. A maior chave em uma árvore binária ordenada heap é encontrada na raiz. Podemos impor a restrição de ordenação de heap em qualquer árvore binária. É particularmente conveniente, no entanto, usar uma árvore binária completa como a abaixo. Representamos árvores binárias completas sequencialmente dentro de uma matriz, colocando os nós com ordem de nível. Com a raiz na posição 1, seus filhos nas posições 2 e 3, seus filhos nas posições 4, 5, 6 e 7 e assim por diante. Definição. Um heap binário é um conjunto de nós com chaves dispostas em uma árvore binária completa ordenada por heap, representada em ordem de nível em uma matriz (não usando a primeira entrada). Numa pilha, o pai do nó na posição k está na posição k2 e, inversamente, os dois filhos do nó na posição k estão nas posições 2k e 2k 1. Podemos viajar para cima e para baixo fazendo aritmética simples em índices de matriz : Para mover-se acima da árvore de ak nós ajustamos k a k2 para mover para baixo a árvore nós ajustamos k a 2k ou 2k1. Algoritmos em heaps. Representamos um heap de tamanho N em matriz privada pq de comprimento N1, com pq0 não utilizado eo heap em pq1 através de pqN. Nós acessamos chaves somente através de funções auxiliares privadas menos () e exch (). As operações de heap que consideramos trabalho primeiro fazendo uma modificação simples que poderia violar a condição de heap, em seguida, viajando pelo heap, modificando o heap como necessário para garantir que a condição heap é satisfeita em todos os lugares. Nós nos referimos a este processo como reheapifying. Ou restaurar a ordem do heap. Bottom-up reheapify (nadar). Se a ordem de heap é violada porque uma chave de nós torna-se maior do que a chave de pais de nós, então podemos fazer progresso para corrigir a violação trocando o nó com seu pai. Após a troca, o nó é maior do que os dois filhos (um é o pai antigo eo outro é menor do que o pai antigo porque era filho desse nó), mas o nó ainda pode ser maior que seu pai. Podemos corrigir essa violação da mesma maneira, e assim por diante, subindo a pilha até chegar a um nó com uma chave maior, ou a raiz. De cima para baixo heapify (pia). Se a ordem de heap for violada porque uma chave de nó se torna menor do que uma ou ambas as chaves de nó de crianças, então podemos fazer progresso para corrigir a violação trocando o nó com o maior de seus dois filhos. Essa opção pode causar uma violação na criança que corrigir essa violação da mesma maneira e assim por diante, movendo para baixo o heap até chegar a um nó com ambos os menores menor ou inferior. Fila de prioridade baseada em heap. Essas operações sink () e swim () fornecem a base para a implementação eficiente da API priority-queue, conforme diagrama abaixo e implementado em MaxPQ. java e MinPQ. java. Inserir. Nós adicionamos o novo item no final da matriz, incrementar o tamanho da pilha e, em seguida, nadar até o heap com esse item para restaurar a condição heap. Remova o máximo. Pegamos o item maior da parte superior, colocamos o item da extremidade da pilha na parte superior, diminuímos o tamanho da pilha e, em seguida, descemos através da pilha com esse item para restaurar a condição de pilha. Proposição. Em uma fila de prioridade N-item, os algoritmos heap requerem não mais de 1 lg N compara para inserir e não mais de 2 lg N compara para remover o máximo. Considerações práticas. Concluímos nosso estudo da API de fila de prioridade de heap com algumas considerações práticas. Multiway pilhas. Não é difícil modificar nosso código para construir heaps com base em uma representação de matriz de heap completo ordenado ternário ou d-árvores. Há um tradeoff entre o custo mais baixo da altura reduzida da árvore eo custo mais elevado de encontrar a maior das três ou d crianças em cada nó. Array redimensionamento. Podemos adicionar um construtor sem argumentos, o código para duplicar matriz em insert (). E codificar para array halving em delMax (). Assim como fizemos para as pilhas na Seção 1.3. Os limites de tempo logarítmicos são amortizados quando o tamanho da fila de prioridade é arbitrário e os arrays são redimensionados. Imutabilidade das chaves. A fila de prioridade contém objetos que são criados pelos clientes, mas assume que o código do cliente não altera as chaves (o que pode invalidar os invariantes do heap). Fila de prioridade de índice. Em muitos aplicativos, faz sentido permitir que os clientes façam referência a itens que já estão na fila de prioridade. Uma maneira fácil de fazer isso é associar um índice inteiro único a cada item. IndexMinPQ. java é uma implementação baseada em heap desta API IndexMaxPQ. java é semelhante, mas para filas de prioridade orientada máxima. Multiway. java é um cliente que mescla vários fluxos de entrada ordenados em um fluxo de saída ordenado. Podemos usar qualquer fila de prioridade para desenvolver um método de classificação. Nós inserimos todas as chaves a serem classificadas em uma fila de prioridade orientada mínimo, então use repetidamente remover o mínimo para removê-los todos em ordem. Ao usar um heap para a fila de prioridade, obtemos heapsort. Focalizando a tarefa de classificação, abandonamos a noção de esconder a representação de pilha da fila de prioridade e usamos swim () e sink () diretamente. Fazer isso nos permite classificar uma matriz sem precisar de espaço extra, mantendo o heap dentro da matriz a ser classificada. Heapsort se divide em duas fases: construção de heap. Onde reorganizamos a matriz original em um heap, e a classificação. Onde puxamos os itens para fora da pilha em ordem decrescente para construir o resultado ordenado. Construção do heap. Podemos realizar essa tarefa em tempo proporcional a N lg N, procedendo da esquerda para a direita através da matriz, usando swim () para garantir que as entradas à esquerda do ponteiro de varredura formam uma árvore completa ordenada por pilha, como sucessivas Inserções de filas prioritárias. Um método inteligente que é muito mais eficiente é proceder da direita para a esquerda, usando sink () para fazer subheaps como vamos. Cada posição na matriz é a raiz de um subconjunto pequeno subconjunto () trabalha ou subheaps tais, também. Se os dois filhos de um nó são pilhas, em seguida, chamar sink () nesse nó torna a subárvore enraizada há um heap. Classificação. A maior parte do trabalho durante heapsort é feito durante a segunda fase, onde removemos os maiores itens restantes do heap e colocá-lo na posição matriz desocupado como o heap encolhe. Heap. java é uma implementação completa do heapsort. Abaixo está um rastreamento do conteúdo do array após cada coletor. Proposição. A construção do heap baseado no dissipador é tempo linear. Proposição. Usuários de heapsort menos de 2n lg n comparam e trocam para classificar n itens. A maioria dos itens reinseridos no heap durante a classificação ir todo o caminho para o fundo. Podemos assim economizar tempo, evitando a verificação de se o item atingiu sua posição, simplesmente promovendo o maior dos dois filhos até que o fundo é atingido, em seguida, mover de volta para cima o heap para a posição adequada. Esta idéia reduz o número de compara por um fator de 2 à custa de contabilidade extra. Suponha que a seqüência (onde uma letra significa inserir e um asterisco significa remover o máximo) é aplicada a uma fila de prioridade inicialmente vazia. Forneça a seqüência de valores retornada por remover as operações máximas. Solução. Criticar a seguinte idéia: para implementar encontrar o máximo em tempo constante, por que não acompanhar o valor máximo inserido até agora, em seguida, retornar esse valor para encontrar o máximo. Solução. Será necessário atualizar o valor máximo a partir do zero após uma operação remove-the-maximum. Fornecer implementações de fila de prioridade que suportam inserir e remover o máximo. Um para cada uma das seguintes estruturas de dados subjacentes: matriz desordenada, matriz ordenada, lista vinculada não ordenada e lista vinculada ordenada. Dê uma tabela dos limites do pior caso para cada operação para cada uma das quatro implementações do exercício anterior. Solução parcial. OrderedArrayMaxPQ. java e UnorderedArrayMaxPQ. java É uma matriz que é ordenada em ordem decrescente uma pilha orientada para max. Responda. Sim. Suponha que seu aplicativo terá um grande número de operações de inserção, mas apenas alguns removerão as operações máximas. Qual a prioridade da implementação da fila que você acha que seria mais eficaz: heap, array desordenado, array ordenado Resposta. Array não ordenado. A inserção é constante. Suponha que seu aplicativo terá um grande número de encontrar as operações máximas, mas um número relativamente pequeno de inserir e remover o máximo de operações. Qual implementação de fila de prioridade você acha que seria mais eficaz: heap, array desordenado, array ordenado Answer. Arranjo ordenado. Encontre o máximo é tempo constante. Qual é o número mínimo de itens que devem ser trocados durante uma remoção da operação máxima em um monte de tamanho N sem chaves duplicadas Dê um montão de tamanho 15 para o qual o mínimo é alcançado. Responda a mesma pergunta para dois e três sucessivos remover as operações máximas. Resposta parcial. (A) 2. Projete um algoritmo de certificação de tempo linear para verificar se uma matriz pq é uma pilha min-orientada. Solução. Consulte o método isMinHeap () em MinPQ. java. Demonstre que a construção de heap com base em sink utiliza no máximo 2 n compara e no máximo n troca. Solução. Basta provar que a construção de heap com base em sink utiliza menos de n intercâmbios porque o número de comparações é no máximo o dobro do número de trocas. Para simplificar, suponha que o heap binário é perfeito (isto é, uma árvore binária em que cada nível é preenchido preenchido) e tem altura h. Definimos a altura de um nó em uma árvore para ser a altura da subárvore enraizada nesse nó. Uma chave em altura k pode ser trocada com no máximo k chaves abaixo dela quando ela é afundada. Uma vez que existem 2 h menos k nós à altura k. O número total de trocas é no máximo: A primeira igualdade é para uma soma não padronizada, mas é fácil verificar se a fórmula se mantém via indução matemática. A segunda igualdade é válida porque uma árvore binária perfeita de altura h tem 2 h 1 menos 1 nós. Provar que o resultado se mantém quando a árvore binária não é perfeita requer um pouco mais de cuidado. Você pode fazer isso usando o fato de que o número de nós na altura k em um monte binário em n nós é no máximo ceil (n 2 k 1). Solução alternativa. Novamente, por simplicidade, suponha que o heap binário é perfeito (isto é, uma árvore binária na qual cada nível é preenchido preenchido). Definimos a altura de um nó em uma árvore para ser a altura da subárvore enraizada nesse nó. Primeiro, observe que um heap binário em n nós tem n menos 1 links (porque cada link é o pai de um nó e cada nó tem um link pai, exceto a raiz). Afundar um nó de altura k requer no máximo k trocas. Carregaremos k links para cada nó em altura k. Mas não necessariamente os links no caminho tomado quando afundando o nó. Em vez disso, cobramos o nó os links k ao longo do caminho a partir do nó que vai para a esquerda-direita-direita-direita-. Por exemplo, no diagrama abaixo, o nó raiz é carregado os 4 links vermelhos o nó azul é carregado os 3 links azul e assim por diante. Observe que nenhum link é carregado em mais de um nó. (Na verdade, existem dois links não cobrados para qualquer nó: o link direito da raiz eo link pai do nó inferior direito). Assim, o número total de trocas é no máximo n. Uma vez que existem no máximo 2 comparações por troca, o número de comparações é no máximo 2 n. Problemas criativos Teoria computacional dos números. Escreva um programa CubeSum. java que imprime todos os inteiros da forma a 3 b 3 onde aeb são inteiros entre 0 e N em ordem classificada, sem usar espaço excessivo. Ou seja, em vez de computar uma matriz das somas N 2 e classificá-las, construa uma fila de prioridades com orientação mínima, inicialmente contendo (0 3. 0, 0), (1 3. 1, 0), (2 3. 2 , 0). (N3, N, 0). Então, enquanto a fila de prioridade é nonempty, remova o item menor (i 3 j 3. i, j), imprima-o e, em seguida, se j 3 (j1) 3. i, j1). Utilize este programa para encontrar todos os números inteiros distintos a, b, c e d entre 0 e 106 de tal modo que a 3 b 3 c 3 d 3, e. 1729 93 103 13 123. Encontre o mínimo. Adicione um método min () para MaxPQ. java. Sua implementação deve usar tempo constante e espaço extra constante. Solução. Adicione uma variável de instância extra que aponta para o item mínimo. Atualize-o após cada chamada para inserir (). Redefini-lo para nulo se a fila de prioridade ficar vazia. Achado dinâmico-mediano. Desenhe um tipo de dados que suporte a inserção no tempo logarítmico, encontre a mediana em tempo constante e remova a mediana no tempo logarítmico. Solução. Mantenha a chave mediana em v use um heap máximo orientado para chaves menores do que a chave de v use um heap min-orientado para chaves maiores que a chave de v. Para inserir, adicione a nova chave no heap apropriado, substitua v por A chave extraída dessa pilha. Limite inferior. Prove que é impossível desenvolver uma implementação do MinPQ API tal que tanto inserir e excluir a garantia mínima para usar N log log N compara. Solução. Isso resultaria em um algoritmo de ordenação baseado em comparação de N log log N (inserir N itens e, em seguida, remover repetidamente o mínimo), violando a proposição da Seção 2.3. Implementação da fila de prioridade de índice. Implemente IndexMaxPQ. java modificando MaxPQ. java da seguinte forma: Altere pq para armazenar índices, adicione uma matriz chaves para manter os valores de chave e adicione uma matriz qp que é o inverso de pq mdash qpi dá a posição de i em pq (o Índice j tal que pqj é i). Em seguida, modifique o código para manter essas estruturas de dados. Use a convenção de que qpi é -1 se i não está na fila e inclua um método contains () que testa essa condição. Você precisa modificar os métodos auxiliar exch () e less () mas não sink () ou swim (). Web Exercícios Melhor, média e pior caso de heapsort. Quais são os melhores casos, casos médios e piores números de comparações para heapsorting uma matriz de comprimento N Solução. Se permitimos duplicatas, o melhor caso é o tempo linear (N chaves iguais) se desautorizar duplicatas, o melhor caso é N lg N compara (mas o melhor caso de entrada é não trivial). O número médio e pior de comparações é 2 N lg N compara. Consulte a Análise de Heapsort para obter detalhes. Melhor e pior caso de heapify. O que é o menor número e a maioria das comparesexchanges necessários para heapify uma matriz de N itens Solução. Heapify uma matriz de N itens em ordem decrescente requer 0 troca e N - 1 compara. Heapifying uma matriz de N itens em ordem crescente requer N intercâmbios e 2N compara. Números de táxi. Encontre os inteiros menores que podem ser expressos como a soma de cubos de números inteiros de duas maneiras diferentes (1.729), três maneiras diferentes (87.539.319), quatro maneiras diferentes (6,963,472,309,248), cinco maneiras diferentes (48,988,659,276,962,496), e seis maneiras diferentes (24,153,319,581,254,312,065,344 ). Esses inteiros são chamados de números Taxicab após a famosa história de Ramanujan. Os inteiros menores que podem ser expressos como a soma de cubos de inteiros em sete maneiras diferentes é atualmente desconhecido. Escreva um programa Taxicab. java que lê em um parâmetro de linha de comando N e imprime todas as soluções não triviales de a 3 b 3 c 3 d 3 tais que a, b, c e d, são menores ou iguais a N. Computacional Teoria dos Números. Encontre todas as soluções para a equação a 2b 2 3c 3 4d 4 para as quais a, b, c e d são menores que 100.000. Dica. Use um heap min e um heap máximo. Manipulação de interrupção. Ao programar um sistema em tempo real que pode ser interrompido (por exemplo, com um clique do mouse ou conexão sem fio), é necessário atender às interrupções imediatamente, antes de prosseguir com a atividade atual. Se as interrupções devem ser tratadas na mesma ordem em que chegam, então uma fila FIFO é a estrutura de dados apropriada. No entanto, se diferentes interrupções têm prioridades diferentes (por exemplo), então precisamos de uma fila de prioridade. Simulação de redes de filas. MM1 para filas paralelas duplas, etc. Difícil analisar matematicamente redes de filas complexas. Em vez disso, use a simulação para traçar a distribuição dos tempos de espera, etc. Precise fila de prioridade para determinar qual evento processar a seguir. Distribuição Zipf. Utilize o resultado do (s) exercício (s) anterior para amostrar a partir da distribuição Zipfian com parâmetros s e N. A distribuição pode assumir valores inteiros de 1 a N e assume o valor k com probabilidade 1ks soma (i 1 a N) 1is . Exemplo: palavras em Shakespeares jogar Hamlet com s aproximadamente igual a 1. Processo aleatório. Comece com N bins, cada um consistindo de uma bola. Selecionar aleatoriamente uma das N esferas e mover a bola para um bin aleatoriamente de modo que a probabilidade de que uma bola é colocada em um escaninho com m bolas é mN. Qual é a distribuição de bolas que resulta após muitas iterações Use o método de amostragem aleatória descrito acima para tornar a simulação eficiente. Vizinhos mais próximos. Dado N vetores x 1. X 2. X N de comprimento M e outro vetor x do mesmo comprimento, encontre os 20 vetores que estão mais próximos de x. Círculo desenhado em um pedaço de papel milimetrado. Escreva um programa para encontrar o raio de um círculo, centrado na origem, que toca 32 pontos com inteiros x e y-coordenadas. Dica: procure um número que pode ser expresso como a soma de dois quadrados de várias maneiras diferentes. Resposta: existem dois triplos pitagóricos com hipotenusa 25: 152 202 252, 72 242 252 resultando em 20 desses pontos de rede existem 22 triplas pitagóricas diferentes com hipotenusa 5,525 isso leva a 180 pontos de rede. 27.625 é o menor raio que toca mais de 64. 154,136,450 tem 35 triplos pitagóricos. Poderes perfeitos. Escreva um programa PerfectPower. java para imprimir todos os poderes perfeitos que podem ser representados como inteiros longos de 64 bits: 4, 8, 9, 16, 25, 27. Uma potência perfeita é um número que pode ser escrito como ab para inteiros a E b ge 2. Adições de ponto flutuante. Adicione N números de ponto flutuante, evitando erros roundoff. Exclua os dois menores: adicione um ao outro e reinsira. Primeiro-ajuste para a embalagem do escaninho. 1710 OPT 2, 119 OPT 4 (decrescente). Use a árvore de torneio máxima em que os jogadores são N escaninhos e valor a capacidade disponível. Empilhe com minmax. Crie um tipo de dados que suporte push, pop, size, min e max (onde min e max são os itens mínimo e máximo na pilha). Todas as operações devem levar tempo constante no pior caso. Dica: associar com cada entrada de pilha os itens mínimo e máximo atualmente na pilha. Fila com minmax. Desenhe um tipo de dados que suporte enqueue, dequeue, tamanho, min e max (onde min e max são os itens mínimo e máximo na fila). Todas as operações devem ter tempo amortizado constante. Dica: fazer o exercício anterior e simular uma fila com duas pilhas. 2i 5j. Imprimir números do formulário 2i 5j em ordem crescente. Min-max heap. Crie uma estrutura de dados que suporta min e max em tempo constante, inserir, excluir min e excluir max em tempo logarítmico, colocando os itens em uma única matriz de tamanho N com as seguintes propriedades: A matriz representa uma árvore binária completa. A chave em um nó em um nível uniforme é menor que (ou igual a) as chaves em sua subárvore a chave em um nó em um nível ímpar é maior que (ou igual a) as chaves em sua subárvore. Observe que o valor máximo é armazenado na raiz eo valor mínimo é armazenado em uma das raízes children. Solution. Min-Max Heaps e Filas de Prioridade Generalizadas Intervalo mínimo de consulta. Dada uma seqüência de N itens, uma consulta mínima de intervalo de índice i para j é o índice do item mínimo entre i e j. Desenhe uma estrutura de dados que pré-processa a seqüência de N itens em tempo linear para suportar consultas mínimas de intervalo em tempo logarítmico. Prove que uma árvore binária completa com N nós tem limites de teto (N2) (nós sem filhos). Máxima prioridade fila com min. Qual é a ordem de crescimento do tempo de execução para encontrar uma chave mínima em um heap binário orientado máximo. Solução. Linearmdashthe chave mínima poderia ser em qualquer um dos nós de folha de teto (N2). Máxima prioridade fila com min. Desenhe um tipo de dados que suporte inserir e remover-o-máximo em tempo logarítmico juntamente com ambos um máximo de min em tempo constante. Solução. Criar uma pilha binária max-orientada e também armazenar a chave mínima inserida até agora (que nunca irá aumentar a menos que este heap torna-se vazio). Kth maior item maior que x. Dado um máximo binário binário orientado, projete um algoritmo para determinar se o kth maior item é maior que ou igual a x. Seu algoritmo deve ser executado no tempo proporcional a k. Solução. Se a chave no nó for maior ou igual a x, pesquisa recursivamente a subárvore esquerda e a subárvore direita. Pare quando o número de nó explorado é igual a k (a resposta é sim) ou não há mais nós a explorar (não). Kth item menor em um min-orientado binary heap. Desenhe um algoritmo k log k para encontrar o kth item mais pequeno em um min-oriented heap binário H contendo N itens. Solução. Construa um novo min-orientado heap H. Não vamos modificar H. Inserir a raiz de H em H, juntamente com seu heap índice 1. Agora, repetidamente apagar o mínimo item x em H e inserir em H os dois filhos de x de H O kth item excluído de H é o kth item menor em H. Fila aleatória. Implementar um RandomQueue para que cada operação é garantida para tomar no máximo tempo logarítmico. Dica. Não pode permitir duplicação de matrizes. Nenhuma maneira fácil com listas ligadas para localizar um elemento aleatório em O (1) tempo. Em vez disso, use uma árvore binária completa com links explícitos. Fila FIFO com exclusão aleatória. Implementar um tipo de dados que suporte as seguintes operações: inserir um item. Exclua o item que foi adicionado menos recentemente. E excluir um item aleatório. Cada operação deve ter (no máximo) tempo logarítmico no pior caso. Solução. Use uma árvore binária completa com links explícitos para atribuir a prioridade inteira i ao item i th adicionado à estrutura de dados. Top k somas de dois arranjos ordenados. Dadas duas matrizes classificadas a e b, cada uma de comprimento N, encontre as maiores k somas da forma ai bj. Dica. Usando uma fila de prioridade (semelhante ao problema do táxi), você pode conseguir um algoritmo O (k log N). Surpreendentemente, é possível fazê-lo em tempo O (k), mas o algoritmo é complicado. Análise empírica da construção de heap. Comparem empiricamente a construção de heap bottom-up de tempo linear versus a construção de heap top-down de tempo linear linear-níve. Certifique-se de comprá-lo sobre um intervalo de valores de N. LaMarca e Ladner relatam que por causa da localidade de cache, o algoritmo ingênuo pode executar melhor na prática do que a abordagem mais inteligente para grandes valores de N (quando o heap já não se encaixa no Cache), embora este último efectue muito menos comparações e trocas. Análise empírica de multipontos. Empiricamente comparar o desempenho de 2- 4- e 8-way heaps. LaMarca e Ladner sugerem várias otimizações, levando em conta os efeitos de cache. Análise empírica de heapsort. Empiricamente comparar o desempenho de 2- 4 e 8-heapsort maneira. LaMarca e Ladner sugerem várias otimizações, levando em conta os efeitos de cache. Seus dados indicam que um otimizado (e memória-ajustado) 8-heapsort maneira pode ser duas vezes mais rápido que heapsort clássico. Heapify por inserções. Suponha que você bulid um heap binário em N teclas, inserindo repetidamente a próxima chave para o heap binário. Mostre que o número total de comparações é no máximo Resposta. O número de comparações é no máximo de lg 1 lg 2. Lg N lg (N) N lg N. Heapify limite inferior. (Gonnet e Munro) Mostre que qualquer algoritmo baseado em comparação para construir um heap binário em N chaves leva pelo menos 1.3644 N no pior caso. Responda . Use um argumento de teoria da informação, ala classificando o limite inferior. Existem N possíveis montões (permutação dos N inteiros) em N chaves distintas, mas há muitos montes que correspondem à mesma ordenação. Por exemplo, existem duas pilhas (c a b e c b a) que correspondem aos 3 elementos a. Imaginemos que temos um array de inteiros como este: A média é obtida com a seguinte fórmula A (1n) xi (com i 1 a n). Então: x1n x2n. Xnn Nós dividimos o valor atual pelo número de valores e adicionamos o resultado anterior ao valor retornado. A assinatura de método de redução é A função de callback reduzir leva os seguintes parâmetros: p. Resultado do cálculo anterior c. Valor atual (do índice atual) i. Valor de índice de elementos de matriz atual a. O Array reduzido atual O segundo parâmetro reduce é o valor padrão. (Usado se o array estiver vazio). Assim, o método de redução média será: Se você preferir, você pode criar uma função separada E, em seguida, basta consultar a assinatura do método de retorno de chamada Ou Aumentar o protótipo Array diretamente. É possível dividir o valor cada vez que o método de redução é chamado. Ou melhor ainda. Usando o método Array. protoype. sum () previamente definido, otimizar o processo de chamar a divisão apenas uma vez :) Em seguida, em qualquer objeto Array do escopo: NB: uma matriz vazia com retorno um desejo NaN é mais correto do que 0 no meu Ponto de vista e pode ser útil em casos de uso específicos.1.5 Entrada e Saída Nesta seção, estendemos o conjunto de abstrações simples (entrada de linha de comando e saída padrão) que usamos como interface entre nossos programas Java eo exterior Mundo para incluir entrada padrão. Desenho padrão. E áudio padrão. Entrada padrão torna conveniente para nós escrever programas que processam quantidades arbitrárias de entrada e para interagir com os nossos programas de desenho padrão torna possível para nós trabalhar com gráficos e áudio padrão adiciona som. Vista aérea. Um programa Java toma os valores de entrada da linha de comando e imprime uma seqüência de caracteres como saída. Por padrão, os argumentos de linha de comando ea saída padrão são associados a um aplicativo que recebe comandos, que chamamos de janela de terminal. Aqui estão algumas instruções para usar a linha de comando em seu sistema. Mac middot Windows middot Linux Argumentos da linha de comando. Todas as nossas classes têm um método main () que toma uma matriz de Cadeia args como argumento. Essa matriz é a seqüência de argumentos de linha de comando que nós digitemos. Se pretendemos que um argumento seja um número, devemos usar um método como Integer. parseInt () para convertê-lo de String para o tipo apropriado. Saída padrão. Para imprimir valores de saída em nossos programas, usamos System. out. println (). Java envia os resultados para um fluxo abstrato de caracteres conhecidos como saída padrão. Por padrão, o sistema operacional conecta a saída padrão à janela do terminal. Toda a saída em nossos programas até agora vem aparecendo na janela do terminal. RandomSeq. java usa este modelo: É necessário um argumento de linha de comando n e imprime na saída padrão uma seqüência de n números aleatórios entre 0 e 1. Para completar nosso modelo de programação, adicionamos as seguintes bibliotecas: Entrada padrão. Ler números e strings do usuário. Desenho padrão. Gráficos de trama. Áudio padrão. Criar som. Saída padrão. Os métodos Javas System. out. print () e System. out. println () implementam a abstração de saída padrão básica de que precisamos. No entanto, para tratar a entrada padrão e saída padrão de forma uniforme (e para fornecer algumas melhorias técnicas), usamos métodos semelhantes que são definidos em nossa biblioteca StdOut: Javas print () e println () métodos são os que você tem Usando O método printf () nos dá mais controle sobre a aparência da saída. Princípios de impressão formatados. Em sua forma mais simples, printf () leva dois argumentos. O primeiro argumento é chamado de string de formato. Ele contém uma especificação de conversão que descreve como o segundo argumento deve ser convertido em uma seqüência de caracteres para saída. As cadeias de formato começam com e terminam com um código de conversão de uma letra. A tabela a seguir resume os códigos mais usados: Format string. A string de formato pode conter caracteres além daqueles para a especificação de conversão. A especificação de conversão é substituída pelo valor do argumento (convertido para uma cadeia conforme especificado) e todos os caracteres restantes são passados ​​para a saída. Argumentos múltiplos. A função printf () pode ter mais de dois argumentos. Neste caso, a cadeia de formato terá uma especificação de conversão adicional para cada argumento adicional. Aqui está mais documentação sobre printf format string sintax. Standard input. Nossa biblioteca StdIn obtém dados de um fluxo de entrada padrão que contém uma seqüência de valores separados por espaços em branco. Cada valor é uma string ou um valor de um dos tipos primitivos Javas. Um dos principais recursos do fluxo de entrada padrão é que o programa consome valores quando ele os lê. Uma vez que seu programa tenha lido um valor, ele não pode fazer backup e lê-lo novamente. A biblioteca é definida pela seguinte API: Agora consideramos vários exemplos em detalhes. Digitação de entrada. When you use the java command to invoke a Java program from the command line, you actually are doing three things: (1) issuing a command to start executing your program, (2) specifying the values of the command-line arguments, and (3) beginning to define the standard input stream. The string of characters that you type in the terminal window after the command line is the standard input stream. For example, AddInts. java takes a command-line argument n . then reads n numbers from standard input and adds them, and prints the result to standard output: Input format. If you type abc or 12.2 or true when StdIn. readInt() is expecting an int . then it will respond with an InputMismatchException . StdIn treats strings of consecutive whitespace characters as identical to one space and allows you to delimit your numbers with such strings. Interactive user input. TwentyQuestions. java is a simple example of a program that interacts with its user. The program generates a random integer and then gives clues to a user trying to guess the number. The fundamental difference between this program and others that we have written is that the user has the ability to change the control flow while the program is executing. Processing an arbitrary-size input stream. Typically, input streams are finite: your program marches through the input stream, consuming values until the stream is empty. But there is no restriction of the size of the input stream. Average. java reads in a sequence of real numbers from standard input and prints their average. Redirection and piping. For many applications, typing input data as a standard input stream from the terminal window is untenable because doing so limits our programs processing power by the amount of data that we can type. Similarly, we often want to save the information printed on the standard output stream for later use. We can use operating system mechanisms to address both issues. Redirecting standard output to a file. By adding a simple directive to the command that invokes a program, we can redirect its standard output to a file, either for permanent storage or for input to some other program at a later time. For example, the command specifies that the standard output stream is not to be printed in the terminal window, but instead is to be written to a text file named data. txt . Each call to StdOut. print() or StdOut. println() appends text at the end of that file. In this example, the end result is a file that contains 1,000 random values. Redirecting standard output from a file. Similarly, we can redirect standard input so that StdIn reads data from a file instead of the terminal window. For example, the commandreads a sequence of numbers from the file data. txt and computes their average value. Specifically, the lt symbol is a directive to implement the standard input stream by reading from the file data. txt instead of by waiting for the user to type something into the terminal window. When the program calls StdIn. readDouble() . the operating system reads the value from the file. This facility to redirect standard input from a file enables us to process huge amounts of data from any source with our programs, limited only by the size of the files that we can store. Connecting two programs. The most flexible way to implement the standard input and standard output abstractions is to specify that they are implemented by our own programs This mechanism is called piping . For example, the following commandspecifies that the standard output for RandomSeq and the standard input stream for Average are the same stream. Filters. For many common tasks, it is convenient to think of each program as a filter that converts a standard input stream to a standard output stream in some way, RangeFilter. java takes two command-line arguments and prints on standard output those numbers from standard input that fall within the specified range. Your operating system also provides a number of filters. For example, the sort filter puts the lines on standard input in sorted order: Another useful filter is more . which reads data from standard input and displays it in your terminal window one screenful at a time. For example, if you type you will see as many numbers as fit in your terminal window, but more will wait for you to hit the space bar before displaying each succeeding screenful. Standard drawing. Now we introduce a simple abstraction for producing drawings as output. We imagine an abstract drawing device capable of drawing lines and points on a two-dimensional canvas. The device is capable of responding to the commands that our programs issue in the form of calls to static methods in StdDraw. The primary interface consists of two kinds of methods: drawing commands that cause the device to take an action (such as drawing a line or drawing a point) and control commands that set parameters such as the pen size or the coordinate scales. Basic drawing commands. We first consider the drawing commands: These methods are nearly self-documenting: StdDraw. line(x0, y0, x1, y1) draws a straight line segment connecting the point ( x 0 . y 0 ) with the point ( x 1 . y 1 ). StdDraw. point(x, y) draws a spot centered on the point ( x . y ). The default coordinate scale is the unit square (all x - and y - coordinates between 0 and 1). The standard implementation displays the canvas in a window on your computers screen, with black lines and points on a white background. Your first drawing. The HelloWorld for graphics programming with StdDraw is to draw a triangle with a point inside. Triangle. java accomplishes this with three calls to StdDraw. line() and one call to StdDraw. point() . Control commands. The default canvas size is 512-by-512 pixels and the default coordinate system is the unit square, but we often want to draw plots at different scales. Also, we often want to draw line segments of different thickness or points of different size from the standard. To accommodate these needs, StdDraw has the following methods:For example, the two-call sequence sets the drawing coordinates to be within a bounding box whose lower-left corner is at ( x 0 . y 0 ) and whose upper-right corner is at ( x 1 . y 1 ). Filtering data to a standard drawing. PlotFilter. java reads a sequence of points defined by ( x . y ) coordinates from standard input and draws a spot at each point. It adopts the convention that the first four numbers on standard input specify the bounding box, so that it can scale the plot. Plotting a function graph. FunctionGraph. java plots the function y sin(4 x ) sin(20 x ) in the interval (0, pi). There are an infinite number of points in the interval, so we have to make do with evaluating the function at a finite number of points within the interval. We sample the function by choosing a set of x - values, then computing y - values by evaluating the function at each x - value. Plotting the function by connecting successive points with lines produces what is known as a piecewise linear approximation. Outline and filled shapes. StdDraw also includes methods to draw circles, rectangles, and arbitrary polygons. Each shape defines an outline. When the method name is just the shape name, that outline is traced by the drawing pen. When the method name begins with filled . the named shape is instead filled solid, not traced. The arguments for circle() define a circle of radius r the arguments for square() define a square of side length 2r centered on the given point and the arguments for polygon() define a sequence of points that we connect by lines, including one from the last point to the first point. Text and color. To annotate or highlight various elements in your drawings, StdDraw includes methods for drawing text, setting the font, and setting the the ink in the pen. In this code, java. awt. Font and java. awt. Color are abstractions that are implemented with non-primitive types that you will learn about in Section 3.1. Until then, we leave the details to StdDraw . The default ink color is black the default font is a 16-point plain Serif font. Double buffering. StdDraw supports a powerful computer graphics feature known as double buffering . When double buffering is enabled by calling enableDoubleBuffering() . all drawing takes place on the offscreen canvas . The offscreen canvas is not displayed it exists only in computer memory. Only when you call show() does your drawing get copied from the offscreen canvas to the onscreen canvas . where it is displayed in the standard drawing window. You can think of double buffering as collecting all of the lines, points, shapes, and text that you tell it to draw, and then drawing them all simultaneously, upon request. One reason to use double buffering is for efficiency when performing a large number of drawing commands. Computer animations. Our most important use of double buffering is to produce computer animations . where we create the illusion of motion by rapidly displaying static drawings. We can produce animations by repeating the following four steps: Clear the offscreen canvas. Draw objects on the offscreen Copy the offscreen canvas to the onscreen canvas. Wait for a short while. In support of these steps, the StdDraw has several methods: The Hello, World program for animation is to produce a black ball that appears to move around on the canvas, bouncing off the boundary according to the laws of elastic collision. Suppose that the ball is at position ( x . y ) and we want to create the impression of having it move to a new position, say ( x 0.01, y 0.02). We do so in four steps: Clear the offscreen canvas to white. Draw a black ball at the new position on the offscreen canvas. Copy the offscreen canvas to the onscreen canvas. Wait for a short while. To create the illusion of movement, BouncingBall. java iterates these steps for a whole sequence of positions of the ball. Images. Our standard draw library supports drawing pictures as well as geometric shapes. The command StdDraw. picture(x, y, filename) plots the image in the given filename (either JPEG, GIF, or PNG format) on the canvas, centered on (x, y). BouncingBallDeluxe. java illustrates an example where the bouncing ball is replaced by an image of a tennis ball. User interaction. Our standard draw library also includes methods so that the user can interact with the window using the mouse. A first example. MouseFollower. java is the HelloWorld of mouse interaction. It draws a blue ball, centered on the location of the mouse. When the user holds down the mouse button, the ball changes color from blue to cyan. A simple attractor. OneSimpleAttractor. java simulates the motion of a blue ball that is attracted to the mouse. It also accounts for a drag force. Many simple attractors. SimpleAttractors. java simulates the motion of 20 blue balls that are attracted to the mouse. It also accounts for a drag force. When the user clicks, the balls disperse randomly. Springs. Springs. java implements a spring system. Standard audio. StdAudio is a library that you can use to play and manipulate sound files. It allows you to play, manipulate and synthesize sound. We introduce some some basic concepts behind one of the oldest and most important areas of computer science and scientific computing: digital signal processing . Concert A. Concert A is a sine wave, scaled to oscillate at a frequency of 440 times per second. The function sin( t ) repeats itself once every 2pi units on the x - axis, so if we measure t in seconds and plot the function sin(2pi t times 440) we get a curve that oscillates 440 times per second. The amplitude ( y - value) corresponds to the volume. We assume it is scaled to be between minus1 and 1. Other notes. A simple mathematical formula characterizes the other notes on the chromatic scale. They are divided equally on a logarithmic (base 2) scale: there are twelve notes on the chromatic scale, and we get the i th note above a given note by multiplying its frequency by the ( i 12)th power of 2. When you double or halve the frequency, you move up or down an octave on the scale. For example 880 hertz is one octave above concert A and 110 hertz is two octaves below concert A. Sampling. For digital sound, we represent a curve by sampling it at regular intervals, in precisely the same manner as when we plot function graphs. We sample sufficiently often that we have an accurate representation of the curvemdasha widely used sampling rate is 44,100 samples per second. It is that simple: we represent sound as an array of numbers (real numbers that are between minus1 and 1).For example, the following code fragment plays concert A for 10 seconds. Play that tune. PlayThatTune. java is an example that shows how easily we can create music with StdAudio . It takes notes from standard input, indexed on the chromatic scale from concert A, and plays them on standard audio. Write a program MaxMin. java that reads in integers (as many as the user enters) from standard input and prints out the maximum and minimum values. Write a program Stats. java that takes an integer command-line argument n . reads n floating-point numbers from standard input, and prints their mean (average value) and sample standard deviation (square root of the sum of the squares of their differences from the average, divided by n minus1). Write a program LongestRun. java that reads in a sequence of integers and prints out both the integer that appears in a longest consecutive run and the length of the run. For example, if the input is 1 2 2 1 5 1 1 7 7 7 7 1 1 . then your program should print Longest run: 4 consecutive 7s . Write a program WordCount. java that reads in text from standard input and prints out the number of words in the text. For the purpose of this exercise, a word is a sequence of non-whitespace characters that is surrounded by whitespace. Write a program Closest. java that takes three floating-point command-line arguments (x, y, z), reads from standard input a sequence of point coordinates ((xi, yi, zi)), and prints the coordinates of the point closest to ((x, y, z)). Recall that the square of the distance between ((x, y, z)) and ((xi, yi, zi)) is ((x - xi)2 (y - yi)2 (z - zi)2). For efficiency, do not use Math. sqrt() or Math. pow() . Given the positions and masses of a sequence of objects, write a program to compute their center-of-mass or centroid. The centroid is the average position of the n objects, weighted by mass. If the positions and masses are given by ( x i . y i . m i ), then the centroid ( x . y . m ) is given by: Write a program Centroid. java that reads in a sequence of positions and masses ( x i . y i . m i ) from standard input and prints out their center of mass ( x . y . m ). Dica. model your program after Average. java. Write a program Checkerboard. java that takes a command-line argument n and plots an n-by-n checkerboard with red and black squares. Color the lower-left square red. Write a program Rose. java that takes a command-line argument n and plots a rose with n petals (if n is odd) or 2n petals (if n is even) by plotting the polar coordinates (r, theta) of the function r sin(n times theta) for theta ranging from 0 to 2pi radians. Below is the desired output for n 4, 7, and 8. Write a program Banner. java that takes a string s from the command line and display it in banner style on the screen, moving from left to right and wrapping back to the beginning of the string as the end is reached. Add a second command-line argument to control the speed. Write a program Circles. java that draws filled circles of random size at random positions in the unit square, producing images like those below. Your program should take four command-line arguments: the number of circles, the probability that each circle is black, the minimum radius, and the maximum radius. Creative Exercises Spirographs. Write a program Spirograph. java that takes three command-line arguments R, r, and a and draws the resulting spirograph. A spirograph (technically, an epicycloid) is a curve formed by rolling a circle of radius r around a larger fixed circle or radius R. If the pen offset from the center of the rolling circle is (ra), then the equation of the resulting curve at time t is given by Such curves were popularized by a best-selling toy that contains discs with gear teeth on the edges and small holes that you could put a pen in to trace spirographs. For a dramatic 3d effect, draw a circular image, e. g. earth. gif instead of a dot, and show it rotating over time. Heres a picture of the resulting spirograph when R 180, r 40, and a 15. Clock. Write a program Clock. java that displays an animation of the second, minute, and hour hands of an analog clock. Use the method StdDraw. show(1000) to update the display roughly once per second. Dica. this may be one of the rare times when you want to use the operator with a double - it works the way you would expect. Oscilloscope. Write a program Oscilloscope. java to simulate the output of an oscilloscope and produce Lissajous patterns. These patterns are named after the French physicist, Jules A. Lissajous, who studied the patterns that arise when two mutually perpendicular periodic disturbances occur simultaneously. Assume that the inputs are sinusoidal, so tha the following parametric equations describe the curve: Take the six parameters A x . w x . theta x . theta y . w y . and theta y from the command line. For example, the first image below has Ax Ay 1, w x 2, w y 3, theta x 20 degrees, theta y 45 degrees. The other has parameters (1, 1, 5, 3, 30, 45) Web Exercises Word and line count. Modify WordCount. java so that reads in text from standard input and prints out the number of characters, words, and lines in the text. Rainfall problem. Write a program Rainfall. java that reads in nonnegative integers (representing rainfall) one at a time until 999999 is entered, and then prints out the average of value (not including 999999). Remove duplicates. Write a program Duplicates. java that reads in a sequence of integers and prints back out the integers, except that it removes repeated values if they appear consecutively. For example, if the input is 1 2 2 1 5 1 1 7 7 7 7 1 1, your program should print out 1 2 1 5 1 7 1. Run length encoding. Write a program RunLengthEncoder. java that encodes a binary input using run length encoding. Write a program RunLengthDecoder. java that decodes a run length encoded message. Head and tail. Write programs Head. java and Tail. java that take an integer command line input N and print out the first or last N lines of the given file. (Print the whole file if it consists of For example the message VENI, VIDI, VICI is converted to YHQL, YLGL, YLFL. Write a program Caesar. java that takes a command-line argument k and applies a Caesar cipher with shift k to a sequence of letters read from standard input. If a letter is not an uppercase letter, simply print it back out. Caesar cipher decoding. How would you decode a message encrypted using a Caesar cipher Hint . you should not need to write any more code. Parity check. A Boolean matrix has the parity property when each row and each column has an even sum. This is a simple type of error-correcting code because if one bit is corrupted in transmission (bit is flipped from 0 to 1 or from 1 to 0) it can be detected and repaired. Heres a 4 x 4 input file which has the parity property: Write a program ParityCheck. java that takes an integer N as a command line input and reads in an N-by-N Boolean matrix from standard input, and outputs if (i) the matrix has the parity property , or (ii) indicates which single corrupted bit (i, j) can be flipped to restore the parity property, or (iii) indicates that the matrix was corrupted (more than two bits would need to be changed to restore the parity property). Use as little internal storage as possible. Hint: you do not even have to store the matrix Takagis function. Plot Takagis function: everywhere continuous, nowhere differentiable. Hitchhiker problem. You are interviewing N candidates for the sole position of American Idol. Every minute you get to see a new candidate, and you have one minute to decide whether or not to declare that person the American Idol. You may not change your mind once you finish interviewing the candidate. Suppose that you can immediately rate each candidate with a single real number between 0 and 1, but of course, you dont know the rating of the candidates not yet seen. Devise a strategy and write a program AmericanIdol that has at least a 25 chance of picking the best candidate (assuming the candidates arrive in random order), reading the 500 data values from standard input. Solution: interview for N2 minutes and record the rating of the best candidate seen so far. In the next N2 minutes, pick the first candidate that has a higher rating than the recorded one. This yields at least a 25 chance since you will get the best candidate if the second best candidate arrives in the first N2 minutes, and the best candidate arrives in the final N2 minutes. This can be improved slightly to 1e 0.36788 by using essentially the same strategy, but switching over at time Ne. Nested diamonds. Write a program Diamonds. java that takes a command line input N and plots N nested squares and diamonds. Below is the desired output for N 3, 4, and 5. Regular polygons. Create a function to plot an N-gon, centered on (x, y) of size length s. Use the function to draws nested polygons like the picture below. Bulging squares. Write a program BulgingSquares. java that draws the following optical illusion from Akiyoshi Kitaoka The center appears to bulge outwards even though all squares are the same size. Spiraling mice. Suppose that N mice that start on the vertices of a regular polygon with N sides, and they each head toward the nearest other mouse (in counterclockwise direction) until they all meet. Write a program to draw the logarithmic spiral paths that they trace out by drawing nested N-gons, rotated and shrunk as in this animation. Spiral. Write a program to draw a spiral like the one below. Globe. Write a program Globe. java that takes a real command-line argument alpha and plots a globe-like pattern with parameter alpha. Plot the polar coordinates (r, theta) of the function f(theta) cos(alpha times theta) for theta ranging from 0 to 7200 degrees. Below is the desired output for alpha 0.8, 0.9, and 0.95. Drawing strings. Write a program RandomText. java that takes a string s and an integer N as command line inputs, and writes the string N times at a random location, and in a random color. 2D random walk. Write a program RandomWalk. java to simulate a 2D random walk and animate the results. Start at the center of a 2N-by-2N grid. The current location is displayed in blue the trail in white. Rotating table. You are seated at a rotating square table (like a lazy Susan), and there are four coins placed in the four corners of the table. Your goal is to flip the coins so that they are either all heads or all tails, at which point a bell rings to notify you that you are done. You may select any two of them, determine their orientation, and (optionally) flip either or both of them over. To make things challenging, you are blindfolded, and the table is spun after each time you select two coins. Write a program RotatingTable. java that initializes the coins to random orientations. Then, it prompts the user to select two positions (1-4), and identifies the orientation of each coin. Next, the user can specify which, if any of the two coins to flip. The process repeats until the user solves the puzzle. Rotating table solver. Write another program RotatingTableSolver. java to solve the rotating table puzzle. One effective strategy is to choose two coins at random and flip them to heads. However, if you get really unlucky, this could take an arbitrary number of steps. Goal: devise a strategy that always solves the puzzle in at most 5 steps. Hex. Hex is a two-player board game popularized by John Nash while a graduate student at Princeton University, and later commercialized by Parker Brothers. It is played on a hexagonal grid in the shape of an 11-by-11 diamond. Write a program Hex. java that draws the board. Projectile motion with drag. Write a program BallisticMotion. java that plots the trajectory of a ball that is shot with velocity v at an angle theta. Account for gravitational and drag forces. Assume that the drag force is proportional to the square of the velocity. Using Newtons equations of motions and the Euler-Cromer method, update the position, velocity, and acceleration according to the following equations: Use G 9.8, C 0.002, and set the initial velocity to 180 and the angle to 60 degrees. Heart. Write a program Heart. java to draw a pink heart: Draw a diamond, then draw two circles to the upper left and upper right sides. Changing square. Write a program that draws a square and changes its color each second. Simple harmonic motion. Repeat the previous exercise, but animate the Lissajous patterns as in this applet. Ex: A B w x w y 1, but at each time t draw 100 (or so) points with phi x ranging from 0 to 720 degrees, and phi x ranging from 0 to 1080 degrees. Bresenhams line drawing algorithm. To plot a line segment from (x1, y1) to (x2, y2) on a monitor, say 1024-by-1024, you need to make a discrete approximation to the continuous line and determine exactly which pixels to turn on. Bresenhams line drawing algorithm is a clever solution that works when the slope is between 0 and 1 and x1 Modify Bresenhams algorithm to handle arbitrary line segments. Millers madness. Write a program Madness. java to plot the parametric equation: where the parameter t is in radians. You should get the following complex picture. Experiment by changing the parameters and produce original pictures. Fays butterfly. Write a program Butterfly. java to plot the polar equation: where the parameter t is in radians. You should get an image like the following butterfly-like figure. Experiment by changing the parameters and produce original pictures. Student database. The file students. txt contains a list of students enrolled in an introductory computer science class at Princeton. The first line contains an integer N that specifies the number of students in the database. Each of the next N lines consists of four pieces of information, separated by whitespace: first name, last name, email address, and section number. The program Students. java reads in the integer N and then N lines of data of standard input, stores the data in four parallel arrays (an integer array for the section number and string arrays for the other fields). Then, the program prints out a list of students in section 4 and 5. Shuffling. In the October 7, 2003 California state runoff election for governor, there were 135 official candidates. To avoid the natural prejudice against candidates whose names appear at the end of the alphabet (Jon W. Zellhoefer), California election officials sought to order the candidates in random order. Write a program program Shuffle. java that takes a command-line argument N, reads in N strings from standard input, and prints them back out in shuffled order. (California decided to randomize the alphabet instead of shuffling the candidates. Using this strategy, not all N possible outcomes are equally likely or even possible For example, two candidates with very similar last names will always end up next to each other.) Reverse. Write a program Reverse. java that reads in an arbitrary number of real values from standard input and prints them in reverse order. Time series analysis. This problem investigates two methods for forecasting in time series analysis. Moving average or exponential smoothing. Polar plots. Create any of these polar plots. Java games. Use StdDraw. java to implement one of the games at javaunlimited. Consider the following program. Suppose the file input. txt contains the following integers: What is the contents of the array a after running the following command High-low. Shuffle a deck of cards, and deal one to the player. Prompt the player to guess whether the next card is higher or lower than the current card. Repeat until player guesses it wrong. Game show. used this. Elastic collisions. Write a program CollidingBalls. java that takes a command-line argument n and plots the trajectories of n bouncing balls that bounce of the walls and each other according to the laws of elastic collisions. Assume all the balls have the same mass. Elastic collisions with obstacles. Each ball should have its own mass. Put a large ball in the center with zero initial velocity. Brownian motion. Statistical outliers. Modify Average. java to print out all the values that are larger than 1.5 standard deviations from the mean. You will need an array to store the values. Optical illusions. Create a Kofka ring or one of the other optical illusions collected by Edward Adelson. Computer animation. In 1995 James Gosling presented a demonstration of Java to Sun executives, illustrating its potential to deliver dynamic and interactive Web content. At the time, web pages were fixed and non-interactive. To demonstrate what the Web could be, Gosling presented applets to rotate 3D molecules, visualize sorting routines, and Duke cart-wheeling across the screen. Java was officially introduced in May 1995 and widely adopted in the technology sector. The Internet would never be the same. Program Duke. java reads in the 17 images T1.gif through T17.gif and produces the animation. To execute on your computer, download the 17 GIF files and put in the same directory as Duke. java . (Alternatively, download and unzip the file duke. zip or duke. jar to extract all 17 GIFs.) Cart-wheeling Duke. Modify Duke. java so that it cartwheels 5 times across the screen, from right to left, wrapping around when it hits the window boundary. Repeat this cart-wheeling cycle 100 times. Dica. after displaying a sequence of 17 frames, move 57 pixels to the left and repeat. Name your program MoreDuke. java. Tac (cat backwards). Write a program Tac. java that reads lines of text from standard input and prints the lines out in reverse order. Game. Implement the game dodge using StdDraw . move a blue disc within the unit square to touch a randomly placed green disc, while avoiding the moving red discs. After each touch, add a new moving red disc. Simple harmonic motion. Create an animation like the one below from Wikipedia of simple harmonic motion. Yin yang. Draw a yin yang using StdDraw. arc() . Twenty questions. Write a program QuestionsTwenty. java that plays 20 questions from the opposite point of view: the user thinks of a number between 1 and a million and the computer makes the guesses. Use binary search to ensure that the computer needs at most 20 guesses. Write a program DeleteX. java that reads in text from standard input and deletes all occurrences of the letter X. To filter a file and remove all Xs, run your program with the following command: Write a program ThreeLargest. java that reads integers from standard input and prints out the three largest inputs. Write a program Pnorm. java that takes a command-line argument p, reads in real numbers from standard input, and prints out their p-norm . The p-norm norm of a vector (x 1 . x N ) is defined to be the pth root of (x 1 p x 2 p . x N p ). Consider the following Java program. Suppose that the file input. txt contains the integers 1 and 1. What does the following command do Modify Add. java so that it re-asks the user to enter two positive integers if the user types in a non-positive integer. Modify TwentyQuestions. java so that it re-asks the user to enter a response if the user types in something other than true or false . Hint: add a do-while loop within the main loop. Nonagram. Write a program to plot a nonagram. Star polygons. Write a program StarPolygon. java that takes two command line inputs p and q, and plots the - star polygon. Complete graph. Write a program to plot that takes an integer N, plots an N-gon, where each vertex lies on a circle of radius 256. Then draw a gray line connecting each pair of vertices. Necker cube. Write a program NeckerCube. java to plot a Necker cube. What happens if you move the StdDraw. clear(Color. BLACK) command to before the beginning of the while loop in BouncingBall. java. Responda . try it and observe a nice woven 3d pattern with the given starting velocity and position. What happens if you change the parameter of StdDraw. show() to 0 or 1000 in BouncingBall. java. Write a program to plot a circular ring of width 10 like the one below using two calls to StdDraw. filledCircle() . Write a program to plot a circular ring of width 10 like the one below using a nested for loop and many calls to StdDraw. point() . Write a program to plot the Olympic rings. Write a program BouncingBallDeluxe. java that embellishes BouncingBall. java by playing a sound effect upon collision with the wall using StdAudio and the sound file pipebang. wav. Last modified on February 20, 2017. Copyright copy 2000ndash2016 Robert Sedgewick and Kevin Wayne. Todos os direitos reservados.

No comments:

Post a Comment