Buscar este blog

jueves, 6 de junio de 2013

SUMAR TRES DIMENSIONES, MIL PERSONAS,LIST SET, TRON, MISTERMIND PROGRAMADO EN JAVA.

EJERCICIO PARA SUMAR UNA MATRIZ DE TRES DIMENSIONES:
package ejercicio130517;
public class matriz3d {
public static void main(String[] args) {
int i, j, k;
int matriz[][][] = new int [3] [3] [3];
for(i = 0; i < matriz.length; i++);{
for(j = 0; j < matriz[i].length; j++);{
for(k = 0; k < matriz[i][j].length; k++);{
matriz[i][j][k] = i;
System.out.println(i);
}}} }}
EJERCICIO PARA CONTABILIZAR "MIL PERSONAS"
package ejercicio130521;
public class milpersonas {
public static void main(String[] args) {
int m = 10;
for (int i=0; i<m; i++){
for (int j=0; j<m; j++){
for (int k=0; k<m; k++){
System.out.println("PERSONA "+i+", FAMILIA DE PERSONA "+j+",AMIGO DE FAMILIA DE PERSONA " +k);
}}}}}
EJERCICIO LIST SET
package ejercicio130522;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;


public class ListSet {

  public static void main(String[] args) {

    //LIST Y SET
      
      ArrayList<String> yes = new ArrayList();
      List<String> yeso = new ArrayList<String>();
      yeso.add("Placido Domingo");
      yeso.add("Cesaria Evora");
      yeso.add("Runa Yacu");
      yeso.add("Placido Domingo");

      // RECORRER MEDIANTE UN FOR
      for (String e:yeso)
        System.out.println(e);
      
      // USO DEL ITERADOR
      Iterator p = yeso.iterator();
      while(p.hasNext()){
        System.out.println(p.next());
      }
     System.out.println();
      Set<String> yeset = new HashSet<String>();
      yeset.add("Placido Domingo");
      yeset.add("Cesaria Evora");
      yeset.add("Runa Yacu");
      yeset.add("Placido Domingo");
      for(String e:yeset)
        System.out.println(e);
}}

TRON DE 2 SERPIENTES EN JAVA CON SALTOS ALEATORIOS
package ejercicio130528;

import java.awt.Image;
import java.util.ArrayList;
public class Animation {
private ArrayList scenes;
private int sceneIndex;
private long movieTime;
private long totalTime;
public Animation(){
scenes = new ArrayList();
totalTime = 0;
start();
}
public synchronized void addScene(Image i, long t){
totalTime += t;
scenes.add(new oneScene(i,totalTime));
}
public synchronized void start(){
movieTime = 0;
sceneIndex = 0;
}
public synchronized void update(long timePassed){
if(scenes.size()>1){
movieTime += timePassed;
if(movieTime>=totalTime){
movieTime = 0;
sceneIndex = 0;
}
while(movieTime > getScene(sceneIndex).endTime){
sceneIndex++;
}
}
}
public synchronized Image getImage(){
if(scenes.size()==0)
{
return null;
}else{
return getScene(sceneIndex).pic;
}
}
private oneScene getScene(int x){
return (oneScene)scenes.get(x);
}
private class oneScene{
Image pic;
long endTime;
public oneScene(Image pic,long endTime){
this.pic = pic;
this.endTime = endTime;
}}}
package ejercicio130528;
import java.awt.*;
import java.awt.image.BufferedImage;

