Buch Cover Buch Cover Buch Cover Buch Cover

Web-Code: - Webcode Help

Bohnenspiel (Felder)

In einer Reihe liegen n Schalen. In jeder Schale kann es Bohnen haben oder die Schale ist leer. Es hat insgesamt weniger Bohnen als Schalen.

Nach folgender Spielvorschrift werden die Bohnen nun ausgetauscht:

  1. Suche die erste Schale mit mehr als einer Bohne. Hat es in jeder Schale maximal eine Bohne, so endet das Spiel
  2. Nimm zwei Bohnen heraus und lege diese in die angrenzenden Schalen. Handelt es sich um die Schale ganz links oder ganz rechts, so ist eine Bohne in die Schale am anderen Ende der Reihe zu legen. (Man könnte sich auch vorstellen, dass die Schalen in einem Kreis angeordnet sind.)
  3. Gehe zurück zu Schritt 1.

Schreiben Sie ein Programm, bei dem der Anwender die Anzahl Schalen und die Anzahlen der Bohnen in jeder Schale eingeben kann. Die Eingabe endet entweder, wenn es eine Bohne weniger als Schalen hat (gleichviele können nicht eingegeben werden) oder es endet, wenn der Anwender die Eingabe der Bohnen beendet.

Nach der Eingabe der Bohnen soll Ihr Programm ausgeben, wie viele Durchgänge (durch Schritt 2 in obigem Algorithmus) nötig sind, um die Bohnen zu verteilen.

0 Kommentare

Bitte melde dich an um einen Kommentar abzugeben

5 Lösung(en)

import java.util.Scanner;

/*@author Till Hardenbicker
 * St. Angela Gymnasium Wipperfürth
 */
public class Bohnenspiel
{
    public static int[] Schale;
    public static int   anzahl_Durchgaenge=0;
   
    public Bohnenspiel() {
    main();
    }
    
    public static void main() {
        belege();
        Durchgaenge();
    }
    
    public static void belege() {
        Scanner sc=new Scanner(System.in);
        
        System.out.println("Wie viele Schalen sollen bereit gestellt werden?");
        Schale = new int[sc.nextInt()];
        System.out.println("Gut, dann verteilen sie mal "+(Schale.length-1)+" Bohnen"+
                            " auf die Schalen!");
        
        int E = 0; //die Summe aller Bohnen, zur Kontrolle. Soll eigentlich ein 
                   //Sigma sein, für Summe. 
        int bohnen_eingabe;
        for(int i=0; i<Schale.length;i++) {
            System.out.print("Schale "+(i+1)+": ");
            bohnen_eingabe = sc.nextInt();
            E=E+bohnen_eingabe;
            if(E>(Schale.length-1)) {
                System.out.println();
                System.err.println("Nein, das ist zu viel. Nochmal neu.");
                belege();
                return;
            }
            else{
                Schale[i]=bohnen_eingabe;
                System.out.println(E+" von "+(Schale.length-1));
            } //Ende der Beleg-Schleife.        
        }
        System.out.print("Notiert wurde "); array_ausgeben();
        System.out.println(); System.out.println("GEHT LOS:");
        System.out.println();
    } //Ende von "Belege"     

    public static void Durchgaenge() {
        boolean ready = true;
        int j =0;
        while(j<Schale.length) { //For-Schleife geht nicht, weil man j später noch braucht
            if(Schale[j]>1) {
                ready = false;
                if(j!=0 && j!=(Schale.length-1)) {
                    Schale[j]=Schale[j]-2;
                    Schale[j-1]++;
                    Schale[j+1]++;
                }
                else if(j==0) {
                    Schale[j]=Schale[j]-2;
                    Schale[Schale.length-1]++;
                    Schale[2]++;
                }
                else if(j==Schale.length-1) {
                    Schale[j]=Schale[j]-2;
                    Schale[0]++;
                    Schale[j-1]++;
                }
            }
        j++;
        } //Ende der Schleife. 
                
                if(!ready){
                    anzahl_Durchgaenge++;
                    System.out.print(j+": "); array_ausgeben();
                    Durchgaenge();    
                }
                else {
                    System.out.println("Fertig nach "+anzahl_Durchgaenge+
                                       " Durchgaengen.");
                }  
    } //Ende der Methode. 
    
