Sandbox: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added Swift task for SplitMix64)
 
(63 intermediate revisions by 10 users not shown)
Line 1: Line 1:
=={{header|Swift}}==
<div class="infobox" style="width: 2in">
{{works with|swift|5.9}}
<big>'''Programming Task'''</big><br />
<syntaxhighlight lang="Swift">
This is a programming task. It lays out a problem which Rosetta Code users are encouraged to solve, using languages they know.
struct SplitMix64: RandomNumberGenerator {
var state: UInt64
init(seed: UInt64) {
state = seed
}
mutating func next() -> UInt64 {
state &+= 0x9e3779b97f4a7c15
var z = state
z = (z ^ (z >> 30)) &* 0xbf58476d1ce4e5b9
z = (z ^ (z >> 27)) &* 0x94d049bb133111eb
return z ^ (z >> 31)
}
mutating func nextFloat() -> Float64 {
Float64(next() >> 11) * 0x1.0p-53
}
}


do {
Code examples should be formatted along the lines of one of the existing [[Help:Example_Programming_Example|prototypes]].{{proggit}}
var split = SplitMix64(seed: 1234567)
</div>
print(split)
<div class="infobox" style="width: 2in">
for _ in 0..<5 {
<big>'''Programming Task'''</big><br />
print(split.next())
This is a programming task. It lays out a problem which Rosetta Code users are encouraged to solve, using languages they know.
}
split = .init(seed: 987654321)
print("\n\(split)")
var counts = [0, 0, 0, 0, 0]
for _ in 0..<100_000 {
let i = Int(split.nextFloat() * 5.0)
counts[i] += 1
}
for (i, count) in zip(0..., counts) {
print("\(i): \(count)")
}
}
</syntaxhighlight>
{{out}}
<pre>
SplitMix64(state: 1234567)
6457827717110365317
3203168211198807973
9817491932198370423
4593380528125082431
16408922859458223821


SplitMix64(state: 987654321)
Code examples should be formatted along the lines of one of the existing [[Help:Example_Programming_Example|prototypes]].{{proggit}}
0: 20027
</div>
1: 19892
<div class="infobox" style="width: 2in">
2: 20073
<big>'''Programming Task'''</big><br />
3: 19978
This is a programming task. It lays out a problem which Rosetta Code users are encouraged to solve, using languages they know.
4: 20030
</pre>


=={{header|Java}}==
Code examples should be formatted along the lines of one of the existing [[Help:Example_Programming_Example|prototypes]].{{proggit}}
</div>
== Can you use a data URL? ==