public abstract class Core {

private static final DisplayMode modes[] = 
{
//new DisplayMode(1920,1080,32,0),
new DisplayMode(1680,1050,32,0),
//new DisplayMode(1280,1024,32,0),
new DisplayMode(800,600,32,0),
new DisplayMode(800,600,24,0),
new DisplayMode(800,600,16,0),
new DisplayMode(640,480,32,0),
new DisplayMode(640,480,24,0),
new DisplayMode(640,480,16,0),
};
private boolean running;
protected ScreenManager sm;
public void stop(){
running = false;
}
public void run(){
try{
init();
gameLoop();
}finally{
sm.restoreScreen();
}
}
public void init(){
sm = new ScreenManager();
DisplayMode dm = sm.findFirstCompatibaleMode(modes);
sm.setFullScreen(dm);
Window w = sm.getFullScreenWindow();
w.setFont(new Font("Arial",Font.PLAIN,20));
w.setBackground(Color.WHITE);
w.setForeground(Color.RED);
w.setCursor(w.getToolkit().createCustomCursor(new BufferedImage(3, 3, BufferedImage.TYPE_INT_ARGB), new Point(0, 0),"null")); 
running = true;
}
public void gameLoop(){
long startTime = System.currentTimeMillis();
long cumTime = startTime;
while (running){
long timePassed = System.currentTimeMillis()-cumTime;
cumTime+= timePassed;
update(timePassed);
Graphics2D g = sm.getGraphics();
draw(g);
g.dispose();
sm.update();
try{
Thread.sleep(20);
}catch(Exception ex){}
}
}
public void update(long timePassed){}
public abstract void draw(Graphics2D g);
}
package ejercicio130528;
import java.awt.*;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;

public class ScreenManager {
private GraphicsDevice vc;
public ScreenManager(){
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
vc = e.getDefaultScreenDevice();
}
public DisplayMode[] getCompatibleDisplayModes(){
return vc.getDisplayModes();
}
public DisplayMode findFirstCompatibaleMode(DisplayMode[] modes){
DisplayMode goodModes[] = vc.getDisplayModes();
for(int x = 0; x<modes.length;x++){
for(int y = 0;y<goodModes.length;y++){
if(displayModesMatch(modes[x],goodModes[y])){
return modes[x];
}
}
}
return null;
}
public DisplayMode getCurrentDM(){
return vc.getDisplayMode();
}
public boolean displayModesMatch(DisplayMode m1, DisplayMode m2){
if(m1.getWidth() != m2.getWidth() || m1.getHeight() != m2.getHeight()){
return false;
}
if(m1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m1.getBitDepth() != m2.getBitDepth()){
return false;
}
if(m1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m1.getRefreshRate() != m2.getRefreshRate()){
return false;
}
return true;
}
public void setFullScreen(DisplayMode dm){
JFrame f = new JFrame();
f.setUndecorated(true);
f.setIgnoreRepaint(true);
f.setResizable(false);
vc.setFullScreenWindow(f);
if(dm != null && vc.isDisplayChangeSupported()){
try{
vc.setDisplayMode(dm);
}catch(Exception ex){}
f.createBufferStrategy(2);
}
}
public Graphics2D getGraphics(){
Window w = vc.getFullScreenWindow();
if(w != null){
BufferStrategy bs = w.getBufferStrategy();
return (Graphics2D)bs.getDrawGraphics();
}
else{
return null;
}
}
public void update(){
Window w = vc.getFullScreenWindow();
if(w != null){
BufferStrategy bs = w.getBufferStrategy();
if(!bs.contentsLost()){
bs.show();
}}}
public Window getFullScreenWindow(){
return vc.getFullScreenWindow();}
public int getWidth(){
Window w = vc.getFullScreenWindow();
if(w != null){
return w.getWidth();
}else{
return 0;
}
}
public int getHeight(){
Window w = vc.getFullScreenWindow();
if(w != null){
return w.getHeight();
}else{
return 0;
}}
public void restoreScreen(){
Window w = vc.getFullScreenWindow();
if(w != null){
w.dispose();
}
vc.setFullScreenWindow(null);
}
public BufferedImage createCompatibaleimage(int w, int h, int t){
Window win = vc.getFullScreenWindow();
if(win != null){
GraphicsConfiguration gc = win.getGraphicsConfiguration();
return gc.createCompatibleImage(w,h,t);
}else{
return null;
}}}
package ejercicio130528;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Stroke;
import java.awt.Window;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;