    public static void array_ausgeben() {
        for(int k=0; k<Schale.length; k++) {
            System.out.print(Schale[k]+" ");                      
        }
        System.out.println(); 
    }

} //Ende der Klasse Bohnenspiel. 

                

Lösung von: Till Hardenbicker (St. Angela Gymnasium Wipperfürth)

package my.Bohnen;

import java.util.Scanner;


public class BohnenSpiel {
	int[] schalen;
	
	public static void main(String[] args) {
		new BohnenSpiel().top();
	}

	private void top() {
		setUpSpiel();
		spielen();
	}

	/**
	 * Das Spiel
	 */
	private void spielen() {
		int aktSchale = 0;
		printSchalen();
		while(!habenAlleSchalenWenigerAlsZweiBohnen()){
			if(schalen[aktSchale]>=2){
				move(aktSchale);
				aktSchale = 0;
				printSchalen();
			}
			
			aktSchale = aktSchale + 1;
			if(aktSchale==schalen.length){
				aktSchale=0;
			}
		}
		
	}

	/**
	 * Das Spielfeld aufsetzen
	 */
	private void setUpSpiel() {
		int anzBohnen = 0;
		int schalenanz = einlesenInt("Wieviele Schalen hat das Spiel");
		schalen = new int[schalenanz];		
		
		int index = 0;
		while(index<schalen.length){
			boolean inputokey = false;
			
			while(!inputokey){
				int anz = einlesenInt("Wieviele Bohnen hat die Schale"+(index+1)+"(-1 startet das Spiel nochmals)");
				if(anz == -1){
					setUpSpiel();
					return;
				}
				if(anz >= 0 && anzBohnen + anz < schalenanz){
					schalen[index] = anz;
					anzBohnen      = anzBohnen + anz;
					inputokey      = true;
				}
				else{
					System.out.println("Anzahl nicht gestattet");
				}
				
				
			}
			
			index = index + 1;
		}
	}
	
	/**
	 * Gibt die Schalen aus
	 */
	private void printSchalen(){
		int index = 0;
		
		while(index< schalen.length){
			int bohnen = schalen[index];
			System.out.print(bohnen + " ");
			index = index + 1;
		}
		System.out.println("");
	}
	
	/**
	 * Überprüft ob alle Schalen weniger als 2 Bohnen haben
	 * @return
	 */
	private boolean habenAlleSchalenWenigerAlsZweiBohnen(){
		int index = 0;
		
		while(index< schalen.length){
			int bohnen = schalen[index];
			if(bohnen>=2) return false;
			index = index + 1;
		}
		return true;
	}
	
	/**
	 * Verschieben nach Links und nach Rechts(je eine Bohne
	 * @param index von welcher Schale
	 */
	private void move(int index) {
		addBohneLinksVon(index);
		addBohneRechtsVon(index);
	}
	
	/**
	 * Bohnen nach Links verschieben
	 * @param index von welcher Schale
	 */
	private void addBohneLinksVon(int index){
		schalen[index] = schalen[index] - 1;
		if(index==0){
			index = schalen.length;
		}
		index = index - 1;
		schalen[index]= schalen[index] + 1;
	}
	
	/**
	 * Bohnen nach rechts verschieben
	 * @param index von welcher Schale
	 */
	private void addBohneRechtsVon(int index){
		schalen[index] = schalen[index] - 1;
		if(index==schalen.length-1){
			index = -1;
		}
		index = index + 1;
		schalen[index]= schalen[index] + 1;
	}
	
	//--------------------- Input lesen -----------------------
	private Scanner	sc	= new Scanner(System.in);
	
	private int einlesenInt(String frage){
		frageAusgeben(frage);

		while (true) {
			String txt = sc.nextLine();
			try {
				return Integer.parseInt(txt);
			} catch (NumberFormatException e) {
				frageAusgeben(frage);
			}
		}
	}
	
	private static void frageAusgeben(String frage) {
		System.out.println(frage);
	}
}

                

Lösung von: Dominik Kessler (Credit Suisse)

// Autor:				Andy Großhennig
// Solution for task:	Bohnenspiel (Felder)

#include <iostream>
#include <vector>
#include <string>
#include <windows.h>

using namespace std;