This is a direct translation of [[Tamagotchi emulator#Go|the Go version]]. As such, the output will be similar if not identical.
[data:text/html,Hello%20World No.]


The code does not use any Java 8+ features so it may function on lower versions.
== What if you transclude a category? ==
<syntaxhighlight lang="Java">
{{Category:Maintenance}}
package com.mt;
-- Okay, the member list doesn't show up. No good.
<div class="infobox" style="width: 2in">
<big>'''Programming Task'''</big><br />
This is a programming task. It lays out a problem which Rosetta Code users are encouraged to solve, using languages they know.


import java.util.ArrayList;
Code examples should be formatted along the lines of one of the existing [[Help:Example_Programming_Example|prototypes]].{{proggit}}
import java.util.List;
</div>
import java.util.Random;
import java.util.Scanner;


class Tamagotchi {
==TITLE==
public String name;
code
public int age,bored,food,poop;
----
== pre test ==
}
<div class="infobox" style="width: 2in">
<big>'''Programming Task'''</big><br />
This is a programming task. It lays out a problem which Rosetta Code users are encouraged to solve, using languages they know.


public class TamagotchiGame {
Code examples should be formatted along the lines of one of the existing [[Help:Example_Programming_Example|prototypes]].{{proggit}}
Tamagotchi tama;//current Tamagotchi
</div>
Random random = new Random(); // pseudo random number generator
<pre style="height:30ex;overflow:scroll">
Test
String[] verbs = {
Another line
"Ask", "Ban", "Bash", "Bite", "Break", "Build",
Yet another line, this time one which clearly is much longer than the width of the browser window, at least assuming normal screen dimensions and font settings, and assuming the browser window is not wider than the screen (which would be impractical anyway).
"Cut", "Dig", "Drag", "Drop", "Drink", "Enjoy",
1
"Eat", "End", "Feed", "Fill", "Force", "Grasp",
2
"Gas", "Get", "Grab", "Grip", "Hoist", "House",
3
"Ice", "Ink", "Join", "Kick", "Leave", "Marry",
4
"Mix", "Nab", "Nail", "Open", "Press", "Quash",
5
"Rub", "Run", "Save", "Snap", "Taste", "Touch",
6
"Use", "Vet", "View", "Wash", "Xerox", "Yield",
7
};
8
9
String[] nouns = {
10
"arms", "bugs", "boots", "bowls", "cabins", "cigars",
11
"dogs", "eggs", "fakes", "flags", "greens", "guests",
12
"hens", "hogs", "items", "jowls", "jewels", "juices",
13
"kits", "logs", "lamps", "lions", "levers", "lemons",
14
"maps", "mugs", "names", "nests", "nights", "nurses",
15
"orbs", "owls", "pages", "posts", "quests", "quotas",
16
"rats", "ribs", "roots", "rules", "salads", "sauces",
17
"toys", "urns", "vines", "words", "waters", "zebras",
18
};
19
20
String[] boredIc ons = {"💤", "💭", "❓"};
21
String[] foodIcons = {"🍼", "🍔", "🍟", "🍰", "🍜"};
</pre>
String[] poopIcons = {"💩"};
==Testing new language tags==
String[] sickIcons1 = {"😄", "😃", "😀", "😊", "😎", "👍"};//ok
===Z80===
String[] sickIcons2 = {"😪", "😥", "😰", "😓"};//ailing
<lang z80>
String[] sickIco ns3 = {"😩", "😫"};//bad
; some random instructions
String[] sickIcons4 = {"😡", "😱"};//very bad
ld a, 80h
String[] sickIcons5 = {"❌", "💀", "👽", "😇"};//dead
ld b, 9Ah
add a, b
String brace(String string) {
adc a, a
return String.format("{ %s }", string);
rst 0 ; reboot :-)
}
</lang>
void create(String name) {
tama = new Tamagotchi();
tama.name = name;
tama.age = 0;
tama.bored = 0;
tama.food = 2;
tama.poop = 0;
}
boolean alive() { // alive if sickness <= 10
return sickness() <= 10;
}
void feed() {
tama.food++;
}
void play() {//may or may not help with boredom
tama.bored = Math.max(0, tama.bored - random.nextInt(2));
}
void talk() {
String verb = verbs[random.nextInt(verbs.length)];
String noun = nouns[random.nextInt(nouns.length)];
System.out.printf("😮 : %s the %s.%n", verb, noun);
tama.bored = Math.max(0, tama.bored - 1);
}
void clean() {
tama.poop = Math.max(0, tama.poop - 1);
}
void idle() {//renamed from wait() due to wait being an existing method from the Object class
tama.age++;
tama.bored += random.nextInt(2);
tama.food = Math.max(0, tama.food - 2);
tama.poop += random.nextInt(2);
}
String status() {// get boredom/food/poop icons
if(alive()) {
StringBuilder b = new StringBuilder(),
f = new StringBuilder(),
p = new StringBuilder();
for(int i = 0; i < tama.bored; i++) {
b.append(boredIcons[random.nextInt(boredIcons.length)]);
}
for(int i = 0; i < tama.food; i++) {
f.append(foodIcons[random.nextInt(foodIcons.length)]);
}
for(int i = 0; i < tama.poop; i++) {
p.append(poopIcons[random.nextInt(poopIcons.length)]);
}
return String.format("%s %s %s", brace(b.toString()), brace(f.toString()), brace(p.toString()));
}
return " R.I.P";
}
//too much boredom/food/poop
int sickness() {
//dies at age 42 at the latest
return tama.poop + tama.bored + Math.max(0, tama.age - 32) + Math.abs(tama.food - 2);
}
//get health status from sickness level
void health() {
int s = sickness();
String icon;
switch(s) {
case 0:
case 1:
case 2:
icon = sickIcons1[random.nextInt(sickIcons1.length)];
break;
case 3:
case 4:
icon = sickIcons2[random.nextInt(sickIcons2.length)];
break;
case 5:
case 6:
icon = sickIcons3[random.nextInt(sickIcons3.length)];
break;
case 7:
case 8:
case 9:
case 10:
icon = sickIcons4[random.nextInt(sickIcons4.length)];
break;
default:
icon = sickIcons5[random.nextInt(sickIcons5.length)];
break;
}
System.out.printf("%s (🎂 %d) %s %d %s%n%n", tama.name, tama.age, icon, s, status());
}
void blurb() {
System.out.println("When the '?' prompt appears, enter an action optionally");
System.out.println("followed by the number of repetitions from 1 to 9.");
System.out.println("If no repetitions are specified, one will be assumed.");
System.out.println("The available options are: feed, play, talk, clean or wait.\n");
}
public static void main(String[] args) {
TamagotchiGame game = new TamagotchiGame();
game.random.setSeed(System.nanoTime());
System.out.println(" TAMAGOTCHI EMULATOR");
System.out.println(" ===================\n");
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the name of your tamagotchi : ");
String name = scanner.nextLine().toLowerCase().trim();
game.create(name);
System.out.printf("%n%s (age) health {bored} {food} {poop}%n%n", "name");
game.health();
game.blurb();
ArrayList<String> commands = new ArrayList<>(List.of("feed", "play", "talk", "clean", "wait"));
int count = 0;
while(game.alive()) {
System.out.print("? ");
String input = scanner.nextLine().toLowerCase().trim();
String[] items = input.split(" ");
if(items.length > 2) continue;
String action = items[0];
if(!commands.contains(action)) {
continue;
}
int reps = 1;
if(items.length == 2) {
reps = Integer.parseInt(items[1]);
} else {
reps = 1;
}
for(int i = 0; i < reps; i++) {
switch(action) {
case "feed":
game.feed();
break;
case "play":
game.play();
break;
case "talk":
game.talk();
break;
case "wait":
game.idle();
break;
}
//simulate a wait on every third (non-wait) action
if(!action.equals("wait")) {
count++;
if(count%3==0) {
game.idle();
}
}
}
game.health();
}
scanner.close();
}
}


===Whitespace===
<lang whitespace>
This may not be a meaningful whitespace
program,
but it's
just a highlighting test
anyway.
</lang>


</syntaxhighlight>
===AviSynth===
{{out}}
<lang avisynth>
<pre>
AviSource("D:\clip.avi")
TAMAGOTCHI EMULATOR
ConvertToYUY2()
===================
PixieDust(5)
</lang>


Enter the name of your tamagotchi : jeremy
===POV-Ray===
<lang povray>
#declare factorial = function(C) { prod(i, 1, C, i) }
#declare A = factorial(5);
sphere{0,A} // a sphere
</lang>


name (age) health {bored} {food} {poop}
===Text===
<lang text>
Is this actually a programming language, or really just plain text?
</lang>


jeremy (🎂 0) 😀 0 { } { 🍜🍜 } { }
===What happens if a language doesn't exist?===
<lang somelanguagethatdoesnotexist>
some code
more code;
* a b -> c /// &a1 ->>> 778
(Probably this is an obfuscated language :-))
</lang>