public class yourclass extends Core implements KeyListener, MouseListener,
MouseMotionListener {
int centrex1 = 40;
int centrey1 = 40;
int centrex2 = 600;
int centrey2 = 440;
int currentDirection1 = 1; 
int currentDirection2 = 3;
int moveAmount = 1; //velocidad de las serpientes
ArrayList<Integer> pathx1 = new ArrayList();
ArrayList<Integer> pathy1 = new ArrayList();
ArrayList<Integer> pathx2 = new ArrayList();
ArrayList<Integer> pathy2 = new ArrayList();

public void init() {
super.init();

Window w = sm.getFullScreenWindow();
w.addKeyListener(this);
w.addMouseListener(this);
w.addMouseMotionListener(this);
}

public static void main(String[] args) {
new yourclass().run();
}

public void draw(Graphics2D g) {
switch(currentDirection1){
case 0:
if (centrey1>0){
centrey1-=moveAmount;
} else {
centrey1 = sm.getHeight();
}
break;
case 1:
if (centrex1 < sm.getWidth()){
centrex1+=moveAmount;
} else {
centrex1 = 0;
}
break;
case 2:
if (centrey1 < sm.getHeight()){
centrey1+=moveAmount;
} else {
centrey1 = 0;
}
break;
case 3:
if (centrex1>0){
centrex1-=moveAmount;
} else {
centrex1 = sm.getWidth();
}
break;
}
switch(currentDirection2){
case 0:
if (centrey2>0){
centrey2-=moveAmount;
} else {
centrey2 = sm.getHeight();
}
break;
case 1:
if (centrex2 < sm.getWidth()){
centrex2+=moveAmount;
} else {
centrex2 = 0;
}
break;
case 2:
if (centrey2 < sm.getHeight()){
centrey2+=moveAmount;
} else {
centrey2 = 0;
}
break;
case 3:
if (centrex2>0){
centrex2-=moveAmount;
} else {
centrex2 = sm.getWidth();
}
break;
}
   for (int x = 0;x<pathx1.size();x++){
    if (((centrex1 == pathx1.get(x)) && (centrey1 == pathy1.get(x))) || ((centrex2 == pathx2.get(x)) && (centrey2 == pathy2.get(x))) || ((centrex1 == pathx2.get(x)) && (centrey1 == pathy2.get(x))) || ((centrex2 == pathx1.get(x)) && (centrey2 == pathy1.get(x)))){
    System.exit(0);
    }
   }//colisiones
pathx1.add(centrex1);
pathy1.add(centrey1);
pathx2.add(centrex2);
pathy2.add(centrey2);
g.setColor(Color.BLACK);
g.fillRect(0, 0, sm.getWidth(), sm.getHeight());
for (int x = 0;x<pathx1.size();x++){
int mh= (int)(Math.random()*6 + 1) ;
if (mh%2==0){
}
else {
g.setColor(Color.green);
g.fillRect(pathx1.get(x), pathy1.get(x), 1, 1);
g.setColor(Color.red);
g.fillRect(pathx2.get(x), pathy2.get(x), 1, 1);
}
}
}

public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
if (currentDirection1 != 2){
currentDirection1 = 0;
}
} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
if (currentDirection1 != 0){
currentDirection1 = 2;
}
} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
if (currentDirection1 != 3){
currentDirection1 = 1;
}
} else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
if (currentDirection1 != 1){
currentDirection1 = 3;
}
}
if (e.getKeyCode() == KeyEvent.VK_W){
if (currentDirection2 != 2){
currentDirection2 = 0;
}
} else if (e.getKeyCode() == KeyEvent.VK_S) {
if (currentDirection2 != 0){
currentDirection2 = 2;
}
} else if (e.getKeyCode() == KeyEvent.VK_D) {
if (currentDirection2 != 3){
currentDirection2 = 1;
}
} else if (e.getKeyCode() == KeyEvent.VK_A) {
if (currentDirection2 != 1){
currentDirection2 = 3;
}}}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent arg0) {
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent arg0) {
}
public void mouseExited(MouseEvent arg0) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {

}
}