// Funcion: Get the amount of bowls and beans and put the beans in the bowls
void startPreparation(vector<int>*i_vecBowls)
{
	int iAmountBowls = 0, iAmountBeans = 0;
	string sBeansinBowls = "";
	string sBeans, sBowl;
	bool bBeans;

	// Loop: Get the amount of bowl
	do
	{
		printf("Wieviele Schalen soll das Spiel haben? (Min: 3) ");
		cin >> iAmountBowls;
	}
	while(iAmountBowls < 3);

	i_vecBowls->resize(iAmountBowls); // Set the size of the bowl vector

	// Loop: Set every value of the bowl vector to zero
	for(vector<int>::iterator i_vec_iBowls = i_vecBowls->begin() ; i_vec_iBowls != i_vecBowls->end() ; i_vec_iBowls++)
	{
		*i_vec_iBowls = 0;
	}

	// Loop: Get the amount of beans
	do
	{
		printf("\nWieviele Bohnen soll das Spiel haben? (2 - %i) ", (iAmountBowls - 1));
		cin >> iAmountBeans;
	}
	while(iAmountBeans < 2 || iAmountBeans >= iAmountBowls);

	printf("\n\n%i Bohnen auf %i Schalen verteilen", iAmountBeans, iAmountBowls);
	printf("\n\nNummer der Schale eingeben gefolgt von einem Leerzeichen und der Anzahl der Bohnen die in die Schale rein sollen\n\n");
	cin.ignore();

	// Loop: Fill the bowls with the beans
	while(iAmountBeans > 0)
	{
		sBowl = "";
		sBeans = "";
		bBeans = false;

		getline(cin, sBeansinBowls);
		
		for(unsigned short shFirst = 0;shFirst < sBeansinBowls.length();shFirst++)
		{
			switch(sBeansinBowls.at(shFirst))
			{
				case ' ':	bBeans = true;
							break;

				default :	if(bBeans == false)
								sBowl += sBeansinBowls.at(shFirst);
							else
								sBeans += sBeansinBowls.at(shFirst);
			}
		}

		i_vecBowls->at((atoi(sBowl.c_str()) - 1 )) += atoi(sBeans.c_str());

		iAmountBeans -= atoi(sBeans.c_str());
		printf("Noch %i Bohnen uebrig\n\n", iAmountBeans);
	}
}

// Function: Show the bowl and the number of round
void showField(vector<int>*i_vecBowls, const int &iRounds, bool *bTwoBeans)
{
	COORD cur={0,0};
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),cur);

	// Loop: Show the bowl and check whether a bowl has more than one bean
	for(vector<int>::iterator i_vec_iBowls = i_vecBowls->begin() ; i_vec_iBowls != i_vecBowls->end() ; i_vec_iBowls++)
	{
		printf("%i  ", *i_vec_iBowls);

		if(*i_vec_iBowls > 1)
			*bTwoBeans = true;
	}

	// Switch: Show start or the number of round
	switch(iRounds)
	{
		case 0: printf("\n\nStart");
				break;
		default:printf("\n\n%i. Runde", iRounds);
	}
	

}

// Function: Manage the game
void play()
{
	vector<int>i_vecBowls;
	int iRounds = 0;
	bool bTwoBeans = false;

	startPreparation(&i_vecBowls);

	system("cls");

	showField(&i_vecBowls, iRounds, &bTwoBeans);

	// Loop: Play until no bowl has more than one bean
	while(bTwoBeans == true)
	{
		bTwoBeans = false;

		for(vector<int>::iterator i_vec_iBowls = i_vecBowls.begin() ; i_vec_iBowls != i_vecBowls.end() ; i_vec_iBowls++)
		{
			if(*i_vec_iBowls < 2)
			{
			}
			else
			{
				if(i_vec_iBowls == i_vecBowls.begin())
				{
					i_vecBowls.at(i_vecBowls.size() - 1) += 1;
					*i_vec_iBowls -= 2;
					*(i_vec_iBowls + 1) += 1;
					break;
				}
				else if(i_vec_iBowls == (i_vecBowls.end() - 1))
				{
					*(i_vec_iBowls - 1) += 1;
					*i_vec_iBowls -= 2;
					i_vecBowls.at(0) += 1;
					break;
				}
				else
				{
					*(i_vec_iBowls - 1) += 1;
					*i_vec_iBowls -= 2;
					*(i_vec_iBowls + 1) += 1;
					break;
				}
			}	
		}

		iRounds++;
		showField(&i_vecBowls, iRounds, &bTwoBeans);
	}

	printf("\n\nNach %i Runden hat keine Schale mehr als Eine Bohne", iRounds);
}