When the '?' prompt appears, enter an action optionally
===Do the old language-free <nowiki><tt></nowiki>-Tags (for inline code formatting) still work?
followed by the number of repetitions from 1 to 9.
The variable <code>foo</tt> is of type <tt>bar</tt>
If no repetitions are specified, one will be assumed.
The available options are: feed, play, talk, clean or wait.


? feed 4
==Whitespace test with unicode ZERO WIDTH NO-BREAK SPACE character (U+FEFF)==
jeremy (🎂 1) 😥 3 { } { 🍟🍜🍟🍜 } { 💩 }
<lang whitespace>
</lang>
testing


? wait 4
== Impl needed ==
jeremy (🎂 5) 😫 5 { 💭💤 } { } { 💩 }
Tcl pages: {{PAGESINCAT:Tcl}}


? clean 2
Tcl/Omit pages: {{PAGESINCAT:Tcl/Omit}}
jeremy (🎂 6) 😫 6 { 💭💭💭 } { } { 💩 }


? talk 4
Programming tasks: {{PAGESINCAT:Programming Tasks}}
😮 : Grasp the names.
😮 : Vet the greens.
😮 : Grasp the urns.
😮 : Dig the zebras.
jeremy (🎂 7) 😰 3 { } { } { 💩 }


? feed 6
== Property query test ==
jeremy (🎂 9) 😊 2 { } { 🍼🍟 } { 💩💩 }
If I understand the ask syntax correctly, this should turn up a list of all programming languages:
{{#ask: [[Subcategory of::Programming languages]] | default=Apparently I don't understand it correctly.}}


? play 2
Or maybe it works this way:
jeremy (🎂 10) 😩 5 { } { } { 💩💩💩 }
{{#ask: [[Subcategory of::Category:Programming languages]] | default=Doesn't work either.}}


? talk
Maybe this way:
😮 : Touch the eggs.
{{#ask: [[Subcategory of:Programming languages]] | Default=Nor does this.}}
jeremy (🎂 10) 😫 5 { } { } { 💩💩💩 }


</pre>
This should turn up all languages and libraries which provide Graphics:
{{#ask: [[provides::Capability:Graphics]] | default=Or not.}}

This should turn up anything which does ''not'' provide Graphics:
{{#ask: [[provides::!Capability:Graphics]] | default=Unless it doesn't.}}

This should turn up anything which provides first class functions:
{{#ask: [[provides::Capability:First class functions]] | default=I would have hoped.}}

And this should be the intersection of the previous two sets:
{{#ask: [[provides::!Capability:Graphics]] [[provides::Capability:First class functions]] | default=Which shouldn't be empty.}}

Latest revision as of 02:14, 9 May 2024

Swift

Works with: swift version 5.9
struct SplitMix64: RandomNumberGenerator {
    var state: UInt64
    init(seed: UInt64) {
        state = seed
    }
    mutating func next() -> UInt64 {
        state &+= 0x9e3779b97f4a7c15
        var z = state
        z = (z ^ (z >> 30)) &* 0xbf58476d1ce4e5b9
        z = (z ^ (z >> 27)) &* 0x94d049bb133111eb
        return z ^ (z >> 31)
    }
    mutating func nextFloat() -> Float64 {
        Float64(next() >> 11) * 0x1.0p-53
    }
}

do {
    var split = SplitMix64(seed: 1234567)
    print(split)
    for _ in 0..<5 {
        print(split.next())
    }
    split = .init(seed: 987654321)
    print("\n\(split)")
    var counts = [0, 0, 0, 0, 0]
    for _ in 0..<100_000 {
        let i = Int(split.nextFloat() * 5.0)
        counts[i] += 1
    }
    for (i, count) in zip(0..., counts) {
        print("\(i): \(count)")
    }
}
Output:
SplitMix64(state: 1234567)
6457827717110365317
3203168211198807973
9817491932198370423
4593380528125082431
16408922859458223821

SplitMix64(state: 987654321)
0: 20027
1: 19892
2: 20073
3: 19978
4: 20030

Java

This is a direct translation of the Go version. As such, the output will be similar if not identical.

The code does not use any Java 8+ features so it may function on lower versions.

package com.mt;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

class Tamagotchi {
	public String name;
	public int age,bored,food,poop;
	
}

public class TamagotchiGame {
	Tamagotchi tama;//current Tamagotchi
	Random random = new Random(); // pseudo random number generator
	
	String[] verbs = {
			"Ask", "Ban", "Bash", "Bite", "Break", "Build",
		    "Cut", "Dig", "Drag", "Drop", "Drink", "Enjoy",
		    "Eat", "End", "Feed", "Fill", "Force", "Grasp",
		    "Gas", "Get", "Grab", "Grip", "Hoist", "House",
		    "Ice", "Ink", "Join", "Kick", "Leave", "Marry",
		    "Mix", "Nab", "Nail", "Open", "Press", "Quash",
		    "Rub", "Run", "Save", "Snap", "Taste", "Touch",
		    "Use", "Vet", "View", "Wash", "Xerox", "Yield",
	};
	
	String[] nouns = {
			"arms", "bugs", "boots", "bowls", "cabins", "cigars",
		    "dogs", "eggs", "fakes", "flags", "greens", "guests",
		    "hens", "hogs", "items", "jowls", "jewels", "juices",
		    "kits", "logs", "lamps", "lions", "levers", "lemons",
		    "maps", "mugs", "names", "nests", "nights", "nurses",
		    "orbs", "owls", "pages", "posts", "quests", "quotas",
		    "rats", "ribs", "roots", "rules", "salads", "sauces",
		    "toys", "urns", "vines", "words", "waters", "zebras",
	};
	
	String[] boredIc ons = {"💤", "💭", "❓"};
	String[] foodIcons = {"🍼", "🍔", "🍟", "🍰", "🍜"};
	String[] poopIcons = {"💩"};
	String[] sickIcons1 = {"😄", "😃", "😀", "😊", "😎", "👍"};//ok
	String[] sickIcons2 = {"😪", "😥", "😰", "😓"};//ailing
	String[] sickIco ns3 = {"😩", "😫"};//bad
	String[] sickIcons4 = {"😡", "😱"};//very bad
	String[] sickIcons5 = {"❌", "💀", "👽", "😇"};//dead
	
	String brace(String string) {
		return String.format("{ %s }", string);
	}
	
	void create(String name) {
		tama = new Tamagotchi();
		tama.name = name;
		tama.age = 0;
		tama.bored = 0;
		tama.food = 2;
		tama.poop = 0;
	}
	
	boolean alive() { // alive if sickness <= 10
		return sickness() <= 10;
	}
	
	void feed() {
		tama.food++;
	}
	
	void play() {//may or may not help with boredom
		tama.bored = Math.max(0, tama.bored - random.nextInt(2));
	}
	
	void talk() {
		String verb = verbs[random.nextInt(verbs.length)];
		String noun = nouns[random.nextInt(nouns.length)];
		System.out.printf("😮 : %s the %s.%n", verb, noun);
		tama.bored = Math.max(0, tama.bored - 1);
	}
	
	void clean() {
		tama.poop = Math.max(0, tama.poop - 1);
	}
	
	void idle() {//renamed from wait() due to wait being an existing method from the Object class
		tama.age++;
		tama.bored += random.nextInt(2);
		tama.food = Math.max(0, tama.food - 2);
		tama.poop += random.nextInt(2);
	}
	
	String status() {// get boredom/food/poop icons
		if(alive()) {
			StringBuilder b = new StringBuilder(),
					f = new StringBuilder(),
					p = new StringBuilder();
			for(int i = 0; i < tama.bored; i++) {
				b.append(boredIcons[random.nextInt(boredIcons.length)]);
			}
			for(int i = 0; i < tama.food; i++) {
				f.append(foodIcons[random.nextInt(foodIcons.length)]);
			}
			for(int i = 0; i < tama.poop; i++) {
				p.append(poopIcons[random.nextInt(poopIcons.length)]);
			}
			
			return String.format("%s  %s  %s", brace(b.toString()), brace(f.toString()), brace(p.toString()));
		}
		
		return " R.I.P";
	}
	
	//too much boredom/food/poop
	int sickness() {
		//dies at age 42 at the latest
		return tama.poop + tama.bored + Math.max(0, tama.age - 32) + Math.abs(tama.food - 2);
	}
	
	//get health status from sickness level
	void health() {
		int s = sickness();
		String icon;
		switch(s) {
		case 0:
		case 1:
		case 2:
			icon = sickIcons1[random.nextInt(sickIcons1.length)];
			break;
		case 3:
		case 4:
			icon = sickIcons2[random.nextInt(sickIcons2.length)];
			break;
		case 5:
		case 6:
			icon = sickIcons3[random.nextInt(sickIcons3.length)];
			break;
		case 7:
		case 8:
		case 9:
		case 10:
			icon = sickIcons4[random.nextInt(sickIcons4.length)];
			break;
		default:
			icon = sickIcons5[random.nextInt(sickIcons5.length)];
			break;
		}
		
		System.out.printf("%s (🎂 %d)  %s %d  %s%n%n", tama.name, tama.age, icon, s, status());
	}
	
	void blurb() {
		System.out.println("When the '?' prompt appears, enter an action optionally");
		System.out.println("followed by the number of repetitions from 1 to 9.");
		System.out.println("If no repetitions are specified, one will be assumed.");
		System.out.println("The available options are: feed, play, talk, clean or wait.\n");
	}
	
	public static void main(String[] args) {
		TamagotchiGame game = new TamagotchiGame();
		game.random.setSeed(System.nanoTime());
		
		System.out.println("         TAMAGOTCHI EMULATOR");
		System.out.println("         ===================\n");
		
		Scanner scanner = new Scanner(System.in);
		System.out.print("Enter the name of your tamagotchi : ");
		String name = scanner.nextLine().toLowerCase().trim();
		
		game.create(name);
		System.out.printf("%n%s (age) health {bored} {food}    {poop}%n%n", "name");
		game.health();
		game.blurb();
		
		ArrayList<String> commands = new ArrayList<>(List.of("feed", "play", "talk", "clean", "wait"));
		
		int count = 0;
		while(game.alive()) {
			System.out.print("? ");
			String input = scanner.nextLine().toLowerCase().trim();
			String[] items = input.split(" ");
			if(items.length > 2) continue;
			
			String action = items[0];
			if(!commands.contains(action)) {
				continue;
			}
			
			int reps = 1;
			if(items.length == 2) {
				reps = Integer.parseInt(items[1]);
			} else {
				reps = 1;
			}
			
			for(int i = 0; i < reps; i++) {
				switch(action) {
				case "feed":
					game.feed();
					break;
				case "play":
					game.play();
					break;
				case "talk":
					game.talk();
					break;
				case "wait":
					game.idle();
					break;
				}
				
				//simulate a wait on every third (non-wait) action
				if(!action.equals("wait")) {
					count++;
					if(count%3==0) {
						game.idle();
					}
				}
			}
			game.health();
		}
		
		scanner.close();
	}
}
Output:
         TAMAGOTCHI EMULATOR
         ===================

Enter the name of your tamagotchi : jeremy

name (age) health {bored} {food}    {poop}

jeremy (🎂 0)  😀 0  {  }  { 🍜🍜 }  {  }

When the '?' prompt appears, enter an action optionally
followed by the number of repetitions from 1 to 9.
If no repetitions are specified, one will be assumed.
The available options are: feed, play, talk, clean or wait.

? feed 4
jeremy (🎂 1)  😥 3  {  }  { 🍟🍜🍟🍜 }  { 💩 }

? wait 4
jeremy (🎂 5)  😫 5  { 💭💤 }  {  }  { 💩 }

? clean 2
jeremy (🎂 6)  😫 6  { 💭💭💭 }  {  }  { 💩 }

? talk 4
😮 : Grasp the names.
😮 : Vet the greens.
😮 : Grasp the urns.
😮 : Dig the zebras.
jeremy (🎂 7)  😰 3  {  }  {  }  { 💩 }

? feed 6
jeremy (🎂 9)  😊 2  {  }  { 🍼🍟 }  { 💩💩 }

? play 2
jeremy (🎂 10)  😩 5  {  }  {  }  { 💩💩💩 }

? talk
😮 : Touch the eggs.
jeremy (🎂 10)  😫 5  {  }  {  }  { 💩💩💩 }