MISTERMIND DE 5 FICHAS (COLORES O NUMEROS) EN JAVA
package ejercicio130604;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MM {
static String f = "";

public static void main(String[] args) {
int s = 0;
String n = "";
String diff = "";
boolean ans = false;
int[] d = new int[5]; //habia un 4
int[] pos = new int[5]; //habia un 4
pos[0] = (int) (Math.random() * 100);
pos[1] = (int) (Math.random() * 100);
pos[2] = (int) (Math.random() * 100);
pos[3] = (int) (Math.random() * 100);
pos[4] = (int) (Math.random() * 100); //esta línea no estaba
f = readLine("Welcome to MasterMind by Greg Cawthorne!\nIn this game you attempt to crack a code with only the aid of minor hints and you own ingenuity!\nPress enter to begin! ");
f = readLine("Would you like to play with letters (1) or numbers (2)? ");
do {
if (f.equals("letters") || f.equals("1")) {
diff = "letters";
ans = true;
System.out
.println("The code will be made up 5 letters of either R,G,B,Y,P,T "); //habia 4 letters
} else if (f.equals("numbers") || f.equals("2")) {
diff = "numbers";
ans = true;
System.out
.println("The code will be made up of 5 numbers of either 1,2,3,4,5,6 ");   //habia 4 numbers
} else {
f = readLine("Sorry, I didn't quite get that. Would you like to play with letters (1) or numbers (2)? ");
}
} while (ans == false);
for (int x = 0; x <= 4; x++) { //había x<=3
if (pos[x] <= 17) {
d[x] = 1;
} else if (pos[x] <= 34) {
d[x] = 2;
} else if (pos[x] <= 51) {
d[x] = 3;
} else if (pos[x] <= 68) {
d[x] = 4;
} else if (pos[x] <= 85) {
d[x] = 5;
} else if (pos[x] <= 100) {
d[x] = 6;
}}
if (diff.equals("numbers")) {
n = "numbers either 1,2,3,4,5 or 6";
} else if (diff.equals("letters")) {
n = "letters either R,B,G,Y,P or T all caps";
}

System.out.println("The computer has thought of his sequence.");
if(diff == "letters"){
check(d, n, s);
} else if (diff == "numbers"){
check2(n, d, s);
}
}

public static void check(int[] d, String n, int s) {
int count2= 0;
String r = "R";
String b = "B";
String g = "G";
String y = "Y";
String p = "P";
String tq = "T";
String f = "";
boolean z = false;
int v = 0;
f = readLine("Take a guess! ");
if ((f.length() == 5) //había if ((f.length() == 4)
&& (f.charAt(0) == r.charAt(0) || f.charAt(0) == b.charAt(0)
|| f.charAt(0) == g.charAt(0)
|| f.charAt(0) == y.charAt(0)
|| f.charAt(0) == p.charAt(0) || f.charAt(0) == tq
.charAt(0))
&& (f.charAt(1) == r.charAt(0) || f.charAt(1) == b.charAt(0)
|| f.charAt(1) == g.charAt(0)
|| f.charAt(1) == y.charAt(0)
|| f.charAt(1) == p.charAt(0) || f.charAt(1) == tq
.charAt(0))
&& (f.charAt(2) == r.charAt(0) || f.charAt(2) == b.charAt(0)
|| f.charAt(2) == g.charAt(0)
|| f.charAt(2) == y.charAt(0)
|| f.charAt(2) == tq.charAt(0) || f.charAt(2) == p
.charAt(0))
&& (f.charAt(3) == r.charAt(0) || f.charAt(3) == b.charAt(0)
|| f.charAt(3) == g.charAt(0)
|| f.charAt(3) == y.charAt(0)
|| f.charAt(3) == tq.charAt(0) || f.charAt(3) == p.charAt(0))
//estas cuatro lineas de abajo no estaban
&& (f.charAt(4) == r.charAt(0) || f.charAt(4) == b.charAt(0)
|| f.charAt(4) == g.charAt(0)
|| f.charAt(4) == y.charAt(0)
|| f.charAt(4) == tq.charAt(0) || f.charAt(4) == p.charAt(0))
) {
z = true;
System.out.println();
s++;
int chin[] = new int[6];
int chin2[] = new int[6];
char bin[] = new char[6];
bin[0] = 'R'; bin[1] = 'B'; bin[2] = 'G'; bin[3] = 'Y'; bin[4] = 'P'; bin[5] = 'T';
char a[] = new char[5]; //había char a[] = new char[4];
int t[] = new int[5]; //había int t[] = new int[4];
for (int x = 0;x<5;x++){ //había for (int x = 0;x<4;x++){
a[x] = (f.charAt(x));
}
for (int eye = 0; eye< 5;eye++){ //había for (int eye = 0; eye< 4;eye++){
for (int tim = 0; tim<6;tim++){
if (a[eye] == bin[tim]){
t[eye] = tim +1;
}}
}for (int x = 0;x<5;x++){ //había }for (int x = 0;x<4;x++){
if (t[x] == 1){
chin[0] = chin[0]+1;
} else if (t[x] == 2){
chin[1] = chin[1]+1;
} else if (t[x] == 3){
chin[2] = chin[2]+1;
} else if (t[x] == 4){
chin[3] = chin[3]+1;
} else if (t[x] == 5){
chin[4] = chin[4]+1;
} else if (t[x] == 6){
chin[5] = chin[5]+1;
}
if (d[x] == 1){
chin2[0] = chin2[0]+1;
} else if (d[x] == 2){
chin2[1] = chin2[1]+1;
} else if (d[x] == 3){
chin2[2] = chin2[2]+1;
} else if (d[x] == 4){
chin2[3] = chin2[3]+1;
} else if (d[x] == 5){
chin2[4] = chin2[4]+1;
} else if (d[x] == 6){
chin2[5] = chin2[5]+1;
}
}
for (int x = 0; x <= 4; x++) { //había for (int x = 0; x <= 3; x++) {
if (d[x] == t[x]) {
v++;
}
}
for (int x = 0;x<6;x++){
if (chin[x] <= chin2[x]){
count2 = count2 + chin[x];
} else {
count2 = count2 + chin2[x]; }
} count2 = count2 - v;
}
if (z == false) {
System.out.println("Invalid guess. Please guess four " + n
+ " with no spaces. :)");
} else { 
System.out.println("You guessed: " + f);
System.out.println("There are "+v+" letters in the right place,\nand "+count2+" other letters which are right, but in the wrong place.");
}
if (v == 4) {
System.out.print("Well done you cracked the code in " + s
+ " attempts!\n");
do{ f = readLine("Do you want to play again? ");
if (f.equals("yes") || f.equals("y") || f.equals("YES")){
main(null);
} else if (f.equals("no") || f.equals("n") || f.equals("NO")){
System.out.println("I hope you enjoyed MasterMind by Greg Cawthorne!");
System.exit(0);
} else {
System.out.print("Sorry I didn't quite get that. ");
z = false;
}} while (z == false);
} check(d, n, s);
}

public static void check2(String n, int[] d, int s){
int count2 = 0;
boolean z = false;
int v = 0;
String one = "1";
String two = "2";
String three = "3";
String four = "4";
String five = "5";
String six = "6";
f = readLine("Take a guess! ");
//había if((f.length() == 4) && (f.charAt(0) == one.charAt(0) || f.charAt(0) == two.charAt(0) || f.charAt(0) == three.charAt(0)

if((f.length() == 5) && (f.charAt(0) == one.charAt(0) || f.charAt(0) == two.charAt(0) || f.charAt(0) == three.charAt(0)
|| f.charAt(0) == four.charAt(0) || f.charAt(0) == five.charAt(0) || f.charAt(0) == six.charAt(0))
&& (f.charAt(1) == one.charAt(0) || f.charAt(1) == two.charAt(0)
|| f.charAt(1) == three.charAt(0)
|| f.charAt(1) == four.charAt(0)
|| f.charAt(1) == five.charAt(0) || f.charAt(1) == six.charAt(0))
&& (f.charAt(2) == one.charAt(0) || f.charAt(2) == two.charAt(0)
|| f.charAt(2) == three.charAt(0)
|| f.charAt(2) == four.charAt(0)
|| f.charAt(2) == five.charAt(0) || f.charAt(2) == six.charAt(0))
&& (f.charAt(3) == one.charAt(0) || f.charAt(3) == two.charAt(0)
|| f.charAt(3) == three.charAt(0)
|| f.charAt(3) == four.charAt(0)
|| f.charAt(3) == five.charAt(0) || f.charAt(3) == six.charAt(0))
//estas cuatro lineas de abajo no estaban
&& (f.charAt(4) == one.charAt(0) || f.charAt(4) == two.charAt(0)
|| f.charAt(4) == three.charAt(0)
|| f.charAt(4) == four.charAt(0)
|| f.charAt(4) == five.charAt(0) || f.charAt(4) == six.charAt(0))
){
z = true;
System.out.println();
s++;
int chin[] = new int[6];
int chin2[] = new int[6];
String a[] = new String[5]; //había String a[] = new String[4];
int t[] = new int[5]; //había int t[] = new int[4];
for (int x = 0;x<=4;x++){ //había for (int x = 0;x<=3;x++){
a[x] = String.valueOf(f.charAt(x));
t[x] = Integer.parseInt(a[x]);
if (t[x] == 1){
chin[0] = chin[0]+1;
} else if (t[x] == 2){
chin[1] = chin[1]+1;
} else if (t[x] == 3){
chin[2] = chin[2]+1;
} else if (t[x] == 4){
chin[3] = chin[3]+1;
} else if (t[x] == 5){
chin[4] = chin[4]+1;
} else if (t[x] == 6){
chin[5] = chin[5]+1;
}
if (d[x] == 1){
chin2[0] = chin2[0]+1;
} else if (d[x] == 2){
chin2[1] = chin2[1]+1;
} else if (d[x] == 3){
chin2[2] = chin2[2]+1;
} else if (d[x] == 4){
chin2[3] = chin2[3]+1;
} else if (d[x] == 5){
chin2[4] = chin2[4]+1;
} else if (d[x] == 6){
chin2[5] = chin2[5]+1;
}
}
System.out.println("You guessed: " + f);
for (int x = 0; x <= 4; x++) { // había for (int x = 0; x <= 3; x++) {
if (d[x] == t[x]) {
v++;
}
}
for (int x = 0;x<6;x++){
if (chin[x] <= chin2[x]){
count2 = count2 + chin[x];
} else {
count2 = count2 + chin2[x]; }
} count2 = count2 - v;
}
if (z == false) {
System.out.println("Invalid guess. Please guess five " + n
+ " with no spaces. :)");
} else { 
System.out.println("There are "+v+" numbers in the right place,\nand "+count2+" other numbers which are right, but in the wrong place.");
}
if (v == 5) { //había if (v == 4) {
System.out.print("Well done you cracked the code in " + s
+ " attempts!\n");
do{ f = readLine("Do you want to play again? ");
if (f.equals("yes") || f.equals("y") || f.equals("YES")){
main(null);
} else if (f.equals("no") || f.equals("n") || f.equals("NO")){
System.out.println("I hope you enjoyed MasterMind by Greg Cawthorne!");
System.exit(0);
} else {
System.out.print("Sorry I didn't quite get that. ");
z = false;
}} while (z == false);
} check2(n, d, s);
}
public static String readLine(String prompt) {
String input = "";
System.out.print(prompt);
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
try {

input = br.readLine();

} catch (IOException ioe) {
}
return input;
}
}