int main()
{
	play();
	
	printf("\n\n");
	system("Pause");
	return 0;
}
                

Lösung von: Andy Großhennig (Bundeswehr)

using System;
using System.Linq;

namespace Bohnenspiel {
	class Program {
		static void Main() {

			//Anzahl Schalen
			int[] schalen = null;
			while (schalen == null || schalen.Length < 2) {
				Console.Clear();
				Console.Write("Schalen>");
				try {
					schalen = new int[
						Convert.ToByte(Console.ReadLine())
						];
				}
				catch (Exception) { }
			}

			//Eingabe Bohnen
			for (int i = 0; 
				i < schalen.Length && schalen.Sum() < schalen.Length - 1;
				i++) {
				Console.Write("Schale {0,3:##0}>", i + 1);
				int temp_anzahl;
				try {
					temp_anzahl = Convert.ToUInt16(Console.ReadLine());
				}
				catch (Exception) {
					i--;
					continue;
				}

				if (schalen.Sum() + temp_anzahl >= schalen.Length)
					schalen[i] = schalen.Length - schalen.Sum() - 1;
				else
					schalen[i] = temp_anzahl;

			}

			//Ausgabe Schalen/Bohnen
			Console.Clear();
			for (int i = 0; i < schalen.Length; i++)
				Console.WriteLine("Schale {0,3:##0} = {1,3:##0}", i + 1, schalen[i]);
			Console.ReadKey(true);

			//Bohnenspiel
			int schritte;
			const int GUARD = 1000000;
			for (schritte = 0; 
				schritte < GUARD && schalen.ToList().Exists(x => x > 1); 
				schritte++) {

				int temp_index = schalen.ToList().IndexOf(schalen.First(x => x > 1));

				schalen[temp_index] -= 2;
				schalen[
					temp_index == 0 ?
					schalen.Length - 1 :
					temp_index - 1
					]++;
				schalen[
					temp_index == schalen.Length - 1 ?
					0 :
					temp_index + 1
					]++;
			}

			//Ausgabe Schritte
			if (schritte == GUARD)
				Console.WriteLine("\nNicht aufgelöst");
			else
				Console.WriteLine("\nSchritte: {0}", schritte);

			Console.ReadKey(true);
		}
	}
}
                

Lösung von: Marcel Kapma ()

var inputCheck = true,
    bowls = [],
    steps = 0,
    i = 0;

function checkBowls() {
  for (var b = 0; b < bowls.length; b++)
    if (bowls[b] > 1) return false;
  return true;
}

function printBowls() { document.write(bowls.join(" - ") + "<br>"); }

function spreadBeans(num) {
  var left = (num == 0) ? bowls.length-1 : num - 1,   // randüberprüfungen
      right = (num == bowls.length-1) ? 0 : num + 1;
  if (bowls[num] >= 2) {
    bowls[num] -= 2;
    bowls[left]++; bowls[right]++;
    printBowls();
    steps++;
  }
  return checkBowls();      // zum sofortigen abbruch der while-schleife (s.u.)
}

// eingabe
do {
  inputCheck = true;
  bowls = prompt("Anzahl der Bohnen in den Schüsseln\n" +
    "(Zahlen getrennt durch Leerzeichen:").split(" ");
  if (eval(bowls.join("+")) >= bowls.length) {
    alert("Es müssen weniger Bohnen als Schalen vorhanden sein.");
    inputCheck = false;
  }
} while (!inputCheck);

document.write("<p>"); printBowls();

// start bohnenspiel
while (!spreadBeans(i))
  i = (i == bowls.length-1) ? 0 : ++i;

document.write("</p><p><b>Versuche: " + steps + "</b></p>"); // lissalanda@gmx.at
                

Lösung von: Lisa Salander (Heidi-Klum-Gymnasium Bottrop)

Verifikation/Checksumme:

Eingabe: 0 2 0 -> 1 Schritt

Eingabe: 0 0 1 3 0 -> 4 Schritte

Aktionen

Bewertung

Durchschnittliche Bewertung:

Eigene Bewertung:
Bitte zuerst anmelden

Meta

Zeit:
Schwierigkeit: k.A.
Webcode: 2f0v-8sr4
Autor: Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch)

Download PDF

Download ZIP

Zu Aufgabenblatt hinzufügen