miércoles, 5 de junio de 2013

Examen SQL

1/ Muestra el nombre del barrio y todos los apartamentos que estén situados en esos barrios cuyo precio sea superior a 350€:

Select b.nombre as 'nombre barrio', a.edificio, a.domicilio, a.piso, a.numeroapto from barrios as b join apartamentos as a on b.codigo=a.codigobarrio where a.precio>350;


2/ Muestra todos los registros y un mensaje que ponga ‘caro’ si el precio de un apartamento supera los 350€

select *, if(precio>350, 'caro', ' ') from barrios as b join apartamentos as a on b.codigo=a.codigobarrio;

3/ Muestra el promedio de los apartamentos agrupados por barrio:

select b.nombre, avg (a.precio) from barrios as b join apartamentos as a on b.cdigo=a.codigobarrio group by b.nombre

4/ Muestra todos los barrios y apartamentos, incluso aquellos barrios en los que no hayan apartamentos:


select * from barrios as b left join apartamentos as a on b.codigo=a.codigobarrio;

5/ Agrupando por nombre de barrio, muestra el nombre del barrio, la media del precio del barrio y cuenta la cantidad de apartamentos que hay en cada barrio.
Además, muestra un mensaje en el que aparezca una nueva media de la siguiente forma: si la media del barrio es mayor a 400€, la nueva media aumentaría un 15%, pero si es menor de 400€, la nueva media aumenta un 10%:


select b.nombre, avg(precio), count(a.numeroapto), if(avg(a.precio)>400, avg(a.precio)+(avg(a.precio)*0.15), avg(a.precio)+(avg(a.precio)*0.1))as medias from barrios as b join apartamentos as a on b.codigo=a.codigobarrio group by b.nombre;

Actividad Final SQL Bases de Datos.



a)    Enunciado:

Una empresa de consultoría de aplicaciones móviles desea poder realizar un informe sobre las descargas de aplicaciones de “iphone” en sus dispositivos.
Para ello necesita saber, qué móvil se ha bajado algo (IMEI), qué modelo de dispositivo es, qué versión tiene, y de qué color es.
Además también quiere almacenar qué aplicación ha sido descargada (nombre), qué tamaño tiene y su coste.
Para finalizar, necesitaría conocer la fecha de descarga de la misma, la cual genera un número automático de orden de descarga.

b)    Diseño Entidad Relación:

c)    Diseño SQL:

create table Iphone(imei varchar(5), modelo varchar (2), version int, color varchar(6), primary key (imei))ENGINE=INNODB;

create table aplicacion(nombre varchar (10), size int, precio int, primary key (nombre))ENGINE=INNODB;

create table descarga(numero int not null auto_increment, imeimovil varchar(5), nombreap varchar (10), fecha date, primary key(numero), index(nombreap), foreign key (imeimovil) references iphone(imei), foreign key (nombreap) references aplicacion(nombre))ENGINE=INNODB;

d)    Pantallazo de las tablas con sus datos:
TABLA IPHONE:
Insert into Iphone values ('11111', '4', 6, 'BLANCO');
Insert into Iphone values ('22222', '4s', 5, 'NEGRO');
Insert into Iphone values ('33333', '4s', 6, 'BLANCO');
Insert into Iphone values ('44444', '5', 6, 'BLANCO');
Insert into Iphone values ('55555', '4s', 6, 'NEGRO');
Insert into Iphone values ('66666', '4', 5, 'NEGRO');
Insert into Iphone values ('77777', '4', 5, 'NEGRO');
Insert into Iphone values ('88888', '5', 6, 'NEGRO');
Insert into Iphone values ('99999', '5', 6, 'NEGRO');

TABLA APLICACION:

insert into aplicacion    values ("instagram", 1, 2);
insert into aplicacion    values ("twitter", 2, 1);
insert into aplicacion    values ("triviados", 5, 3);
insert into aplicacion    values ("candycrush", 6, 5);
insert into aplicacion    values ("shazam", 2, 2);
insert into aplicacion    values ("youtube", 4, 1);
insert into aplicacion    values ("runtastic", 9, 2);
insert into aplicacion    values ("facebook", 3, 1);

TABLA DESCARGA:
insert into descarga (imeimovil, nombreap, fecha) values ('33333', 'facebook', '20130301');
insert into descarga (imeimovil, nombreap, fecha) values ('11111', 'twitter', '20130301');
insert into descarga (imeimovil, nombreap, fecha) values ('55555', 'twitter', '20130305');
insert into descarga (imeimovil, nombreap, fecha) values ('66666', 'facebook', '20130305');
insert into descarga (imeimovil, nombreap, fecha) values ('66666', 'runtastic', '20130306');
insert into descarga (imeimovil, nombreap, fecha) values ('88888', 'runtastic', '20130307');
insert into descarga (imeimovil, nombreap, fecha) values ('88888', 'facebook', '20130308');
insert into descarga (imeimovil, nombreap, fecha) values ('77777', 'facebook', '20130309');
insert into descarga (imeimovil, nombreap, fecha) values ('44444', 'candycrush', '20130310');
insert into descarga (imeimovil, nombreap, fecha) values ('22222', 'youtube', '20130311');
insert into descarga (imeimovil, nombreap, fecha) values ('22222', 'twitter', '20130312');
insert into descarga (imeimovil, nombreap, fecha) values ('44444', 'runtastic', '20130313');
insert into descarga (imeimovil, nombreap, fecha) values ('44444', 'facebook', '20130314');
insert into descarga (imeimovil, nombreap, fecha) values ('44444', 'twitter', '20130315');
insert into descarga (imeimovil, nombreap, fecha) values ('44444', 'instagram', '20130317');
insert into descarga (imeimovil, nombreap, fecha) values ('55555', 'triviados', '20130317');
insert into descarga (imeimovil, nombreap, fecha) values ('55555', 'runtastic', '20130317');
insert into descarga (imeimovil, nombreap, fecha) values ('88888', 'twitter', '20130317');
insert into descarga (imeimovil, nombreap, fecha) values ('77777', 'twitter', '20130317');
insert into descarga (imeimovil, nombreap, fecha) values ('66666', 'twitter', '20130320');
insert into descarga (imeimovil, nombreap, fecha) values ('55555', 'youtube', '20130320');
insert into descarga (imeimovil, nombreap, fecha) values ('99999', 'twitter', '20130321');
insert into descarga (imeimovil, nombreap, fecha) values ('99999', 'shazam', '20130321');
insert into descarga (imeimovil, nombreap, fecha) values ('55555', 'instagram', '20130321');
insert into descarga (imeimovil, nombreap, fecha) values ('55555', 'shazam', '20130322');
insert into descarga (imeimovil, nombreap, fecha) values ('33333', 'twitter', '20130323');
insert into descarga (imeimovil, nombreap, fecha) values ('33333', 'instagram', '20130324');
insert into descarga (imeimovil, nombreap, fecha) values ('33333', 'runtastic', '20130330');
insert into descarga (imeimovil, nombreap, fecha) values ('33333', 'candycrush', '20130330');
insert into descarga (imeimovil, nombreap, fecha) values ('99999', 'youtube', '20130330');

e)     Consultas sobre la base de datos. Deberás utilizar y realizar pantallazos de:
I.-Muestra por pantalla las descargas realizadas por un terminal 4s:
SELECT *
FROM descarga
JOIN Iphone ON Iphone.imei = descarga.imeimovil
WHERE Iphone.modelo = '4s'

II.-Muestra todas las descargas ordenadas por imei:
SELECT *
FROM descarga
ORDER BY imeimovil

III.-Muestra la cantidad de veces que se haya descargado cada una de las aplicaciones:
select count(d.nombreap), (a.nombre) from descarga as d join aplicacion as a on d.nombreap=a.nombre group by a.nombre;

IV.- Cuenta  todas las descargas realizadas ordenadas por modelo de iphone:
select count(d.nombreap), (i.modelo) from descarga as d join Iphone as i on d.imeimovil=i.imei group by i.modelo;

V.-Muestra por pantalla la cantidad de descargas realizadas por cada terminal (por imei):
SELECT COUNT( d.nombreap ) , i.imei FROM descarga AS d JOIN Iphone AS i ON d.imeimovil = i.imei GROUP BY i.imei

VI.-Muestra por pantalla todas las descargas realizadas de cada aplicación mostrando además un mensaje si la aplicación ha sido un éxito (hay más de 4 descargas) .
select count(d.nombreap), (a.nombre), if (count(d.nombreap)>4, 'exito', ' ') as 'exito o no' from descarga as d  join aplicacion as a on d.nombreap=a.nombre group by a.nombre

VII.-Muestra por pantalla el total de dinero gastado por dispositivo.
SELECT d.imeimovil, sum(a.precio)
from aplicacion as a
join descarga as d
on a.nombre=d.nombreap
group by d.imeimovil

VIII.- Muestra por pantalla todas las aplicaciones que empiecen por 't':
select * from aplicacion where nombre like 't%'

IX.-Muestra por pantalla las aplicaciones que hayan sido descargadas mas de tres veces:
select count(nombreap),nombreap from descarga  group by nombreap  having count(nombreap)>3;

X.-Muestra por pantalla todos aquellos terminales que se hayan descargado 'runtastic' o 'facebook', con su fecha de descarga.
select fecha, imeimovil, nombreap from descarga where nombreap='facebook' or nombreap='runtastic'

XI.- Actualiza los precios de 'shazam' a 5.
UPDATE aplicacion SET precio =5 WHERE nombre = 'shazam' 

select * from aplicación


XII.-Muestra por pantalla todas las aplicaciones aunque no hayan sido descargadas ninguna vez:
Para realizar un right join necesito agregar una nueva línea en la tabla aplicación:
insert into aplicacion    values ("amazon", 10, 7);
SELECT *
FROM aplicacion AS a
LEFT JOIN descarga AS d ON a.nombre = d.nombreap